View.cpp 122 KB

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