View.cpp 126 KB

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