View.cpp 127 KB

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