View.cpp 127 KB

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