View.cpp 128 KB

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