View.cpp 124 KB

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