View.cpp 127 KB

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