View.cpp 119 KB

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