View.cpp 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "../Graphics/Camera.h"
  24. #include "../Graphics/DebugRenderer.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../Graphics/Geometry.h"
  27. #include "../Graphics/Graphics.h"
  28. #include "../Graphics/GraphicsEvents.h"
  29. #include "../Graphics/GraphicsImpl.h"
  30. #include "../IO/Log.h"
  31. #include "../Graphics/Material.h"
  32. #include "../Graphics/OcclusionBuffer.h"
  33. #include "../Graphics/Octree.h"
  34. #include "../Graphics/Renderer.h"
  35. #include "../Graphics/RenderPath.h"
  36. #include "../Resource/ResourceCache.h"
  37. #include "../Core/Profiler.h"
  38. #include "../Scene/Scene.h"
  39. #include "../Graphics/ShaderVariation.h"
  40. #include "../Graphics/Skybox.h"
  41. #include "../Graphics/Technique.h"
  42. #include "../Graphics/Texture2D.h"
  43. #include "../Graphics/Texture3D.h"
  44. #include "../Graphics/TextureCube.h"
  45. #include "../Graphics/VertexBuffer.h"
  46. #include "../Graphics/View.h"
  47. #include "../UI/UI.h"
  48. #include "../Core/WorkQueue.h"
  49. #include "../DebugNew.h"
  50. namespace Atomic
  51. {
  52. static const Vector3* directions[] =
  53. {
  54. &Vector3::RIGHT,
  55. &Vector3::LEFT,
  56. &Vector3::UP,
  57. &Vector3::DOWN,
  58. &Vector3::FORWARD,
  59. &Vector3::BACK
  60. };
  61. /// %Frustum octree query for shadowcasters.
  62. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  63. {
  64. public:
  65. /// Construct with frustum and query parameters.
  66. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  67. unsigned viewMask = DEFAULT_VIEWMASK) :
  68. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  69. {
  70. }
  71. /// Intersection test for drawables.
  72. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  73. {
  74. while (start != end)
  75. {
  76. Drawable* drawable = *start++;
  77. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  78. (drawable->GetViewMask() & viewMask_))
  79. {
  80. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  81. result_.Push(drawable);
  82. }
  83. }
  84. }
  85. };
  86. /// %Frustum octree query for zones and occluders.
  87. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  88. {
  89. public:
  90. /// Construct with frustum and query parameters.
  91. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  92. unsigned viewMask = DEFAULT_VIEWMASK) :
  93. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  94. {
  95. }
  96. /// Intersection test for drawables.
  97. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  98. {
  99. while (start != end)
  100. {
  101. Drawable* drawable = *start++;
  102. unsigned char flags = drawable->GetDrawableFlags();
  103. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY &&
  104. drawable->IsOccluder())) && (drawable->GetViewMask() & viewMask_))
  105. {
  106. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  107. result_.Push(drawable);
  108. }
  109. }
  110. }
  111. };
  112. /// %Frustum octree query with occlusion.
  113. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  114. {
  115. public:
  116. /// Construct with frustum, occlusion buffer and query parameters.
  117. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  118. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  119. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  120. buffer_(buffer)
  121. {
  122. }
  123. /// Intersection test for an octant.
  124. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  125. {
  126. if (inside)
  127. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  128. else
  129. {
  130. Intersection result = frustum_.IsInside(box);
  131. if (result != OUTSIDE && !buffer_->IsVisible(box))
  132. result = OUTSIDE;
  133. return result;
  134. }
  135. }
  136. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  137. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  138. {
  139. while (start != end)
  140. {
  141. Drawable* drawable = *start++;
  142. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  143. {
  144. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  145. result_.Push(drawable);
  146. }
  147. }
  148. }
  149. /// Occlusion buffer.
  150. OcclusionBuffer* buffer_;
  151. };
  152. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  153. {
  154. View* view = reinterpret_cast<View*>(item->aux_);
  155. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  156. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  157. OcclusionBuffer* buffer = view->occlusionBuffer_;
  158. const Matrix3x4& viewMatrix = view->camera_->GetView();
  159. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  160. Vector3 absViewZ = viewZ.Abs();
  161. unsigned cameraViewMask = view->camera_->GetViewMask();
  162. bool cameraZoneOverride = view->cameraZoneOverride_;
  163. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  164. while (start != end)
  165. {
  166. Drawable* drawable = *start++;
  167. bool batchesUpdated = false;
  168. // If draw distance non-zero, update and check it
  169. float maxDistance = drawable->GetDrawDistance();
  170. if (maxDistance > 0.0f)
  171. {
  172. drawable->UpdateBatches(view->frame_);
  173. batchesUpdated = true;
  174. if (drawable->GetDistance() > maxDistance)
  175. continue;
  176. }
  177. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  178. {
  179. if (!batchesUpdated)
  180. drawable->UpdateBatches(view->frame_);
  181. drawable->MarkInView(view->frame_);
  182. // For geometries, find zone, clear lights and calculate view space Z range
  183. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  184. {
  185. Zone* drawableZone = drawable->GetZone();
  186. if (!cameraZoneOverride && (drawable->IsZoneDirty() || !drawableZone || (drawableZone->GetViewMask() &
  187. cameraViewMask) == 0))
  188. view->FindZone(drawable);
  189. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  190. Vector3 center = geomBox.Center();
  191. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  192. Vector3 edge = geomBox.Size() * 0.5f;
  193. float viewEdgeZ = absViewZ.DotProduct(edge);
  194. float minZ = viewCenterZ - viewEdgeZ;
  195. float maxZ = viewCenterZ + viewEdgeZ;
  196. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  197. drawable->ClearLights();
  198. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  199. if (drawable->GetType() != Skybox::GetTypeStatic())
  200. {
  201. result.minZ_ = Min(result.minZ_, minZ);
  202. result.maxZ_ = Max(result.maxZ_, maxZ);
  203. }
  204. result.geometries_.Push(drawable);
  205. }
  206. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  207. {
  208. Light* light = static_cast<Light*>(drawable);
  209. // Skip lights with zero brightness or black color
  210. if (!light->GetEffectiveColor().Equals(Color::BLACK))
  211. result.lights_.Push(light);
  212. }
  213. }
  214. }
  215. }
  216. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  217. {
  218. View* view = reinterpret_cast<View*>(item->aux_);
  219. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  220. view->ProcessLight(*query, threadIndex);
  221. }
  222. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  223. {
  224. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  225. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  226. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  227. while (start != end)
  228. {
  229. Drawable* drawable = *start++;
  230. // We may leave null pointer holes in the queue if a drawable is found out to require a main thread update
  231. if (drawable)
  232. drawable->UpdateGeometry(frame);
  233. }
  234. }
  235. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  236. {
  237. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  238. queue->SortFrontToBack();
  239. }
  240. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  241. {
  242. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  243. queue->SortBackToFront();
  244. }
  245. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  246. {
  247. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  248. start->litBaseBatches_.SortFrontToBack();
  249. start->litBatches_.SortFrontToBack();
  250. }
  251. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  252. {
  253. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  254. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  255. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  256. }
  257. View::View(Context* context) :
  258. Object(context),
  259. graphics_(GetSubsystem<Graphics>()),
  260. renderer_(GetSubsystem<Renderer>()),
  261. scene_(0),
  262. octree_(0),
  263. camera_(0),
  264. cameraZone_(0),
  265. farClipZone_(0),
  266. renderTarget_(0),
  267. substituteRenderTarget_(0)
  268. {
  269. // Create octree query and scene results vector for each thread
  270. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  271. tempDrawables_.Resize(numThreads);
  272. sceneResults_.Resize(numThreads);
  273. frame_.camera_ = 0;
  274. }
  275. View::~View()
  276. {
  277. }
  278. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  279. {
  280. renderPath_ = viewport->GetRenderPath();
  281. if (!renderPath_)
  282. return false;
  283. drawDebug_ = viewport->GetDrawDebug();
  284. hasScenePasses_ = false;
  285. lightVolumeCommand_ = 0;
  286. // Make sure that all necessary batch queues exist
  287. scenePasses_.Clear();
  288. noStencil_ = false;
  289. #ifdef ATOMIC_OPENGL
  290. #ifdef GL_ES_VERSION_2_0
  291. // On OpenGL ES we assume a stencil is not available or would not give a good performance, and disable light stencil
  292. // optimizations in any case
  293. noStencil_ = true;
  294. #else
  295. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  296. {
  297. const RenderPathCommand& command = renderPath_->commands_[i];
  298. if (!command.enabled_)
  299. continue;
  300. if (command.depthStencilName_.Length())
  301. {
  302. // Using a readable depth texture will disable light stencil optimizations on OpenGL, as for compatibility reasons
  303. // we are using a depth format without stencil channel
  304. noStencil_ = true;
  305. break;
  306. }
  307. }
  308. #endif
  309. #endif
  310. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  311. {
  312. const RenderPathCommand& command = renderPath_->commands_[i];
  313. if (!command.enabled_)
  314. continue;
  315. if (command.type_ == CMD_SCENEPASS)
  316. {
  317. hasScenePasses_ = true;
  318. ScenePassInfo info;
  319. info.pass_ = command.pass_;
  320. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  321. info.markToStencil_ = !noStencil_ && command.markToStencil_;
  322. info.vertexLights_ = command.vertexLights_;
  323. // Check scenepass metadata for defining custom passes which interact with lighting
  324. if (!command.metadata_.Empty())
  325. {
  326. if (command.metadata_ == "gbuffer")
  327. gBufferPassName_ = command.pass_;
  328. else if (command.metadata_ == "base" && command.pass_ != "base")
  329. {
  330. basePassName_ = command.pass_;
  331. litBasePassName_ = "lit" + command.pass_;
  332. }
  333. else if (command.metadata_ == "alpha" && command.pass_ != "alpha")
  334. {
  335. alphaPassName_ = command.pass_;
  336. litAlphaPassName_ = "lit" + command.pass_;
  337. }
  338. }
  339. HashMap<StringHash, BatchQueue>::Iterator j = batchQueues_.Find(command.pass_);
  340. if (j == batchQueues_.End())
  341. j = batchQueues_.Insert(Pair<StringHash, BatchQueue>(command.pass_, BatchQueue()));
  342. info.batchQueue_ = &j->second_;
  343. scenePasses_.Push(info);
  344. }
  345. // Allow a custom forward light pass
  346. else if (command.type_ == CMD_FORWARDLIGHTS && !command.pass_.Empty())
  347. lightPassName_ = command.pass_;
  348. }
  349. scene_ = viewport->GetScene();
  350. camera_ = viewport->GetCamera();
  351. octree_ = 0;
  352. // Get default zone first in case we do not have zones defined
  353. cameraZone_ = farClipZone_ = renderer_->GetDefaultZone();
  354. if (hasScenePasses_)
  355. {
  356. if (!scene_ || !camera_ || !camera_->IsEnabledEffective())
  357. return false;
  358. // If scene is loading scene content asynchronously, it is incomplete and should not be rendered
  359. if (scene_->IsAsyncLoading() && scene_->GetAsyncLoadMode() > LOAD_RESOURCES_ONLY)
  360. return false;
  361. octree_ = scene_->GetComponent<Octree>();
  362. if (!octree_)
  363. return false;
  364. // Do not accept view if camera projection is illegal
  365. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  366. if (!camera_->IsProjectionValid())
  367. return false;
  368. }
  369. cameraNode_ = camera_ ? camera_->GetNode() : (Node*)0;
  370. renderTarget_ = renderTarget;
  371. gBufferPassName_ = StringHash();
  372. basePassName_ = PASS_BASE;
  373. alphaPassName_ = PASS_ALPHA;
  374. lightPassName_ = PASS_LIGHT;
  375. litBasePassName_ = PASS_LITBASE;
  376. litAlphaPassName_ = PASS_LITALPHA;
  377. // Go through commands to check for deferred rendering and other flags
  378. deferred_ = false;
  379. deferredAmbient_ = false;
  380. useLitBase_ = false;
  381. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  382. {
  383. const RenderPathCommand& command = renderPath_->commands_[i];
  384. if (!command.enabled_)
  385. continue;
  386. // Check if ambient pass and G-buffer rendering happens at the same time
  387. if (command.type_ == CMD_SCENEPASS && command.outputNames_.Size() > 1)
  388. {
  389. if (CheckViewportWrite(command))
  390. deferredAmbient_ = true;
  391. }
  392. else if (command.type_ == CMD_LIGHTVOLUMES)
  393. {
  394. lightVolumeCommand_ = &command;
  395. deferred_ = true;
  396. }
  397. else if (command.type_ == CMD_FORWARDLIGHTS)
  398. useLitBase_ = command.useLitBase_;
  399. }
  400. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  401. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  402. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  403. const IntRect& rect = viewport->GetRect();
  404. if (rect != IntRect::ZERO)
  405. {
  406. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  407. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  408. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  409. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  410. }
  411. else
  412. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  413. viewSize_ = viewRect_.Size();
  414. rtSize_ = IntVector2(rtWidth, rtHeight);
  415. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  416. #ifdef ATOMIC_OPENGL
  417. if (renderTarget_)
  418. {
  419. viewRect_.bottom_ = rtHeight - viewRect_.top_;
  420. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  421. }
  422. #endif
  423. drawShadows_ = renderer_->GetDrawShadows();
  424. materialQuality_ = renderer_->GetMaterialQuality();
  425. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  426. minInstances_ = renderer_->GetMinInstances();
  427. // Set possible quality overrides from the camera
  428. unsigned viewOverrideFlags = camera_ ? camera_->GetViewOverrideFlags() : VO_NONE;
  429. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  430. materialQuality_ = QUALITY_LOW;
  431. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  432. drawShadows_ = false;
  433. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  434. maxOccluderTriangles_ = 0;
  435. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  436. if (viewSize_.y_ > viewSize_.x_ * 4)
  437. maxOccluderTriangles_ = 0;
  438. return true;
  439. }
  440. void View::Update(const FrameInfo& frame)
  441. {
  442. frame_.camera_ = camera_;
  443. frame_.timeStep_ = frame.timeStep_;
  444. frame_.frameNumber_ = frame.frameNumber_;
  445. frame_.viewSize_ = viewSize_;
  446. using namespace BeginViewUpdate;
  447. VariantMap& eventData = GetEventDataMap();
  448. eventData[P_VIEW] = this;
  449. eventData[P_SURFACE] = renderTarget_;
  450. eventData[P_TEXTURE] = (renderTarget_ ? renderTarget_->GetParentTexture() : 0);
  451. eventData[P_SCENE] = scene_;
  452. eventData[P_CAMERA] = camera_;
  453. renderer_->SendEvent(E_BEGINVIEWUPDATE, eventData);
  454. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  455. // Clear buffers, geometry, light, occluder & batch list
  456. renderTargets_.Clear();
  457. geometries_.Clear();
  458. lights_.Clear();
  459. zones_.Clear();
  460. occluders_.Clear();
  461. vertexLightQueues_.Clear();
  462. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  463. i->second_.Clear(maxSortedInstances);
  464. if (hasScenePasses_ && (!camera_ || !octree_))
  465. {
  466. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  467. return;
  468. }
  469. // Set automatic aspect ratio if required
  470. if (camera_ && camera_->GetAutoAspectRatio())
  471. camera_->SetAspectRatioInternal((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  472. GetDrawables();
  473. GetBatches();
  474. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  475. }
  476. void View::Render()
  477. {
  478. if (hasScenePasses_ && (!octree_ || !camera_))
  479. return;
  480. // Actually update geometry data now
  481. UpdateGeometries();
  482. // Allocate screen buffers as necessary
  483. AllocateScreenBuffers();
  484. // Forget parameter sources from the previous view
  485. graphics_->ClearParameterSources();
  486. // If stream offset is supported, write all instance transforms to a single large buffer
  487. // Else we must lock the instance buffer for each batch group
  488. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  489. PrepareInstancingBuffer();
  490. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  491. // again to ensure correct projection will be used
  492. if (camera_)
  493. {
  494. if (camera_->GetAutoAspectRatio())
  495. camera_->SetAspectRatioInternal((float)(viewSize_.x_) / (float)(viewSize_.y_));
  496. }
  497. // Bind the face selection and indirection cube maps for point light shadows
  498. #ifndef GL_ES_VERSION_2_0
  499. if (renderer_->GetDrawShadows())
  500. {
  501. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  502. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  503. }
  504. #endif
  505. if (renderTarget_)
  506. {
  507. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  508. // as a render texture produced on Direct3D9
  509. #ifdef ATOMIC_OPENGL
  510. if (camera_)
  511. camera_->SetFlipVertical(true);
  512. #endif
  513. }
  514. // Render
  515. ExecuteRenderPathCommands();
  516. // After executing all commands, reset rendertarget & state for debug geometry rendering
  517. // Use the last rendertarget (before blitting) so that OpenGL deferred rendering can have benefit of proper depth buffer
  518. // values; after a blit to backbuffer the same depth buffer would not be available any longer
  519. graphics_->SetRenderTarget(0, currentRenderTarget_);
  520. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  521. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  522. graphics_->SetDepthStencil(GetDepthStencil(currentRenderTarget_));
  523. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  524. IntRect viewport = (currentRenderTarget_ == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  525. rtSizeNow.y_);
  526. graphics_->SetViewport(viewport);
  527. graphics_->SetFillMode(FILL_SOLID);
  528. graphics_->SetClipPlane(false);
  529. graphics_->SetColorWrite(true);
  530. graphics_->SetDepthBias(0.0f, 0.0f);
  531. graphics_->SetScissorTest(false);
  532. graphics_->SetStencilTest(false);
  533. graphics_->ResetStreamFrequencies();
  534. // Draw the associated debug geometry now if enabled
  535. if (drawDebug_ && octree_ && camera_)
  536. {
  537. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  538. if (debug && debug->IsEnabledEffective())
  539. {
  540. debug->SetView(camera_);
  541. debug->Render();
  542. }
  543. }
  544. #ifdef ATOMIC_OPENGL
  545. if (camera_)
  546. camera_->SetFlipVertical(false);
  547. #endif
  548. // Run framebuffer blitting if necessary
  549. if (currentRenderTarget_ != renderTarget_)
  550. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()), renderTarget_, true);
  551. // "Forget" the scene, camera, octree and zone after rendering
  552. scene_ = 0;
  553. camera_ = 0;
  554. octree_ = 0;
  555. cameraZone_ = 0;
  556. farClipZone_ = 0;
  557. occlusionBuffer_ = 0;
  558. frame_.camera_ = 0;
  559. }
  560. Graphics* View::GetGraphics() const
  561. {
  562. return graphics_;
  563. }
  564. Renderer* View::GetRenderer() const
  565. {
  566. return renderer_;
  567. }
  568. void View::SetGlobalShaderParameters()
  569. {
  570. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  571. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  572. if (scene_)
  573. {
  574. float elapsedTime = scene_->GetElapsedTime();
  575. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  576. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  577. }
  578. }
  579. void View::SetCameraShaderParameters(Camera* camera, bool setProjection)
  580. {
  581. if (!camera)
  582. return;
  583. Matrix3x4 cameraEffectiveTransform = camera->GetEffectiveWorldTransform();
  584. graphics_->SetShaderParameter(VSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  585. graphics_->SetShaderParameter(VSP_CAMERAROT, cameraEffectiveTransform.RotationMatrix());
  586. graphics_->SetShaderParameter(PSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  587. float nearClip = camera->GetNearClip();
  588. float farClip = camera->GetFarClip();
  589. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  590. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  591. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  592. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  593. Vector4 depthMode = Vector4::ZERO;
  594. if (camera->IsOrthographic())
  595. {
  596. depthMode.x_ = 1.0f;
  597. #ifdef ATOMIC_OPENGL
  598. depthMode.z_ = 0.5f;
  599. depthMode.w_ = 0.5f;
  600. #else
  601. depthMode.z_ = 1.0f;
  602. #endif
  603. }
  604. else
  605. depthMode.w_ = 1.0f / camera->GetFarClip();
  606. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  607. Vector4 depthReconstruct(farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), camera->IsOrthographic() ? 1.0f :
  608. 0.0f, camera->IsOrthographic() ? 0.0f : 1.0f);
  609. graphics_->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  610. Vector3 nearVector, farVector;
  611. camera->GetFrustumSize(nearVector, farVector);
  612. graphics_->SetShaderParameter(VSP_FRUSTUMSIZE, farVector);
  613. if (setProjection)
  614. {
  615. Matrix4 projection = camera->GetProjection();
  616. #ifdef ATOMIC_OPENGL
  617. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  618. float constantBias = 2.0f * graphics_->GetDepthConstantBias();
  619. projection.m22_ += projection.m32_ * constantBias;
  620. projection.m23_ += projection.m33_ * constantBias;
  621. #endif
  622. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * camera->GetView());
  623. }
  624. }
  625. void View::SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect)
  626. {
  627. float texWidth = (float)texSize.x_;
  628. float texHeight = (float)texSize.y_;
  629. float widthRange = 0.5f * viewRect.Width() / texWidth;
  630. float heightRange = 0.5f * viewRect.Height() / texHeight;
  631. #ifdef ATOMIC_OPENGL
  632. Vector4 bufferUVOffset(((float)viewRect.left_) / texWidth + widthRange,
  633. 1.0f - (((float)viewRect.top_) / texHeight + heightRange), widthRange, heightRange);
  634. #else
  635. Vector4 bufferUVOffset((0.5f + (float)viewRect.left_) / texWidth + widthRange,
  636. (0.5f + (float)viewRect.top_) / texHeight + heightRange, widthRange, heightRange);
  637. #endif
  638. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  639. float invSizeX = 1.0f / texWidth;
  640. float invSizeY = 1.0f / texHeight;
  641. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(invSizeX, invSizeY, 0.0f, 0.0f));
  642. }
  643. void View::GetDrawables()
  644. {
  645. if (!octree_ || !camera_)
  646. return;
  647. PROFILE(GetDrawables);
  648. WorkQueue* queue = GetSubsystem<WorkQueue>();
  649. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  650. // Get zones and occluders first
  651. {
  652. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, camera_->GetViewMask());
  653. octree_->GetDrawables(query);
  654. }
  655. highestZonePriority_ = M_MIN_INT;
  656. int bestPriority = M_MIN_INT;
  657. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  658. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  659. {
  660. Drawable* drawable = *i;
  661. unsigned char flags = drawable->GetDrawableFlags();
  662. if (flags & DRAWABLE_ZONE)
  663. {
  664. Zone* zone = static_cast<Zone*>(drawable);
  665. zones_.Push(zone);
  666. int priority = zone->GetPriority();
  667. if (priority > highestZonePriority_)
  668. highestZonePriority_ = priority;
  669. if (priority > bestPriority && zone->IsInside(cameraPos))
  670. {
  671. cameraZone_ = zone;
  672. bestPriority = priority;
  673. }
  674. }
  675. else
  676. occluders_.Push(drawable);
  677. }
  678. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  679. cameraZoneOverride_ = cameraZone_->GetOverride();
  680. if (!cameraZoneOverride_)
  681. {
  682. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  683. bestPriority = M_MIN_INT;
  684. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  685. {
  686. int priority = (*i)->GetPriority();
  687. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  688. {
  689. farClipZone_ = *i;
  690. bestPriority = priority;
  691. }
  692. }
  693. }
  694. if (farClipZone_ == renderer_->GetDefaultZone())
  695. farClipZone_ = cameraZone_;
  696. // If occlusion in use, get & render the occluders
  697. occlusionBuffer_ = 0;
  698. if (maxOccluderTriangles_ > 0)
  699. {
  700. UpdateOccluders(occluders_, camera_);
  701. if (occluders_.Size())
  702. {
  703. PROFILE(DrawOcclusion);
  704. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  705. DrawOccluders(occlusionBuffer_, occluders_);
  706. }
  707. }
  708. // Get lights and geometries. Coarse occlusion for octants is used at this point
  709. if (occlusionBuffer_)
  710. {
  711. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  712. DRAWABLE_LIGHT, camera_->GetViewMask());
  713. octree_->GetDrawables(query);
  714. }
  715. else
  716. {
  717. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY |
  718. DRAWABLE_LIGHT, camera_->GetViewMask());
  719. octree_->GetDrawables(query);
  720. }
  721. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  722. {
  723. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  724. {
  725. PerThreadSceneResult& result = sceneResults_[i];
  726. result.geometries_.Clear();
  727. result.lights_.Clear();
  728. result.minZ_ = M_INFINITY;
  729. result.maxZ_ = 0.0f;
  730. }
  731. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  732. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  733. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  734. // Create a work item for each thread
  735. for (int i = 0; i < numWorkItems; ++i)
  736. {
  737. SharedPtr<WorkItem> item = queue->GetFreeItem();
  738. item->priority_ = M_MAX_UNSIGNED;
  739. item->workFunction_ = CheckVisibilityWork;
  740. item->aux_ = this;
  741. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  742. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  743. end = start + drawablesPerItem;
  744. item->start_ = &(*start);
  745. item->end_ = &(*end);
  746. queue->AddWorkItem(item);
  747. start = end;
  748. }
  749. queue->Complete(M_MAX_UNSIGNED);
  750. }
  751. // Combine lights, geometries & scene Z range from the threads
  752. geometries_.Clear();
  753. lights_.Clear();
  754. minZ_ = M_INFINITY;
  755. maxZ_ = 0.0f;
  756. if (sceneResults_.Size() > 1)
  757. {
  758. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  759. {
  760. PerThreadSceneResult& result = sceneResults_[i];
  761. geometries_.Push(result.geometries_);
  762. lights_.Push(result.lights_);
  763. minZ_ = Min(minZ_, result.minZ_);
  764. maxZ_ = Max(maxZ_, result.maxZ_);
  765. }
  766. }
  767. else
  768. {
  769. // If just 1 thread, copy the results directly
  770. PerThreadSceneResult& result = sceneResults_[0];
  771. minZ_ = result.minZ_;
  772. maxZ_ = result.maxZ_;
  773. Swap(geometries_, result.geometries_);
  774. Swap(lights_, result.lights_);
  775. }
  776. if (minZ_ == M_INFINITY)
  777. minZ_ = 0.0f;
  778. // Sort the lights to brightest/closest first, and per-vertex lights first so that per-vertex base pass can be evaluated first
  779. for (unsigned i = 0; i < lights_.Size(); ++i)
  780. {
  781. Light* light = lights_[i];
  782. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  783. light->SetLightQueue(0);
  784. }
  785. Sort(lights_.Begin(), lights_.End(), CompareLights);
  786. }
  787. void View::GetBatches()
  788. {
  789. if (!octree_ || !camera_)
  790. return;
  791. nonThreadedGeometries_.Clear();
  792. threadedGeometries_.Clear();
  793. WorkQueue* queue = GetSubsystem<WorkQueue>();
  794. PODVector<Light*> vertexLights;
  795. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassName_) ? &batchQueues_[alphaPassName_] : (BatchQueue*)0;
  796. // Process lit geometries and shadow casters for each light
  797. {
  798. PROFILE(ProcessLights);
  799. lightQueryResults_.Resize(lights_.Size());
  800. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  801. {
  802. SharedPtr<WorkItem> item = queue->GetFreeItem();
  803. item->priority_ = M_MAX_UNSIGNED;
  804. item->workFunction_ = ProcessLightWork;
  805. item->aux_ = this;
  806. LightQueryResult& query = lightQueryResults_[i];
  807. query.light_ = lights_[i];
  808. item->start_ = &query;
  809. queue->AddWorkItem(item);
  810. }
  811. // Ensure all lights have been processed before proceeding
  812. queue->Complete(M_MAX_UNSIGNED);
  813. }
  814. // Build light queues and lit batches
  815. {
  816. PROFILE(GetLightBatches);
  817. // Preallocate light queues: per-pixel lights which have lit geometries
  818. unsigned numLightQueues = 0;
  819. unsigned usedLightQueues = 0;
  820. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  821. {
  822. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  823. ++numLightQueues;
  824. }
  825. lightQueues_.Resize(numLightQueues);
  826. maxLightsDrawables_.Clear();
  827. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  828. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  829. {
  830. LightQueryResult& query = *i;
  831. // If light has no affected geometries, no need to process further
  832. if (query.litGeometries_.Empty())
  833. continue;
  834. Light* light = query.light_;
  835. // Per-pixel light
  836. if (!light->GetPerVertex())
  837. {
  838. unsigned shadowSplits = query.numSplits_;
  839. // Initialize light queue and store it to the light so that it can be found later
  840. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  841. light->SetLightQueue(&lightQueue);
  842. lightQueue.light_ = light;
  843. lightQueue.shadowMap_ = 0;
  844. lightQueue.litBaseBatches_.Clear(maxSortedInstances);
  845. lightQueue.litBatches_.Clear(maxSortedInstances);
  846. lightQueue.volumeBatches_.Clear();
  847. // Allocate shadow map now
  848. if (shadowSplits > 0)
  849. {
  850. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  851. // If did not manage to get a shadow map, convert the light to unshadowed
  852. if (!lightQueue.shadowMap_)
  853. shadowSplits = 0;
  854. }
  855. // Setup shadow batch queues
  856. lightQueue.shadowSplits_.Resize(shadowSplits);
  857. for (unsigned j = 0; j < shadowSplits; ++j)
  858. {
  859. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  860. Camera* shadowCamera = query.shadowCameras_[j];
  861. shadowQueue.shadowCamera_ = shadowCamera;
  862. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  863. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  864. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  865. // Setup the shadow split viewport and finalize shadow camera parameters
  866. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  867. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  868. // Loop through shadow casters
  869. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  870. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  871. {
  872. Drawable* drawable = *k;
  873. // If drawable is not in actual view frustum, mark it in view here and check its geometry update type
  874. if (!drawable->IsInView(frame_, true))
  875. {
  876. drawable->MarkInView(frame_.frameNumber_, 0);
  877. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  878. if (type == UPDATE_MAIN_THREAD)
  879. nonThreadedGeometries_.Push(drawable);
  880. else if (type == UPDATE_WORKER_THREAD)
  881. threadedGeometries_.Push(drawable);
  882. }
  883. Zone* zone = GetZone(drawable);
  884. const Vector<SourceBatch>& batches = drawable->GetBatches();
  885. for (unsigned l = 0; l < batches.Size(); ++l)
  886. {
  887. const SourceBatch& srcBatch = batches[l];
  888. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  889. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  890. continue;
  891. Pass* pass = tech->GetSupportedPass(PASS_SHADOW);
  892. // Skip if material has no shadow pass
  893. if (!pass)
  894. continue;
  895. Batch destBatch(srcBatch);
  896. destBatch.pass_ = pass;
  897. destBatch.camera_ = shadowCamera;
  898. destBatch.zone_ = zone;
  899. destBatch.lightQueue_ = &lightQueue;
  900. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  901. }
  902. }
  903. }
  904. // Process lit geometries
  905. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  906. {
  907. Drawable* drawable = *j;
  908. drawable->AddLight(light);
  909. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  910. if (!drawable->GetMaxLights())
  911. GetLitBatches(drawable, lightQueue, alphaQueue);
  912. else
  913. maxLightsDrawables_.Insert(drawable);
  914. }
  915. // In deferred modes, store the light volume batch now
  916. if (deferred_)
  917. {
  918. Batch volumeBatch;
  919. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  920. volumeBatch.geometryType_ = GEOM_STATIC;
  921. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  922. volumeBatch.numWorldTransforms_ = 1;
  923. volumeBatch.camera_ = camera_;
  924. volumeBatch.lightQueue_ = &lightQueue;
  925. volumeBatch.distance_ = light->GetDistance();
  926. volumeBatch.material_ = 0;
  927. volumeBatch.pass_ = 0;
  928. volumeBatch.zone_ = 0;
  929. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVolumeCommand_->vertexShaderName_,
  930. lightVolumeCommand_->pixelShaderName_, lightVolumeCommand_->vertexShaderDefines_,
  931. lightVolumeCommand_->pixelShaderDefines_);
  932. lightQueue.volumeBatches_.Push(volumeBatch);
  933. }
  934. }
  935. // Per-vertex light
  936. else
  937. {
  938. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  939. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  940. {
  941. Drawable* drawable = *j;
  942. drawable->AddVertexLight(light);
  943. }
  944. }
  945. }
  946. }
  947. // Process drawables with limited per-pixel light count
  948. if (maxLightsDrawables_.Size())
  949. {
  950. PROFILE(GetMaxLightsBatches);
  951. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  952. {
  953. Drawable* drawable = *i;
  954. drawable->LimitLights();
  955. const PODVector<Light*>& lights = drawable->GetLights();
  956. for (unsigned i = 0; i < lights.Size(); ++i)
  957. {
  958. Light* light = lights[i];
  959. // Find the correct light queue again
  960. LightBatchQueue* queue = light->GetLightQueue();
  961. if (queue)
  962. GetLitBatches(drawable, *queue, alphaQueue);
  963. }
  964. }
  965. }
  966. // Build base pass batches and find out the geometry update queue (threaded or nonthreaded) drawables should end up to
  967. {
  968. PROFILE(GetBaseBatches);
  969. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  970. {
  971. Drawable* drawable = *i;
  972. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  973. if (type == UPDATE_MAIN_THREAD)
  974. nonThreadedGeometries_.Push(drawable);
  975. else if (type == UPDATE_WORKER_THREAD)
  976. threadedGeometries_.Push(drawable);
  977. Zone* zone = GetZone(drawable);
  978. const Vector<SourceBatch>& batches = drawable->GetBatches();
  979. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  980. if (!drawableVertexLights.Empty())
  981. drawable->LimitVertexLights();
  982. for (unsigned j = 0; j < batches.Size(); ++j)
  983. {
  984. const SourceBatch& srcBatch = batches[j];
  985. // Check here if the material refers to a rendertarget texture with camera(s) attached
  986. // Only check this for backbuffer views (null rendertarget)
  987. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  988. CheckMaterialForAuxView(srcBatch.material_);
  989. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  990. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  991. continue;
  992. Batch destBatch(srcBatch);
  993. destBatch.camera_ = camera_;
  994. destBatch.zone_ = zone;
  995. destBatch.isBase_ = true;
  996. destBatch.pass_ = 0;
  997. destBatch.lightMask_ = GetLightMask(drawable);
  998. // Check each of the scene passes
  999. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  1000. {
  1001. ScenePassInfo& info = scenePasses_[k];
  1002. destBatch.pass_ = tech->GetSupportedPass(info.pass_);
  1003. if (!destBatch.pass_)
  1004. continue;
  1005. // Skip forward base pass if the corresponding litbase pass already exists
  1006. if (info.pass_ == basePassName_ && j < 32 && drawable->HasBasePass(j))
  1007. continue;
  1008. if (info.vertexLights_ && !drawableVertexLights.Empty())
  1009. {
  1010. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  1011. // them to prevent double-lighting
  1012. if (deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  1013. {
  1014. vertexLights.Clear();
  1015. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  1016. {
  1017. if (drawableVertexLights[i]->GetPerVertex())
  1018. vertexLights.Push(drawableVertexLights[i]);
  1019. }
  1020. }
  1021. else
  1022. vertexLights = drawableVertexLights;
  1023. if (!vertexLights.Empty())
  1024. {
  1025. // Find a vertex light queue. If not found, create new
  1026. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  1027. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  1028. if (i == vertexLightQueues_.End())
  1029. {
  1030. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  1031. i->second_.light_ = 0;
  1032. i->second_.shadowMap_ = 0;
  1033. i->second_.vertexLights_ = vertexLights;
  1034. }
  1035. destBatch.lightQueue_ = &(i->second_);
  1036. }
  1037. }
  1038. else
  1039. destBatch.lightQueue_ = 0;
  1040. bool allowInstancing = info.allowInstancing_;
  1041. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (zone->GetLightMask() & 0xff))
  1042. allowInstancing = false;
  1043. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  1044. }
  1045. }
  1046. }
  1047. }
  1048. }
  1049. void View::UpdateGeometries()
  1050. {
  1051. PROFILE(SortAndUpdateGeometry);
  1052. WorkQueue* queue = GetSubsystem<WorkQueue>();
  1053. // Sort batches
  1054. {
  1055. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1056. {
  1057. const RenderPathCommand& command = renderPath_->commands_[i];
  1058. if (!IsNecessary(command))
  1059. continue;
  1060. if (command.type_ == CMD_SCENEPASS)
  1061. {
  1062. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1063. item->priority_ = M_MAX_UNSIGNED;
  1064. item->workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork : SortBatchQueueBackToFrontWork;
  1065. item->start_ = &batchQueues_[command.pass_];
  1066. queue->AddWorkItem(item);
  1067. }
  1068. }
  1069. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1070. {
  1071. SharedPtr<WorkItem> lightItem = queue->GetFreeItem();
  1072. lightItem->priority_ = M_MAX_UNSIGNED;
  1073. lightItem->workFunction_ = SortLightQueueWork;
  1074. lightItem->start_ = &(*i);
  1075. queue->AddWorkItem(lightItem);
  1076. if (i->shadowSplits_.Size())
  1077. {
  1078. SharedPtr<WorkItem> shadowItem = queue->GetFreeItem();
  1079. shadowItem->priority_ = M_MAX_UNSIGNED;
  1080. shadowItem->workFunction_ = SortShadowQueueWork;
  1081. shadowItem->start_ = &(*i);
  1082. queue->AddWorkItem(shadowItem);
  1083. }
  1084. }
  1085. }
  1086. // Update geometries. Split into threaded and non-threaded updates.
  1087. {
  1088. if (threadedGeometries_.Size())
  1089. {
  1090. // In special cases (context loss, multi-view) a drawable may theoretically first have reported a threaded update, but will actually
  1091. // require a main thread update. Check these cases first and move as applicable. The threaded work routine will tolerate the null
  1092. // pointer holes that we leave to the threaded update queue.
  1093. for (PODVector<Drawable*>::Iterator i = threadedGeometries_.Begin(); i != threadedGeometries_.End(); ++i)
  1094. {
  1095. if ((*i)->GetUpdateGeometryType() == UPDATE_MAIN_THREAD)
  1096. {
  1097. nonThreadedGeometries_.Push(*i);
  1098. *i = 0;
  1099. }
  1100. }
  1101. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  1102. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  1103. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  1104. for (int i = 0; i < numWorkItems; ++i)
  1105. {
  1106. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  1107. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  1108. end = start + drawablesPerItem;
  1109. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1110. item->priority_ = M_MAX_UNSIGNED;
  1111. item->workFunction_ = UpdateDrawableGeometriesWork;
  1112. item->aux_ = const_cast<FrameInfo*>(&frame_);
  1113. item->start_ = &(*start);
  1114. item->end_ = &(*end);
  1115. queue->AddWorkItem(item);
  1116. start = end;
  1117. }
  1118. }
  1119. // While the work queue is processed, update non-threaded geometries
  1120. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  1121. (*i)->UpdateGeometry(frame_);
  1122. }
  1123. // Finally ensure all threaded work has completed
  1124. queue->Complete(M_MAX_UNSIGNED);
  1125. }
  1126. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue)
  1127. {
  1128. Light* light = lightQueue.light_;
  1129. Zone* zone = GetZone(drawable);
  1130. const Vector<SourceBatch>& batches = drawable->GetBatches();
  1131. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  1132. // Shadows on transparencies can only be rendered if shadow maps are not reused
  1133. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  1134. bool allowLitBase = useLitBase_ && !light->IsNegative() && light == drawable->GetFirstLight() &&
  1135. drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  1136. for (unsigned i = 0; i < batches.Size(); ++i)
  1137. {
  1138. const SourceBatch& srcBatch = batches[i];
  1139. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1140. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1141. continue;
  1142. // Do not create pixel lit forward passes for materials that render into the G-buffer
  1143. if (gBufferPassName_.Value() && tech->HasPass(gBufferPassName_))
  1144. continue;
  1145. Batch destBatch(srcBatch);
  1146. bool isLitAlpha = false;
  1147. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1148. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1149. if (i < 32 && allowLitBase)
  1150. {
  1151. destBatch.pass_ = tech->GetSupportedPass(litBasePassName_);
  1152. if (destBatch.pass_)
  1153. {
  1154. destBatch.isBase_ = true;
  1155. drawable->SetBasePass(i);
  1156. }
  1157. else
  1158. destBatch.pass_ = tech->GetSupportedPass(lightPassName_);
  1159. }
  1160. else
  1161. destBatch.pass_ = tech->GetSupportedPass(lightPassName_);
  1162. // If no lit pass, check for lit alpha
  1163. if (!destBatch.pass_)
  1164. {
  1165. destBatch.pass_ = tech->GetSupportedPass(litAlphaPassName_);
  1166. isLitAlpha = true;
  1167. }
  1168. // Skip if material does not receive light at all
  1169. if (!destBatch.pass_)
  1170. continue;
  1171. destBatch.camera_ = camera_;
  1172. destBatch.lightQueue_ = &lightQueue;
  1173. destBatch.zone_ = zone;
  1174. if (!isLitAlpha)
  1175. {
  1176. if (destBatch.isBase_)
  1177. AddBatchToQueue(lightQueue.litBaseBatches_, destBatch, tech);
  1178. else
  1179. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1180. }
  1181. else if (alphaQueue)
  1182. {
  1183. // Transparent batches can not be instanced
  1184. AddBatchToQueue(*alphaQueue, destBatch, tech, false, allowTransparentShadows);
  1185. }
  1186. }
  1187. }
  1188. void View::ExecuteRenderPathCommands()
  1189. {
  1190. // If not reusing shadowmaps, render all of them first
  1191. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1192. {
  1193. PROFILE(RenderShadowMaps);
  1194. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1195. {
  1196. if (i->shadowMap_)
  1197. RenderShadowMap(*i);
  1198. }
  1199. }
  1200. {
  1201. PROFILE(ExecuteRenderPath);
  1202. // Set for safety in case of empty renderpath
  1203. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1204. currentViewportTexture_ = 0;
  1205. bool viewportModified = false;
  1206. bool isPingponging = false;
  1207. unsigned lastCommandIndex = 0;
  1208. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1209. {
  1210. RenderPathCommand& command = renderPath_->commands_[i];
  1211. if (IsNecessary(command))
  1212. lastCommandIndex = i;
  1213. }
  1214. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1215. {
  1216. RenderPathCommand& command = renderPath_->commands_[i];
  1217. if (!IsNecessary(command))
  1218. continue;
  1219. bool viewportRead = CheckViewportRead(command);
  1220. bool viewportWrite = CheckViewportWrite(command);
  1221. bool beginPingpong = CheckPingpong(i);
  1222. // Has the viewport been modified and will be read as a texture by the current command?
  1223. if (viewportRead && viewportModified)
  1224. {
  1225. // Start pingponging without a blit if already rendering to the substitute render target
  1226. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1227. isPingponging = true;
  1228. // If not using pingponging, simply resolve/copy to the first viewport texture
  1229. if (!isPingponging)
  1230. {
  1231. if (!currentRenderTarget_)
  1232. {
  1233. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1234. currentViewportTexture_ = viewportTextures_[0];
  1235. viewportModified = false;
  1236. }
  1237. else
  1238. {
  1239. if (viewportWrite)
  1240. {
  1241. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1242. viewportTextures_[0]->GetRenderSurface(), false);
  1243. currentViewportTexture_ = viewportTextures_[0];
  1244. viewportModified = false;
  1245. }
  1246. else
  1247. {
  1248. // If the current render target is already a texture, and we are not writing to it, can read that
  1249. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1250. // will do both read and write, and then we need to blit / resolve
  1251. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1252. }
  1253. }
  1254. }
  1255. else
  1256. {
  1257. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1258. viewportTextures_[1] = viewportTextures_[0];
  1259. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1260. currentViewportTexture_ = viewportTextures_[0];
  1261. viewportModified = false;
  1262. }
  1263. }
  1264. if (beginPingpong)
  1265. isPingponging = true;
  1266. // Determine viewport write target
  1267. if (viewportWrite)
  1268. {
  1269. if (isPingponging)
  1270. {
  1271. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1272. // If the render path ends into a quad, it can be redirected to the final render target
  1273. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1274. currentRenderTarget_ = renderTarget_;
  1275. }
  1276. else
  1277. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1278. }
  1279. switch (command.type_)
  1280. {
  1281. case CMD_CLEAR:
  1282. {
  1283. PROFILE(ClearRenderTarget);
  1284. Color clearColor = command.clearColor_;
  1285. if (command.useFogColor_)
  1286. clearColor = farClipZone_->GetFogColor();
  1287. SetRenderTargets(command);
  1288. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1289. }
  1290. break;
  1291. case CMD_SCENEPASS:
  1292. if (!batchQueues_[command.pass_].IsEmpty())
  1293. {
  1294. PROFILE(RenderScenePass);
  1295. SetRenderTargets(command);
  1296. bool allowDepthWrite = SetTextures(command);
  1297. graphics_->SetDrawAntialiased(true);
  1298. graphics_->SetFillMode(camera_->GetFillMode());
  1299. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1300. batchQueues_[command.pass_].Draw(this, command.markToStencil_, false, allowDepthWrite);
  1301. }
  1302. break;
  1303. case CMD_QUAD:
  1304. {
  1305. PROFILE(RenderQuad);
  1306. SetRenderTargets(command);
  1307. SetTextures(command);
  1308. RenderQuad(command);
  1309. }
  1310. break;
  1311. case CMD_FORWARDLIGHTS:
  1312. // Render shadow maps + opaque objects' additive lighting
  1313. if (!lightQueues_.Empty())
  1314. {
  1315. PROFILE(RenderLights);
  1316. SetRenderTargets(command);
  1317. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1318. {
  1319. // If reusing shadowmaps, render each of them before the lit batches
  1320. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1321. {
  1322. RenderShadowMap(*i);
  1323. SetRenderTargets(command);
  1324. }
  1325. bool allowDepthWrite = SetTextures(command);
  1326. graphics_->SetDrawAntialiased(true);
  1327. graphics_->SetFillMode(camera_->GetFillMode());
  1328. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1329. // Draw base (replace blend) batches first
  1330. i->litBaseBatches_.Draw(this, false, false, allowDepthWrite);
  1331. // Then, if there are additive passes, optimize the light and draw them
  1332. if (!i->litBatches_.IsEmpty())
  1333. {
  1334. renderer_->OptimizeLightByScissor(i->light_, camera_);
  1335. if (!noStencil_)
  1336. renderer_->OptimizeLightByStencil(i->light_, camera_);
  1337. i->litBatches_.Draw(this, false, true, allowDepthWrite);
  1338. }
  1339. }
  1340. graphics_->SetScissorTest(false);
  1341. graphics_->SetStencilTest(false);
  1342. }
  1343. break;
  1344. case CMD_LIGHTVOLUMES:
  1345. // Render shadow maps + light volumes
  1346. if (!lightQueues_.Empty())
  1347. {
  1348. PROFILE(RenderLightVolumes);
  1349. SetRenderTargets(command);
  1350. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1351. {
  1352. // If reusing shadowmaps, render each of them before the lit batches
  1353. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1354. {
  1355. RenderShadowMap(*i);
  1356. SetRenderTargets(command);
  1357. }
  1358. SetTextures(command);
  1359. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1360. {
  1361. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1362. i->volumeBatches_[j].Draw(this, false);
  1363. }
  1364. }
  1365. graphics_->SetScissorTest(false);
  1366. graphics_->SetStencilTest(false);
  1367. }
  1368. break;
  1369. case CMD_RENDERUI:
  1370. {
  1371. SetRenderTargets(command);
  1372. GetSubsystem<UI>()->Render(false);
  1373. }
  1374. break;
  1375. default:
  1376. break;
  1377. }
  1378. // If current command output to the viewport, mark it modified
  1379. if (viewportWrite)
  1380. viewportModified = true;
  1381. }
  1382. }
  1383. }
  1384. void View::SetRenderTargets(RenderPathCommand& command)
  1385. {
  1386. unsigned index = 0;
  1387. bool useColorWrite = true;
  1388. bool useCustomDepth = false;
  1389. while (index < command.outputNames_.Size())
  1390. {
  1391. if (!command.outputNames_[index].Compare("viewport", false))
  1392. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1393. else
  1394. {
  1395. StringHash nameHash(command.outputNames_[index]);
  1396. if (renderTargets_.Contains(nameHash))
  1397. {
  1398. Texture2D* texture = renderTargets_[nameHash];
  1399. // Check for depth only rendering (by specifying a depth texture as the sole output)
  1400. if (!index && command.outputNames_.Size() == 1 && texture && texture->GetFormat() ==
  1401. Graphics::GetReadableDepthFormat() || texture->GetFormat() == Graphics::GetDepthStencilFormat())
  1402. {
  1403. useColorWrite = false;
  1404. useCustomDepth = true;
  1405. #ifndef ATOMIC_OPENGL
  1406. // On D3D actual depth-only rendering is illegal, we need a color rendertarget
  1407. if (!depthOnlyDummyTexture_)
  1408. {
  1409. depthOnlyDummyTexture_ = renderer_->GetScreenBuffer(texture->GetWidth(), texture->GetHeight(),
  1410. graphics_->GetDummyColorFormat(), false, false);
  1411. }
  1412. #endif
  1413. graphics_->SetRenderTarget(0, depthOnlyDummyTexture_);
  1414. graphics_->SetDepthStencil(texture);
  1415. }
  1416. else
  1417. graphics_->SetRenderTarget(index, texture);
  1418. }
  1419. else
  1420. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1421. }
  1422. ++index;
  1423. }
  1424. while (index < MAX_RENDERTARGETS)
  1425. {
  1426. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1427. ++index;
  1428. }
  1429. if (command.depthStencilName_.Length())
  1430. {
  1431. Texture2D* depthTexture = renderTargets_[StringHash(command.depthStencilName_)];
  1432. if (depthTexture)
  1433. {
  1434. useCustomDepth = true;
  1435. graphics_->SetDepthStencil(depthTexture);
  1436. }
  1437. }
  1438. // When rendering to the final destination rendertarget, use the actual viewport. Otherwise texture rendertargets will be
  1439. // viewport-sized, so they should use their full size as the viewport
  1440. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  1441. IntRect viewport = (graphics_->GetRenderTarget(0) == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  1442. rtSizeNow.y_);
  1443. if (!useCustomDepth)
  1444. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1445. graphics_->SetViewport(viewport);
  1446. graphics_->SetColorWrite(useColorWrite);
  1447. }
  1448. bool View::SetTextures(RenderPathCommand& command)
  1449. {
  1450. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1451. bool allowDepthWrite = true;
  1452. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1453. {
  1454. if (command.textureNames_[i].Empty())
  1455. continue;
  1456. // Bind the rendered output
  1457. if (!command.textureNames_[i].Compare("viewport", false))
  1458. {
  1459. graphics_->SetTexture(i, currentViewportTexture_);
  1460. continue;
  1461. }
  1462. // Bind a rendertarget
  1463. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1464. if (j != renderTargets_.End())
  1465. {
  1466. graphics_->SetTexture(i, j->second_);
  1467. // Check if the current depth stencil is being sampled
  1468. if (graphics_->GetDepthStencil() && j->second_ == graphics_->GetDepthStencil()->GetParentTexture())
  1469. allowDepthWrite = false;
  1470. continue;
  1471. }
  1472. // Bind a texture from the resource system
  1473. Texture* texture;
  1474. // Detect cube/3D textures by file extension: they are defined by an XML file
  1475. if (GetExtension(command.textureNames_[i]) == ".xml")
  1476. {
  1477. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1478. if (i == TU_VOLUMEMAP)
  1479. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1480. else
  1481. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1482. }
  1483. else
  1484. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1485. if (texture)
  1486. graphics_->SetTexture(i, texture);
  1487. else
  1488. {
  1489. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1490. command.textureNames_[i] = String::EMPTY;
  1491. }
  1492. }
  1493. return allowDepthWrite;
  1494. }
  1495. void View::RenderQuad(RenderPathCommand& command)
  1496. {
  1497. if (command.vertexShaderName_.Empty() || command.pixelShaderName_.Empty())
  1498. return;
  1499. // If shader can not be found, clear it from the command to prevent redundant attempts
  1500. ShaderVariation* vs = graphics_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1501. if (!vs)
  1502. command.vertexShaderName_ = String::EMPTY;
  1503. ShaderVariation* ps = graphics_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1504. if (!ps)
  1505. command.pixelShaderName_ = String::EMPTY;
  1506. // Set shaders & shader parameters and textures
  1507. graphics_->SetShaders(vs, ps);
  1508. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1509. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1510. graphics_->SetShaderParameter(k->first_, k->second_);
  1511. SetGlobalShaderParameters();
  1512. SetCameraShaderParameters(camera_, false);
  1513. // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
  1514. IntRect viewport = graphics_->GetViewport();
  1515. IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
  1516. SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
  1517. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1518. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1519. {
  1520. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1521. if (!rtInfo.enabled_)
  1522. continue;
  1523. StringHash nameHash(rtInfo.name_);
  1524. if (!renderTargets_.Contains(nameHash))
  1525. continue;
  1526. String invSizeName = rtInfo.name_ + "InvSize";
  1527. String offsetsName = rtInfo.name_ + "Offsets";
  1528. float width = (float)renderTargets_[nameHash]->GetWidth();
  1529. float height = (float)renderTargets_[nameHash]->GetHeight();
  1530. graphics_->SetShaderParameter(invSizeName, Vector2(1.0f / width, 1.0f / height));
  1531. #ifdef ATOMIC_OPENGL
  1532. graphics_->SetShaderParameter(offsetsName, Vector2::ZERO);
  1533. #else
  1534. graphics_->SetShaderParameter(offsetsName, Vector2(0.5f / width, 0.5f / height));
  1535. #endif
  1536. }
  1537. graphics_->SetBlendMode(BLEND_REPLACE);
  1538. graphics_->SetDepthTest(CMP_ALWAYS);
  1539. graphics_->SetDepthWrite(false);
  1540. graphics_->SetDrawAntialiased(false);
  1541. graphics_->SetFillMode(FILL_SOLID);
  1542. graphics_->SetClipPlane(false);
  1543. graphics_->SetScissorTest(false);
  1544. graphics_->SetStencilTest(false);
  1545. DrawFullscreenQuad(false);
  1546. }
  1547. bool View::IsNecessary(const RenderPathCommand& command)
  1548. {
  1549. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1550. !batchQueues_[command.pass_].IsEmpty());
  1551. }
  1552. bool View::CheckViewportRead(const RenderPathCommand& command)
  1553. {
  1554. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1555. {
  1556. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1562. {
  1563. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1564. {
  1565. if (!command.outputNames_[i].Compare("viewport", false))
  1566. return true;
  1567. }
  1568. return false;
  1569. }
  1570. bool View::CheckPingpong(unsigned index)
  1571. {
  1572. // Current command must be a viewport-reading & writing quad to begin the pingpong chain
  1573. RenderPathCommand& current = renderPath_->commands_[index];
  1574. if (current.type_ != CMD_QUAD || !CheckViewportRead(current) || !CheckViewportWrite(current))
  1575. return false;
  1576. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1577. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1578. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1579. {
  1580. RenderPathCommand& command = renderPath_->commands_[i];
  1581. if (!IsNecessary(command))
  1582. continue;
  1583. if (CheckViewportWrite(command))
  1584. {
  1585. if (command.type_ != CMD_QUAD)
  1586. return false;
  1587. }
  1588. }
  1589. return true;
  1590. }
  1591. void View::AllocateScreenBuffers()
  1592. {
  1593. bool needSubstitute = false;
  1594. unsigned numViewportTextures = 0;
  1595. depthOnlyDummyTexture_ = 0;
  1596. #ifdef ATOMIC_OPENGL
  1597. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1598. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1599. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1600. Graphics::GetRGBAFormat()))
  1601. needSubstitute = true;
  1602. // Also need substitute if rendering to backbuffer using a custom (readable) depth buffer
  1603. if (!renderTarget_ && !needSubstitute)
  1604. {
  1605. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1606. {
  1607. const RenderPathCommand& command = renderPath_->commands_[i];
  1608. if (!IsNecessary(command))
  1609. continue;
  1610. if (command.depthStencilName_.Length() && command.outputNames_.Size() && !command.outputNames_[0].Compare("viewport",
  1611. false))
  1612. {
  1613. needSubstitute = true;
  1614. break;
  1615. }
  1616. }
  1617. }
  1618. #endif
  1619. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1620. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1621. needSubstitute = true;
  1622. // If viewport is smaller than whole texture/backbuffer in deferred rendering, need to reserve a buffer, as the G-buffer
  1623. // textures will be sized equal to the viewport
  1624. if (viewSize_.x_ < rtSize_.x_ || viewSize_.y_ < rtSize_.y_)
  1625. {
  1626. if (deferred_)
  1627. needSubstitute = true;
  1628. else if (!needSubstitute)
  1629. {
  1630. // Check also if using MRT without deferred rendering and rendering to the viewport and another texture,
  1631. // or using custom depth
  1632. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1633. {
  1634. const RenderPathCommand& command = renderPath_->commands_[i];
  1635. if (!IsNecessary(command))
  1636. continue;
  1637. if (command.depthStencilName_.Length())
  1638. needSubstitute = true;
  1639. if (!needSubstitute && command.outputNames_.Size() > 1)
  1640. {
  1641. for (unsigned j = 0; j < command.outputNames_.Size(); ++j)
  1642. {
  1643. if (!command.outputNames_[j].Compare("viewport", false))
  1644. {
  1645. needSubstitute = true;
  1646. break;
  1647. }
  1648. }
  1649. }
  1650. if (needSubstitute)
  1651. break;
  1652. }
  1653. }
  1654. }
  1655. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1656. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1657. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1658. if (renderer_->GetHDRRendering())
  1659. {
  1660. format = Graphics::GetRGBAFloat16Format();
  1661. needSubstitute = true;
  1662. }
  1663. #ifdef ATOMIC_OPENGL
  1664. if (deferred_ && !renderer_->GetHDRRendering())
  1665. format = Graphics::GetRGBAFormat();
  1666. #endif
  1667. // Check for commands which read the viewport, or pingpong between viewport textures
  1668. bool hasViewportRead = false;
  1669. bool hasPingpong = false;
  1670. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1671. {
  1672. const RenderPathCommand& command = renderPath_->commands_[i];
  1673. if (!IsNecessary(command))
  1674. continue;
  1675. if (CheckViewportRead(command))
  1676. hasViewportRead = true;
  1677. if (!hasPingpong && CheckPingpong(i))
  1678. hasPingpong = true;
  1679. }
  1680. if (hasViewportRead)
  1681. {
  1682. ++numViewportTextures;
  1683. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1684. // is specified, there is no choice
  1685. #ifdef GL_ES_VERSION_2_0
  1686. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1687. needSubstitute = true;
  1688. #endif
  1689. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1690. // does not support reading a cube map
  1691. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1692. needSubstitute = true;
  1693. // If rendering to a texture, but the viewport is less than the whole texture, use a substitute to ensure
  1694. // postprocessing shaders will never read outside the viewport
  1695. if (renderTarget_ && (viewSize_.x_ < renderTarget_->GetWidth() || viewSize_.y_ < renderTarget_->GetHeight()))
  1696. needSubstitute = true;
  1697. if (hasPingpong && !needSubstitute)
  1698. ++numViewportTextures;
  1699. }
  1700. // Allocate screen buffers with filtering active in case the quad commands need that
  1701. // Follow the sRGB mode of the destination render target
  1702. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1703. substituteRenderTarget_ = needSubstitute ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true,
  1704. sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1705. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1706. {
  1707. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true, sRGB) :
  1708. (Texture2D*)0;
  1709. }
  1710. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1711. if (numViewportTextures == 1 && substituteRenderTarget_)
  1712. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1713. // Allocate extra render targets defined by the rendering path
  1714. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1715. {
  1716. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1717. if (!rtInfo.enabled_)
  1718. continue;
  1719. float width = rtInfo.size_.x_;
  1720. float height = rtInfo.size_.y_;
  1721. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1722. {
  1723. width = (float)viewSize_.x_ / Max(width, M_EPSILON);
  1724. height = (float)viewSize_.y_ / Max(height, M_EPSILON);
  1725. }
  1726. else if (rtInfo.sizeMode_ == SIZE_VIEWPORTMULTIPLIER)
  1727. {
  1728. width = (float)viewSize_.x_ * width;
  1729. height = (float)viewSize_.y_ * height;
  1730. }
  1731. int intWidth = (int)(width + 0.5f);
  1732. int intHeight = (int)(height + 0.5f);
  1733. // If the rendertarget is persistent, key it with a hash derived from the RT name and the view's pointer
  1734. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(intWidth, intHeight, rtInfo.format_, rtInfo.filtered_,
  1735. rtInfo.sRGB_, rtInfo.persistent_ ? StringHash(rtInfo.name_).Value() + (unsigned)(size_t)this : 0);
  1736. }
  1737. }
  1738. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1739. {
  1740. if (!source)
  1741. return;
  1742. PROFILE(BlitFramebuffer);
  1743. // If blitting to the destination rendertarget, use the actual viewport. Intermediate textures on the other hand
  1744. // are always viewport-sized
  1745. IntVector2 srcSize(source->GetWidth(), source->GetHeight());
  1746. IntVector2 destSize = destination ? IntVector2(destination->GetWidth(), destination->GetHeight()) : IntVector2(
  1747. graphics_->GetWidth(), graphics_->GetHeight());
  1748. IntRect srcRect = (source->GetRenderSurface() == renderTarget_) ? viewRect_ : IntRect(0, 0, srcSize.x_, srcSize.y_);
  1749. IntRect destRect = (destination == renderTarget_) ? viewRect_ : IntRect(0, 0, destSize.x_, destSize.y_);
  1750. graphics_->SetBlendMode(BLEND_REPLACE);
  1751. graphics_->SetDepthTest(CMP_ALWAYS);
  1752. graphics_->SetDepthWrite(depthWrite);
  1753. graphics_->SetFillMode(FILL_SOLID);
  1754. graphics_->SetClipPlane(false);
  1755. graphics_->SetScissorTest(false);
  1756. graphics_->SetStencilTest(false);
  1757. graphics_->SetRenderTarget(0, destination);
  1758. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1759. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1760. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1761. graphics_->SetViewport(destRect);
  1762. static const String shaderName("CopyFramebuffer");
  1763. graphics_->SetShaders(graphics_->GetShader(VS, shaderName), graphics_->GetShader(PS, shaderName));
  1764. SetGBufferShaderParameters(srcSize, srcRect);
  1765. graphics_->SetTexture(TU_DIFFUSE, source);
  1766. DrawFullscreenQuad(false);
  1767. }
  1768. void View::DrawFullscreenQuad(bool nearQuad)
  1769. {
  1770. Geometry* geometry = renderer_->GetQuadGeometry();
  1771. Matrix3x4 model = Matrix3x4::IDENTITY;
  1772. Matrix4 projection = Matrix4::IDENTITY;
  1773. #ifdef ATOMIC_OPENGL
  1774. if (camera_ && camera_->GetFlipVertical())
  1775. projection.m11_ = -1.0f;
  1776. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1777. #else
  1778. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1779. #endif
  1780. graphics_->SetCullMode(CULL_NONE);
  1781. graphics_->SetShaderParameter(VSP_MODEL, model);
  1782. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1783. graphics_->ClearTransformSources();
  1784. geometry->Draw(graphics_);
  1785. }
  1786. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1787. {
  1788. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1789. float halfViewSize = camera->GetHalfViewSize();
  1790. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1791. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1792. {
  1793. Drawable* occluder = *i;
  1794. bool erase = false;
  1795. if (!occluder->IsInView(frame_, true))
  1796. occluder->UpdateBatches(frame_);
  1797. // Check occluder's draw distance (in main camera view)
  1798. float maxDistance = occluder->GetDrawDistance();
  1799. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1800. {
  1801. // Check that occluder is big enough on the screen
  1802. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1803. float diagonal = box.Size().Length();
  1804. float compare;
  1805. if (!camera->IsOrthographic())
  1806. compare = diagonal * halfViewSize / occluder->GetDistance();
  1807. else
  1808. compare = diagonal * invOrthoSize;
  1809. if (compare < occluderSizeThreshold_)
  1810. erase = true;
  1811. else
  1812. {
  1813. // Store amount of triangles divided by screen size as a sorting key
  1814. // (best occluders are big and have few triangles)
  1815. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1816. }
  1817. }
  1818. else
  1819. erase = true;
  1820. if (erase)
  1821. i = occluders.Erase(i);
  1822. else
  1823. ++i;
  1824. }
  1825. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1826. if (occluders.Size())
  1827. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1828. }
  1829. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1830. {
  1831. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1832. buffer->Clear();
  1833. for (unsigned i = 0; i < occluders.Size(); ++i)
  1834. {
  1835. Drawable* occluder = occluders[i];
  1836. if (i > 0)
  1837. {
  1838. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1839. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1840. continue;
  1841. }
  1842. // Check for running out of triangles
  1843. if (!occluder->DrawOcclusion(buffer))
  1844. break;
  1845. }
  1846. buffer->BuildDepthHierarchy();
  1847. }
  1848. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1849. {
  1850. Light* light = query.light_;
  1851. LightType type = light->GetLightType();
  1852. const Frustum& frustum = camera_->GetFrustum();
  1853. // Check if light should be shadowed
  1854. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1855. // If shadow distance non-zero, check it
  1856. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1857. isShadowed = false;
  1858. // OpenGL ES can not support point light shadows
  1859. #ifdef GL_ES_VERSION_2_0
  1860. if (isShadowed && type == LIGHT_POINT)
  1861. isShadowed = false;
  1862. #endif
  1863. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1864. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1865. query.litGeometries_.Clear();
  1866. switch (type)
  1867. {
  1868. case LIGHT_DIRECTIONAL:
  1869. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1870. {
  1871. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1872. query.litGeometries_.Push(geometries_[i]);
  1873. }
  1874. break;
  1875. case LIGHT_SPOT:
  1876. {
  1877. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY,
  1878. camera_->GetViewMask());
  1879. octree_->GetDrawables(octreeQuery);
  1880. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1881. {
  1882. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1883. query.litGeometries_.Push(tempDrawables[i]);
  1884. }
  1885. }
  1886. break;
  1887. case LIGHT_POINT:
  1888. {
  1889. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1890. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1891. octree_->GetDrawables(octreeQuery);
  1892. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1893. {
  1894. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1895. query.litGeometries_.Push(tempDrawables[i]);
  1896. }
  1897. }
  1898. break;
  1899. }
  1900. // If no lit geometries or not shadowed, no need to process shadow cameras
  1901. if (query.litGeometries_.Empty() || !isShadowed)
  1902. {
  1903. query.numSplits_ = 0;
  1904. return;
  1905. }
  1906. // Determine number of shadow cameras and setup their initial positions
  1907. SetupShadowCameras(query);
  1908. // Process each split for shadow casters
  1909. query.shadowCasters_.Clear();
  1910. for (unsigned i = 0; i < query.numSplits_; ++i)
  1911. {
  1912. Camera* shadowCamera = query.shadowCameras_[i];
  1913. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1914. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1915. // For point light check that the face is visible: if not, can skip the split
  1916. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1917. continue;
  1918. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1919. if (type == LIGHT_DIRECTIONAL)
  1920. {
  1921. if (minZ_ > query.shadowFarSplits_[i])
  1922. continue;
  1923. if (maxZ_ < query.shadowNearSplits_[i])
  1924. continue;
  1925. // Reuse lit geometry query for all except directional lights
  1926. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1927. camera_->GetViewMask());
  1928. octree_->GetDrawables(query);
  1929. }
  1930. // Check which shadow casters actually contribute to the shadowing
  1931. ProcessShadowCasters(query, tempDrawables, i);
  1932. }
  1933. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1934. // only cost has been the shadow camera setup & queries
  1935. if (query.shadowCasters_.Empty())
  1936. query.numSplits_ = 0;
  1937. }
  1938. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1939. {
  1940. Light* light = query.light_;
  1941. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1942. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1943. const Matrix3x4& lightView = shadowCamera->GetView();
  1944. const Matrix4& lightProj = shadowCamera->GetProjection();
  1945. LightType type = light->GetLightType();
  1946. query.shadowCasterBox_[splitIndex].defined_ = false;
  1947. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1948. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1949. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1950. Frustum lightViewFrustum;
  1951. if (type != LIGHT_DIRECTIONAL)
  1952. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1953. else
  1954. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1955. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1956. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1957. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1958. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1959. return;
  1960. BoundingBox lightViewBox;
  1961. BoundingBox lightProjBox;
  1962. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1963. {
  1964. Drawable* drawable = *i;
  1965. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1966. // Check for that first
  1967. if (!drawable->GetCastShadows())
  1968. continue;
  1969. // Check shadow mask
  1970. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1971. continue;
  1972. // For point light, check that this drawable is inside the split shadow camera frustum
  1973. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1974. continue;
  1975. // Check shadow distance
  1976. float maxShadowDistance = drawable->GetShadowDistance();
  1977. float drawDistance = drawable->GetDrawDistance();
  1978. bool batchesUpdated = drawable->IsInView(frame_, true);
  1979. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1980. maxShadowDistance = drawDistance;
  1981. if (maxShadowDistance > 0.0f)
  1982. {
  1983. if (!batchesUpdated)
  1984. {
  1985. drawable->UpdateBatches(frame_);
  1986. batchesUpdated = true;
  1987. }
  1988. if (drawable->GetDistance() > maxShadowDistance)
  1989. continue;
  1990. }
  1991. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1992. // times. However, this should not cause problems as no scene modification happens at this point.
  1993. if (!batchesUpdated)
  1994. drawable->UpdateBatches(frame_);
  1995. // Project shadow caster bounding box to light view space for visibility check
  1996. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1997. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1998. {
  1999. // Merge to shadow caster bounding box and add to the list
  2000. if (type == LIGHT_DIRECTIONAL)
  2001. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  2002. else
  2003. {
  2004. lightProjBox = lightViewBox.Projected(lightProj);
  2005. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  2006. }
  2007. query.shadowCasters_.Push(drawable);
  2008. }
  2009. }
  2010. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  2011. }
  2012. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  2013. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  2014. {
  2015. if (shadowCamera->IsOrthographic())
  2016. {
  2017. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  2018. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  2019. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2020. }
  2021. else
  2022. {
  2023. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  2024. if (drawable->IsInView(frame_))
  2025. return true;
  2026. // For perspective lights, extrusion direction depends on the position of the shadow caster
  2027. Vector3 center = lightViewBox.Center();
  2028. Ray extrusionRay(center, center);
  2029. float extrusionDistance = shadowCamera->GetFarClip();
  2030. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  2031. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  2032. float sizeFactor = extrusionDistance / originalDistance;
  2033. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  2034. // than necessary, so the test will be conservative
  2035. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  2036. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  2037. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  2038. lightViewBox.Merge(extrudedBox);
  2039. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2040. }
  2041. }
  2042. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  2043. {
  2044. unsigned width = shadowMap->GetWidth();
  2045. unsigned height = shadowMap->GetHeight();
  2046. switch (light->GetLightType())
  2047. {
  2048. case LIGHT_DIRECTIONAL:
  2049. {
  2050. int numSplits = light->GetNumShadowSplits();
  2051. if (numSplits == 1)
  2052. return IntRect(0, 0, width, height);
  2053. else if (numSplits == 2)
  2054. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  2055. else
  2056. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  2057. (splitIndex / 2 + 1) * height / 2);
  2058. }
  2059. case LIGHT_SPOT:
  2060. return IntRect(0, 0, width, height);
  2061. case LIGHT_POINT:
  2062. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  2063. (splitIndex / 2 + 1) * height / 3);
  2064. }
  2065. return IntRect();
  2066. }
  2067. void View::SetupShadowCameras(LightQueryResult& query)
  2068. {
  2069. Light* light = query.light_;
  2070. int splits = 0;
  2071. switch (light->GetLightType())
  2072. {
  2073. case LIGHT_DIRECTIONAL:
  2074. {
  2075. const CascadeParameters& cascade = light->GetShadowCascade();
  2076. float nearSplit = camera_->GetNearClip();
  2077. float farSplit;
  2078. int numSplits = light->GetNumShadowSplits();
  2079. while (splits < numSplits)
  2080. {
  2081. // If split is completely beyond camera far clip, we are done
  2082. if (nearSplit > camera_->GetFarClip())
  2083. break;
  2084. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  2085. if (farSplit <= nearSplit)
  2086. break;
  2087. // Setup the shadow camera for the split
  2088. Camera* shadowCamera = renderer_->GetShadowCamera();
  2089. query.shadowCameras_[splits] = shadowCamera;
  2090. query.shadowNearSplits_[splits] = nearSplit;
  2091. query.shadowFarSplits_[splits] = farSplit;
  2092. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  2093. nearSplit = farSplit;
  2094. ++splits;
  2095. }
  2096. }
  2097. break;
  2098. case LIGHT_SPOT:
  2099. {
  2100. Camera* shadowCamera = renderer_->GetShadowCamera();
  2101. query.shadowCameras_[0] = shadowCamera;
  2102. Node* cameraNode = shadowCamera->GetNode();
  2103. Node* lightNode = light->GetNode();
  2104. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  2105. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2106. shadowCamera->SetFarClip(light->GetRange());
  2107. shadowCamera->SetFov(light->GetFov());
  2108. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  2109. splits = 1;
  2110. }
  2111. break;
  2112. case LIGHT_POINT:
  2113. {
  2114. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  2115. {
  2116. Camera* shadowCamera = renderer_->GetShadowCamera();
  2117. query.shadowCameras_[i] = shadowCamera;
  2118. Node* cameraNode = shadowCamera->GetNode();
  2119. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  2120. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  2121. cameraNode->SetDirection(*directions[i]);
  2122. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2123. shadowCamera->SetFarClip(light->GetRange());
  2124. shadowCamera->SetFov(90.0f);
  2125. shadowCamera->SetAspectRatio(1.0f);
  2126. }
  2127. splits = MAX_CUBEMAP_FACES;
  2128. }
  2129. break;
  2130. }
  2131. query.numSplits_ = splits;
  2132. }
  2133. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  2134. {
  2135. Node* shadowCameraNode = shadowCamera->GetNode();
  2136. Node* lightNode = light->GetNode();
  2137. float extrusionDistance = camera_->GetFarClip();
  2138. const FocusParameters& parameters = light->GetShadowFocus();
  2139. // Calculate initial position & rotation
  2140. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  2141. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  2142. // Calculate main camera shadowed frustum in light's view space
  2143. farSplit = Min(farSplit, camera_->GetFarClip());
  2144. // Use the scene Z bounds to limit frustum size if applicable
  2145. if (parameters.focus_)
  2146. {
  2147. nearSplit = Max(minZ_, nearSplit);
  2148. farSplit = Min(maxZ_, farSplit);
  2149. }
  2150. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  2151. Polyhedron frustumVolume;
  2152. frustumVolume.Define(splitFrustum);
  2153. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  2154. if (parameters.focus_)
  2155. {
  2156. BoundingBox litGeometriesBox;
  2157. for (unsigned i = 0; i < geometries_.Size(); ++i)
  2158. {
  2159. Drawable* drawable = geometries_[i];
  2160. // Skip skyboxes as they have undefinedly large bounding box size
  2161. if (drawable->GetType() == Skybox::GetTypeStatic())
  2162. continue;
  2163. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  2164. (GetLightMask(drawable) & light->GetLightMask()))
  2165. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  2166. }
  2167. if (litGeometriesBox.defined_)
  2168. {
  2169. frustumVolume.Clip(litGeometriesBox);
  2170. // If volume became empty, restore it to avoid zero size
  2171. if (frustumVolume.Empty())
  2172. frustumVolume.Define(splitFrustum);
  2173. }
  2174. }
  2175. // Transform frustum volume to light space
  2176. const Matrix3x4& lightView = shadowCamera->GetView();
  2177. frustumVolume.Transform(lightView);
  2178. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  2179. BoundingBox shadowBox;
  2180. if (!parameters.nonUniform_)
  2181. shadowBox.Define(Sphere(frustumVolume));
  2182. else
  2183. shadowBox.Define(frustumVolume);
  2184. shadowCamera->SetOrthographic(true);
  2185. shadowCamera->SetAspectRatio(1.0f);
  2186. shadowCamera->SetNearClip(0.0f);
  2187. shadowCamera->SetFarClip(shadowBox.max_.z_);
  2188. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  2189. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  2190. }
  2191. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2192. const BoundingBox& shadowCasterBox)
  2193. {
  2194. const FocusParameters& parameters = light->GetShadowFocus();
  2195. float shadowMapWidth = (float)(shadowViewport.Width());
  2196. LightType type = light->GetLightType();
  2197. if (type == LIGHT_DIRECTIONAL)
  2198. {
  2199. BoundingBox shadowBox;
  2200. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  2201. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  2202. shadowBox.min_.y_ = -shadowBox.max_.y_;
  2203. shadowBox.min_.x_ = -shadowBox.max_.x_;
  2204. // Requantize and snap to shadow map texels
  2205. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2206. }
  2207. if (type == LIGHT_SPOT)
  2208. {
  2209. if (parameters.focus_)
  2210. {
  2211. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2212. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2213. float viewSize = Max(viewSizeX, viewSizeY);
  2214. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2215. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2216. float quantize = parameters.quantize_ * invOrthoSize;
  2217. float minView = parameters.minView_ * invOrthoSize;
  2218. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2219. if (viewSize < 1.0f)
  2220. shadowCamera->SetZoom(1.0f / viewSize);
  2221. }
  2222. }
  2223. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2224. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2225. if (shadowCamera->GetZoom() >= 1.0f)
  2226. {
  2227. if (light->GetLightType() != LIGHT_POINT)
  2228. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2229. else
  2230. {
  2231. #ifdef ATOMIC_OPENGL
  2232. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2233. #else
  2234. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2235. #endif
  2236. }
  2237. }
  2238. }
  2239. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2240. const BoundingBox& viewBox)
  2241. {
  2242. Node* shadowCameraNode = shadowCamera->GetNode();
  2243. const FocusParameters& parameters = light->GetShadowFocus();
  2244. float shadowMapWidth = (float)(shadowViewport.Width());
  2245. float minX = viewBox.min_.x_;
  2246. float minY = viewBox.min_.y_;
  2247. float maxX = viewBox.max_.x_;
  2248. float maxY = viewBox.max_.y_;
  2249. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2250. Vector2 viewSize(maxX - minX, maxY - minY);
  2251. // Quantize size to reduce swimming
  2252. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2253. if (parameters.nonUniform_)
  2254. {
  2255. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2256. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2257. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2258. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2259. }
  2260. else if (parameters.focus_)
  2261. {
  2262. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2263. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2264. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2265. viewSize.y_ = viewSize.x_;
  2266. }
  2267. shadowCamera->SetOrthoSize(viewSize);
  2268. // Center shadow camera to the view space bounding box
  2269. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2270. Vector3 adjust(center.x_, center.y_, 0.0f);
  2271. shadowCameraNode->Translate(rot * adjust, TS_WORLD);
  2272. // If the shadow map viewport is known, snap to whole texels
  2273. if (shadowMapWidth > 0.0f)
  2274. {
  2275. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2276. // Take into account that shadow map border will not be used
  2277. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2278. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2279. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2280. shadowCameraNode->Translate(rot * snap, TS_WORLD);
  2281. }
  2282. }
  2283. void View::FindZone(Drawable* drawable)
  2284. {
  2285. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2286. int bestPriority = M_MIN_INT;
  2287. Zone* newZone = 0;
  2288. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2289. // (possibly incorrect) and must be re-evaluated on the next frame
  2290. bool temporary = !camera_->GetFrustum().IsInside(center);
  2291. // First check if the current zone remains a conclusive result
  2292. Zone* lastZone = drawable->GetZone();
  2293. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2294. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2295. newZone = lastZone;
  2296. else
  2297. {
  2298. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2299. {
  2300. Zone* zone = *i;
  2301. int priority = zone->GetPriority();
  2302. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2303. {
  2304. newZone = zone;
  2305. bestPriority = priority;
  2306. }
  2307. }
  2308. }
  2309. drawable->SetZone(newZone, temporary);
  2310. }
  2311. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2312. {
  2313. if (!material)
  2314. {
  2315. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  2316. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  2317. }
  2318. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2319. // If only one technique, no choice
  2320. if (techniques.Size() == 1)
  2321. return techniques[0].technique_;
  2322. else
  2323. {
  2324. float lodDistance = drawable->GetLodDistance();
  2325. // Check for suitable technique. Techniques should be ordered like this:
  2326. // Most distant & highest quality
  2327. // Most distant & lowest quality
  2328. // Second most distant & highest quality
  2329. // ...
  2330. for (unsigned i = 0; i < techniques.Size(); ++i)
  2331. {
  2332. const TechniqueEntry& entry = techniques[i];
  2333. Technique* tech = entry.technique_;
  2334. if (!tech || (!tech->IsSupported()) || materialQuality_ < entry.qualityLevel_)
  2335. continue;
  2336. if (lodDistance >= entry.lodDistance_)
  2337. return tech;
  2338. }
  2339. // If no suitable technique found, fallback to the last
  2340. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2341. }
  2342. }
  2343. void View::CheckMaterialForAuxView(Material* material)
  2344. {
  2345. const SharedPtr<Texture>* textures = material->GetTextures();
  2346. unsigned numTextures = material->GetNumUsedTextureUnits();
  2347. for (unsigned i = 0; i < numTextures; ++i)
  2348. {
  2349. Texture* texture = textures[i];
  2350. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2351. {
  2352. // Have to check cube & 2D textures separately
  2353. if (texture->GetType() == Texture2D::GetTypeStatic())
  2354. {
  2355. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2356. RenderSurface* target = tex2D->GetRenderSurface();
  2357. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2358. target->QueueUpdate();
  2359. }
  2360. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2361. {
  2362. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2363. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2364. {
  2365. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2366. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2367. target->QueueUpdate();
  2368. }
  2369. }
  2370. }
  2371. }
  2372. // Flag as processed so we can early-out next time we come across this material on the same frame
  2373. material->MarkForAuxView(frame_.frameNumber_);
  2374. }
  2375. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2376. {
  2377. if (!batch.material_)
  2378. batch.material_ = renderer_->GetDefaultMaterial();
  2379. // Convert to instanced if possible
  2380. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer())
  2381. batch.geometryType_ = GEOM_INSTANCED;
  2382. if (batch.geometryType_ == GEOM_INSTANCED)
  2383. {
  2384. BatchGroupKey key(batch);
  2385. HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchQueue.batchGroups_.Find(key);
  2386. if (i == batchQueue.batchGroups_.End())
  2387. {
  2388. // Create a new group based on the batch
  2389. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2390. BatchGroup newGroup(batch);
  2391. newGroup.geometryType_ = GEOM_STATIC;
  2392. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2393. newGroup.CalculateSortKey();
  2394. i = batchQueue.batchGroups_.Insert(MakePair(key, newGroup));
  2395. }
  2396. int oldSize = i->second_.instances_.Size();
  2397. i->second_.AddTransforms(batch);
  2398. // Convert to using instancing shaders when the instancing limit is reached
  2399. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2400. {
  2401. i->second_.geometryType_ = GEOM_INSTANCED;
  2402. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2403. i->second_.CalculateSortKey();
  2404. }
  2405. }
  2406. else
  2407. {
  2408. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2409. batch.CalculateSortKey();
  2410. // If batch is static with multiple world transforms and cannot instance, we must push copies of the batch individually
  2411. if (batch.geometryType_ == GEOM_STATIC && batch.numWorldTransforms_ > 1)
  2412. {
  2413. unsigned numTransforms = batch.numWorldTransforms_;
  2414. batch.numWorldTransforms_ = 1;
  2415. for (unsigned i = 0; i < numTransforms; ++i)
  2416. {
  2417. // Move the transform pointer to generate copies of the batch which only refer to 1 world transform
  2418. batchQueue.batches_.Push(batch);
  2419. ++batch.worldTransform_;
  2420. }
  2421. }
  2422. else
  2423. batchQueue.batches_.Push(batch);
  2424. }
  2425. }
  2426. void View::PrepareInstancingBuffer()
  2427. {
  2428. PROFILE(PrepareInstancingBuffer);
  2429. unsigned totalInstances = 0;
  2430. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2431. totalInstances += i->second_.GetNumInstances();
  2432. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2433. {
  2434. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2435. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2436. totalInstances += i->litBaseBatches_.GetNumInstances();
  2437. totalInstances += i->litBatches_.GetNumInstances();
  2438. }
  2439. // If fail to set buffer size, fall back to per-group locking
  2440. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2441. {
  2442. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2443. unsigned freeIndex = 0;
  2444. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2445. if (!dest)
  2446. return;
  2447. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2448. i->second_.SetTransforms(dest, freeIndex);
  2449. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2450. {
  2451. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2452. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2453. i->litBaseBatches_.SetTransforms(dest, freeIndex);
  2454. i->litBatches_.SetTransforms(dest, freeIndex);
  2455. }
  2456. instancingBuffer->Unlock();
  2457. }
  2458. }
  2459. void View::SetupLightVolumeBatch(Batch& batch)
  2460. {
  2461. Light* light = batch.lightQueue_->light_;
  2462. LightType type = light->GetLightType();
  2463. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2464. float lightDist;
  2465. graphics_->SetBlendMode(light->IsNegative() ? BLEND_SUBTRACT : BLEND_ADD);
  2466. graphics_->SetDepthBias(0.0f, 0.0f);
  2467. graphics_->SetDepthWrite(false);
  2468. graphics_->SetFillMode(FILL_SOLID);
  2469. graphics_->SetClipPlane(false);
  2470. if (type != LIGHT_DIRECTIONAL)
  2471. {
  2472. if (type == LIGHT_POINT)
  2473. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2474. else
  2475. lightDist = light->GetFrustum().Distance(cameraPos);
  2476. // Draw front faces if not inside light volume
  2477. if (lightDist < camera_->GetNearClip() * 2.0f)
  2478. {
  2479. renderer_->SetCullMode(CULL_CW, camera_);
  2480. graphics_->SetDepthTest(CMP_GREATER);
  2481. }
  2482. else
  2483. {
  2484. renderer_->SetCullMode(CULL_CCW, camera_);
  2485. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2486. }
  2487. }
  2488. else
  2489. {
  2490. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2491. // refresh the directional light's model transform before rendering
  2492. light->GetVolumeTransform(camera_);
  2493. graphics_->SetCullMode(CULL_NONE);
  2494. graphics_->SetDepthTest(CMP_ALWAYS);
  2495. }
  2496. graphics_->SetScissorTest(false);
  2497. if (!noStencil_)
  2498. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2499. else
  2500. graphics_->SetStencilTest(false);
  2501. }
  2502. void View::RenderShadowMap(const LightBatchQueue& queue)
  2503. {
  2504. PROFILE(RenderShadowMap);
  2505. Texture2D* shadowMap = queue.shadowMap_;
  2506. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2507. graphics_->SetColorWrite(false);
  2508. graphics_->SetDrawAntialiased(true);
  2509. graphics_->SetFillMode(FILL_SOLID);
  2510. graphics_->SetClipPlane(false);
  2511. graphics_->SetStencilTest(false);
  2512. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2513. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  2514. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  2515. graphics_->SetDepthStencil(shadowMap);
  2516. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2517. graphics_->Clear(CLEAR_DEPTH);
  2518. // Set shadow depth bias
  2519. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2520. // Render each of the splits
  2521. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2522. {
  2523. float multiplier = 1.0f;
  2524. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2525. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2526. {
  2527. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2528. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2529. }
  2530. // Perform further modification of depth bias on OpenGL ES, as shadow calculations' precision is limited
  2531. float addition = 0.0f;
  2532. #ifdef GL_ES_VERSION_2_0
  2533. multiplier *= renderer_->GetMobileShadowBiasMul();
  2534. addition = renderer_->GetMobileShadowBiasAdd();
  2535. #endif
  2536. graphics_->SetDepthBias(multiplier * parameters.constantBias_ + addition, multiplier * parameters.slopeScaledBias_);
  2537. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2538. if (!shadowQueue.shadowBatches_.IsEmpty())
  2539. {
  2540. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2541. shadowQueue.shadowBatches_.Draw(this, false, false, true);
  2542. }
  2543. }
  2544. graphics_->SetColorWrite(true);
  2545. graphics_->SetDepthBias(0.0f, 0.0f);
  2546. }
  2547. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2548. {
  2549. // If using the backbuffer, return the backbuffer depth-stencil
  2550. if (!renderTarget)
  2551. return 0;
  2552. // Then check for linked depth-stencil
  2553. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2554. // Finally get one from Renderer
  2555. if (!depthStencil)
  2556. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2557. return depthStencil;
  2558. }
  2559. }