View.cpp 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964
  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.outputNames_.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(static_cast<Texture2D*>(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. destBatch.lightQueue_ = &lightQueue;
  902. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  903. }
  904. }
  905. }
  906. // Process lit geometries
  907. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  908. {
  909. Drawable* drawable = *j;
  910. drawable->AddLight(light);
  911. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  912. if (!drawable->GetMaxLights())
  913. GetLitBatches(drawable, lightQueue, alphaQueue);
  914. else
  915. maxLightsDrawables_.Insert(drawable);
  916. }
  917. // In deferred modes, store the light volume batch now
  918. if (deferred_)
  919. {
  920. Batch volumeBatch;
  921. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  922. volumeBatch.geometryType_ = GEOM_STATIC;
  923. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  924. volumeBatch.numWorldTransforms_ = 1;
  925. volumeBatch.camera_ = camera_;
  926. volumeBatch.lightQueue_ = &lightQueue;
  927. volumeBatch.distance_ = light->GetDistance();
  928. volumeBatch.material_ = 0;
  929. volumeBatch.pass_ = 0;
  930. volumeBatch.zone_ = 0;
  931. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVolumeCommand_->vertexShaderName_,
  932. lightVolumeCommand_->pixelShaderName_, lightVolumeCommand_->vertexShaderDefines_,
  933. lightVolumeCommand_->pixelShaderDefines_);
  934. lightQueue.volumeBatches_.Push(volumeBatch);
  935. }
  936. }
  937. // Per-vertex light
  938. else
  939. {
  940. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  941. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  942. {
  943. Drawable* drawable = *j;
  944. drawable->AddVertexLight(light);
  945. }
  946. }
  947. }
  948. }
  949. // Process drawables with limited per-pixel light count
  950. if (maxLightsDrawables_.Size())
  951. {
  952. PROFILE(GetMaxLightsBatches);
  953. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  954. {
  955. Drawable* drawable = *i;
  956. drawable->LimitLights();
  957. const PODVector<Light*>& lights = drawable->GetLights();
  958. for (unsigned i = 0; i < lights.Size(); ++i)
  959. {
  960. Light* light = lights[i];
  961. // Find the correct light queue again
  962. LightBatchQueue* queue = light->GetLightQueue();
  963. if (queue)
  964. GetLitBatches(drawable, *queue, alphaQueue);
  965. }
  966. }
  967. }
  968. }
  969. void View::GetBaseBatches()
  970. {
  971. PROFILE(GetBaseBatches);
  972. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  973. {
  974. Drawable* drawable = *i;
  975. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  976. if (type == UPDATE_MAIN_THREAD)
  977. nonThreadedGeometries_.Push(drawable);
  978. else if (type == UPDATE_WORKER_THREAD)
  979. threadedGeometries_.Push(drawable);
  980. const Vector<SourceBatch>& batches = drawable->GetBatches();
  981. bool vertexLightsProcessed = false;
  982. for (unsigned j = 0; j < batches.Size(); ++j)
  983. {
  984. const SourceBatch& srcBatch = batches[j];
  985. // Check here if the material refers to a rendertarget texture with camera(s) attached
  986. // Only check this for backbuffer views (null rendertarget)
  987. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  988. CheckMaterialForAuxView(srcBatch.material_);
  989. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  990. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  991. continue;
  992. // Check each of the scene passes
  993. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  994. {
  995. ScenePassInfo& info = scenePasses_[k];
  996. // Skip forward base pass if the corresponding litbase pass already exists
  997. if (info.passIndex_ == basePassIndex_ && j < 32 && drawable->HasBasePass(j))
  998. continue;
  999. Pass* pass = tech->GetSupportedPass(info.passIndex_);
  1000. if (!pass)
  1001. continue;
  1002. Batch destBatch(srcBatch);
  1003. destBatch.pass_ = pass;
  1004. destBatch.camera_ = camera_;
  1005. destBatch.zone_ = GetZone(drawable);
  1006. destBatch.isBase_ = true;
  1007. destBatch.lightMask_ = GetLightMask(drawable);
  1008. if (info.vertexLights_)
  1009. {
  1010. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  1011. if (drawableVertexLights.Size() && !vertexLightsProcessed)
  1012. {
  1013. // Limit vertex lights. If this is a deferred opaque batch, remove converted per-pixel lights,
  1014. // as they will be rendered as light volumes in any case, and drawing them also as vertex lights
  1015. // would result in double lighting
  1016. drawable->LimitVertexLights(deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE);
  1017. vertexLightsProcessed = true;
  1018. }
  1019. if (drawableVertexLights.Size())
  1020. {
  1021. // Find a vertex light queue. If not found, create new
  1022. unsigned long long hash = GetVertexLightQueueHash(drawableVertexLights);
  1023. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  1024. if (i == vertexLightQueues_.End())
  1025. {
  1026. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  1027. i->second_.light_ = 0;
  1028. i->second_.shadowMap_ = 0;
  1029. i->second_.vertexLights_ = drawableVertexLights;
  1030. }
  1031. destBatch.lightQueue_ = &(i->second_);
  1032. }
  1033. }
  1034. else
  1035. destBatch.lightQueue_ = 0;
  1036. bool allowInstancing = info.allowInstancing_;
  1037. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (destBatch.zone_->GetLightMask() & 0xff))
  1038. allowInstancing = false;
  1039. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  1040. }
  1041. }
  1042. }
  1043. }
  1044. void View::UpdateGeometries()
  1045. {
  1046. PROFILE(SortAndUpdateGeometry);
  1047. WorkQueue* queue = GetSubsystem<WorkQueue>();
  1048. // Sort batches
  1049. {
  1050. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1051. {
  1052. const RenderPathCommand& command = renderPath_->commands_[i];
  1053. if (!IsNecessary(command))
  1054. continue;
  1055. if (command.type_ == CMD_SCENEPASS)
  1056. {
  1057. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1058. item->priority_ = M_MAX_UNSIGNED;
  1059. item->workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork : SortBatchQueueBackToFrontWork;
  1060. item->start_ = &batchQueues_[command.passIndex_];
  1061. queue->AddWorkItem(item);
  1062. }
  1063. }
  1064. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1065. {
  1066. SharedPtr<WorkItem> lightItem = queue->GetFreeItem();
  1067. lightItem->priority_ = M_MAX_UNSIGNED;
  1068. lightItem->workFunction_ = SortLightQueueWork;
  1069. lightItem->start_ = &(*i);
  1070. queue->AddWorkItem(lightItem);
  1071. if (i->shadowSplits_.Size())
  1072. {
  1073. SharedPtr<WorkItem> shadowItem = queue->GetFreeItem();
  1074. shadowItem->priority_ = M_MAX_UNSIGNED;
  1075. shadowItem->workFunction_ = SortShadowQueueWork;
  1076. shadowItem->start_ = &(*i);
  1077. queue->AddWorkItem(shadowItem);
  1078. }
  1079. }
  1080. }
  1081. // Update geometries. Split into threaded and non-threaded updates.
  1082. {
  1083. if (threadedGeometries_.Size())
  1084. {
  1085. // In special cases (context loss, multi-view) a drawable may theoretically first have reported a threaded update, but will actually
  1086. // require a main thread update. Check these cases first and move as applicable. The threaded work routine will tolerate the null
  1087. // pointer holes that we leave to the threaded update queue.
  1088. for (PODVector<Drawable*>::Iterator i = threadedGeometries_.Begin(); i != threadedGeometries_.End(); ++i)
  1089. {
  1090. if ((*i)->GetUpdateGeometryType() == UPDATE_MAIN_THREAD)
  1091. {
  1092. nonThreadedGeometries_.Push(*i);
  1093. *i = 0;
  1094. }
  1095. }
  1096. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  1097. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  1098. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  1099. for (int i = 0; i < numWorkItems; ++i)
  1100. {
  1101. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  1102. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  1103. end = start + drawablesPerItem;
  1104. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1105. item->priority_ = M_MAX_UNSIGNED;
  1106. item->workFunction_ = UpdateDrawableGeometriesWork;
  1107. item->aux_ = const_cast<FrameInfo*>(&frame_);
  1108. item->start_ = &(*start);
  1109. item->end_ = &(*end);
  1110. queue->AddWorkItem(item);
  1111. start = end;
  1112. }
  1113. }
  1114. // While the work queue is processed, update non-threaded geometries
  1115. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  1116. (*i)->UpdateGeometry(frame_);
  1117. }
  1118. // Finally ensure all threaded work has completed
  1119. queue->Complete(M_MAX_UNSIGNED);
  1120. }
  1121. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue)
  1122. {
  1123. Light* light = lightQueue.light_;
  1124. Zone* zone = GetZone(drawable);
  1125. const Vector<SourceBatch>& batches = drawable->GetBatches();
  1126. bool allowLitBase = useLitBase_ && !lightQueue.negative_ && light == drawable->GetFirstLight() &&
  1127. drawable->GetVertexLights().Empty() && !zone->GetAmbientGradient();
  1128. for (unsigned i = 0; i < batches.Size(); ++i)
  1129. {
  1130. const SourceBatch& srcBatch = batches[i];
  1131. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1132. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1133. continue;
  1134. // Do not create pixel lit forward passes for materials that render into the G-buffer
  1135. if (gBufferPassIndex_ != M_MAX_UNSIGNED && tech->HasPass(gBufferPassIndex_))
  1136. continue;
  1137. Batch destBatch(srcBatch);
  1138. bool isLitAlpha = false;
  1139. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1140. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1141. if (i < 32 && allowLitBase)
  1142. {
  1143. destBatch.pass_ = tech->GetSupportedPass(litBasePassIndex_);
  1144. if (destBatch.pass_)
  1145. {
  1146. destBatch.isBase_ = true;
  1147. drawable->SetBasePass(i);
  1148. }
  1149. else
  1150. destBatch.pass_ = tech->GetSupportedPass(lightPassIndex_);
  1151. }
  1152. else
  1153. destBatch.pass_ = tech->GetSupportedPass(lightPassIndex_);
  1154. // If no lit pass, check for lit alpha
  1155. if (!destBatch.pass_)
  1156. {
  1157. destBatch.pass_ = tech->GetSupportedPass(litAlphaPassIndex_);
  1158. isLitAlpha = true;
  1159. }
  1160. // Skip if material does not receive light at all
  1161. if (!destBatch.pass_)
  1162. continue;
  1163. destBatch.camera_ = camera_;
  1164. destBatch.lightQueue_ = &lightQueue;
  1165. destBatch.zone_ = zone;
  1166. if (!isLitAlpha)
  1167. {
  1168. if (destBatch.isBase_)
  1169. AddBatchToQueue(lightQueue.litBaseBatches_, destBatch, tech);
  1170. else
  1171. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1172. }
  1173. else if (alphaQueue)
  1174. {
  1175. // Transparent batches can not be instanced, and shadows on transparencies can only be rendered if shadow maps are
  1176. // not reused
  1177. AddBatchToQueue(*alphaQueue, destBatch, tech, false, !renderer_->GetReuseShadowMaps());
  1178. }
  1179. }
  1180. }
  1181. void View::ExecuteRenderPathCommands()
  1182. {
  1183. // If not reusing shadowmaps, render all of them first
  1184. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1185. {
  1186. PROFILE(RenderShadowMaps);
  1187. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1188. {
  1189. if (i->shadowMap_)
  1190. RenderShadowMap(*i);
  1191. }
  1192. }
  1193. {
  1194. PROFILE(ExecuteRenderPath);
  1195. // Set for safety in case of empty renderpath
  1196. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1197. currentViewportTexture_ = 0;
  1198. bool viewportModified = false;
  1199. bool isPingponging = false;
  1200. unsigned lastCommandIndex = 0;
  1201. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1202. {
  1203. RenderPathCommand& command = renderPath_->commands_[i];
  1204. if (IsNecessary(command))
  1205. lastCommandIndex = i;
  1206. }
  1207. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1208. {
  1209. RenderPathCommand& command = renderPath_->commands_[i];
  1210. if (!IsNecessary(command))
  1211. continue;
  1212. bool viewportRead = CheckViewportRead(command);
  1213. bool viewportWrite = CheckViewportWrite(command);
  1214. bool beginPingpong = CheckPingpong(i);
  1215. // Has the viewport been modified and will be read as a texture by the current command?
  1216. if (viewportRead && viewportModified)
  1217. {
  1218. // Start pingponging without a blit if already rendering to the substitute render target
  1219. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1220. isPingponging = true;
  1221. // If not using pingponging, simply resolve/copy to the first viewport texture
  1222. if (!isPingponging)
  1223. {
  1224. if (!currentRenderTarget_)
  1225. {
  1226. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1227. currentViewportTexture_ = viewportTextures_[0];
  1228. viewportModified = false;
  1229. }
  1230. else
  1231. {
  1232. if (viewportWrite)
  1233. {
  1234. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1235. viewportTextures_[0]->GetRenderSurface(), false);
  1236. currentViewportTexture_ = viewportTextures_[0];
  1237. viewportModified = false;
  1238. }
  1239. else
  1240. {
  1241. // If the current render target is already a texture, and we are not writing to it, can read that
  1242. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1243. // will do both read and write, and then we need to blit / resolve
  1244. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1245. }
  1246. }
  1247. }
  1248. else
  1249. {
  1250. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1251. viewportTextures_[1] = viewportTextures_[0];
  1252. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1253. currentViewportTexture_ = viewportTextures_[0];
  1254. viewportModified = false;
  1255. }
  1256. }
  1257. if (beginPingpong)
  1258. isPingponging = true;
  1259. // Determine viewport write target
  1260. if (viewportWrite)
  1261. {
  1262. if (isPingponging)
  1263. {
  1264. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1265. // If the render path ends into a quad, it can be redirected to the final render target
  1266. // However, on OpenGL we can not reliably do this in case the final target is the backbuffer, and we want to
  1267. // render depth buffer sensitive debug geometry afterward (backbuffer and textures can not share depth)
  1268. #ifndef URHO3D_OPENGL
  1269. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1270. #else
  1271. if (i == lastCommandIndex && command.type_ == CMD_QUAD && renderTarget_)
  1272. #endif
  1273. currentRenderTarget_ = renderTarget_;
  1274. }
  1275. else
  1276. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1277. }
  1278. switch (command.type_)
  1279. {
  1280. case CMD_CLEAR:
  1281. {
  1282. PROFILE(ClearRenderTarget);
  1283. Color clearColor = command.clearColor_;
  1284. if (command.useFogColor_)
  1285. clearColor = farClipZone_->GetFogColor();
  1286. SetRenderTargets(command);
  1287. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1288. }
  1289. break;
  1290. case CMD_SCENEPASS:
  1291. {
  1292. BatchQueue& queue = batchQueues_[command.passIndex_];
  1293. if (!queue.IsEmpty())
  1294. {
  1295. PROFILE(RenderScenePass);
  1296. SetRenderTargets(command);
  1297. bool allowDepthWrite = SetTextures(command);
  1298. graphics_->SetFillMode(camera_->GetFillMode());
  1299. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1300. queue.Draw(this, command.markToStencil_, false, allowDepthWrite);
  1301. }
  1302. }
  1303. break;
  1304. case CMD_QUAD:
  1305. {
  1306. PROFILE(RenderQuad);
  1307. SetRenderTargets(command);
  1308. SetTextures(command);
  1309. RenderQuad(command);
  1310. }
  1311. break;
  1312. case CMD_FORWARDLIGHTS:
  1313. // Render shadow maps + opaque objects' additive lighting
  1314. if (!lightQueues_.Empty())
  1315. {
  1316. PROFILE(RenderLights);
  1317. SetRenderTargets(command);
  1318. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1319. {
  1320. // If reusing shadowmaps, render each of them before the lit batches
  1321. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1322. {
  1323. RenderShadowMap(*i);
  1324. SetRenderTargets(command);
  1325. }
  1326. bool allowDepthWrite = SetTextures(command);
  1327. graphics_->SetFillMode(camera_->GetFillMode());
  1328. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1329. // Draw base (replace blend) batches first
  1330. i->litBaseBatches_.Draw(this, false, false, allowDepthWrite);
  1331. // Then, if there are additive passes, optimize the light and draw them
  1332. if (!i->litBatches_.IsEmpty())
  1333. {
  1334. renderer_->OptimizeLightByScissor(i->light_, camera_);
  1335. if (!noStencil_)
  1336. renderer_->OptimizeLightByStencil(i->light_, camera_);
  1337. i->litBatches_.Draw(this, false, true, allowDepthWrite);
  1338. }
  1339. }
  1340. graphics_->SetScissorTest(false);
  1341. graphics_->SetStencilTest(false);
  1342. }
  1343. break;
  1344. case CMD_LIGHTVOLUMES:
  1345. // Render shadow maps + light volumes
  1346. if (!lightQueues_.Empty())
  1347. {
  1348. PROFILE(RenderLightVolumes);
  1349. SetRenderTargets(command);
  1350. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1351. {
  1352. // If reusing shadowmaps, render each of them before the lit batches
  1353. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1354. {
  1355. RenderShadowMap(*i);
  1356. SetRenderTargets(command);
  1357. }
  1358. SetTextures(command);
  1359. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1360. {
  1361. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1362. i->volumeBatches_[j].Draw(this, false);
  1363. }
  1364. }
  1365. graphics_->SetScissorTest(false);
  1366. graphics_->SetStencilTest(false);
  1367. }
  1368. break;
  1369. case CMD_RENDERUI:
  1370. {
  1371. SetRenderTargets(command);
  1372. GetSubsystem<UI>()->Render(false);
  1373. }
  1374. break;
  1375. default:
  1376. break;
  1377. }
  1378. // If current command output to the viewport, mark it modified
  1379. if (viewportWrite)
  1380. viewportModified = true;
  1381. }
  1382. }
  1383. }
  1384. void View::SetRenderTargets(RenderPathCommand& command)
  1385. {
  1386. unsigned index = 0;
  1387. bool useColorWrite = true;
  1388. bool useCustomDepth = false;
  1389. while (index < command.outputNames_.Size())
  1390. {
  1391. if (!command.outputNames_[index].Compare("viewport", false))
  1392. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1393. else
  1394. {
  1395. StringHash nameHash(command.outputNames_[index]);
  1396. if (renderTargets_.Contains(nameHash))
  1397. {
  1398. Texture2D* texture = renderTargets_[nameHash];
  1399. // Check for depth only rendering (by specifying a depth texture as the sole output)
  1400. if (!index && command.outputNames_.Size() == 1 && texture && (texture->GetFormat() ==
  1401. Graphics::GetReadableDepthFormat() || texture->GetFormat() == Graphics::GetDepthStencilFormat()))
  1402. {
  1403. useColorWrite = false;
  1404. useCustomDepth = true;
  1405. #ifndef URHO3D_OPENGL
  1406. // On D3D actual depth-only rendering is illegal, we need a color rendertarget
  1407. if (!depthOnlyDummyTexture_)
  1408. {
  1409. depthOnlyDummyTexture_ = renderer_->GetScreenBuffer(texture->GetWidth(), texture->GetHeight(),
  1410. graphics_->GetDummyColorFormat(), false, false);
  1411. }
  1412. #endif
  1413. graphics_->SetRenderTarget(0, depthOnlyDummyTexture_);
  1414. graphics_->SetDepthStencil(texture);
  1415. }
  1416. else
  1417. graphics_->SetRenderTarget(index, texture);
  1418. }
  1419. else
  1420. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1421. }
  1422. ++index;
  1423. }
  1424. while (index < MAX_RENDERTARGETS)
  1425. {
  1426. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1427. ++index;
  1428. }
  1429. if (command.depthStencilName_.Length())
  1430. {
  1431. Texture2D* depthTexture = renderTargets_[StringHash(command.depthStencilName_)];
  1432. if (depthTexture)
  1433. {
  1434. useCustomDepth = true;
  1435. graphics_->SetDepthStencil(depthTexture);
  1436. }
  1437. }
  1438. // When rendering to the final destination rendertarget, use the actual viewport. Otherwise texture rendertargets will be
  1439. // viewport-sized, so they should use their full size as the viewport
  1440. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  1441. IntRect viewport = (graphics_->GetRenderTarget(0) == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  1442. rtSizeNow.y_);
  1443. if (!useCustomDepth)
  1444. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1445. graphics_->SetViewport(viewport);
  1446. graphics_->SetColorWrite(useColorWrite);
  1447. }
  1448. bool View::SetTextures(RenderPathCommand& command)
  1449. {
  1450. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1451. bool allowDepthWrite = true;
  1452. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1453. {
  1454. if (command.textureNames_[i].Empty())
  1455. continue;
  1456. // Bind the rendered output
  1457. if (!command.textureNames_[i].Compare("viewport", false))
  1458. {
  1459. graphics_->SetTexture(i, currentViewportTexture_);
  1460. continue;
  1461. }
  1462. // Bind a rendertarget
  1463. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1464. if (j != renderTargets_.End())
  1465. {
  1466. graphics_->SetTexture(i, j->second_);
  1467. // Check if the current depth stencil is being sampled
  1468. if (graphics_->GetDepthStencil() && j->second_ == graphics_->GetDepthStencil()->GetParentTexture())
  1469. allowDepthWrite = false;
  1470. continue;
  1471. }
  1472. // Bind a texture from the resource system
  1473. Texture* texture;
  1474. // Detect cube/3D textures by file extension: they are defined by an XML file
  1475. if (GetExtension(command.textureNames_[i]) == ".xml")
  1476. {
  1477. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1478. #ifdef DESKTOP_GRAPHICS
  1479. if (i == TU_VOLUMEMAP)
  1480. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1481. else
  1482. #endif
  1483. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1484. }
  1485. else
  1486. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1487. if (texture)
  1488. graphics_->SetTexture(i, texture);
  1489. else
  1490. {
  1491. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1492. command.textureNames_[i] = String::EMPTY;
  1493. }
  1494. }
  1495. return allowDepthWrite;
  1496. }
  1497. void View::RenderQuad(RenderPathCommand& command)
  1498. {
  1499. if (command.vertexShaderName_.Empty() || command.pixelShaderName_.Empty())
  1500. return;
  1501. // If shader can not be found, clear it from the command to prevent redundant attempts
  1502. ShaderVariation* vs = graphics_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1503. if (!vs)
  1504. command.vertexShaderName_ = String::EMPTY;
  1505. ShaderVariation* ps = graphics_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1506. if (!ps)
  1507. command.pixelShaderName_ = String::EMPTY;
  1508. // Set shaders & shader parameters and textures
  1509. graphics_->SetShaders(vs, ps);
  1510. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1511. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1512. graphics_->SetShaderParameter(k->first_, k->second_);
  1513. SetGlobalShaderParameters();
  1514. SetCameraShaderParameters(camera_, false);
  1515. // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
  1516. IntRect viewport = graphics_->GetViewport();
  1517. IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
  1518. SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
  1519. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1520. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1521. {
  1522. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1523. if (!rtInfo.enabled_)
  1524. continue;
  1525. StringHash nameHash(rtInfo.name_);
  1526. if (!renderTargets_.Contains(nameHash))
  1527. continue;
  1528. String invSizeName = rtInfo.name_ + "InvSize";
  1529. String offsetsName = rtInfo.name_ + "Offsets";
  1530. float width = (float)renderTargets_[nameHash]->GetWidth();
  1531. float height = (float)renderTargets_[nameHash]->GetHeight();
  1532. const Vector2& pixelUVOffset = Graphics::GetPixelUVOffset();
  1533. graphics_->SetShaderParameter(invSizeName, Vector2(1.0f / width, 1.0f / height));
  1534. graphics_->SetShaderParameter(offsetsName, Vector2(pixelUVOffset.x_ / width, pixelUVOffset.y_ / height));
  1535. }
  1536. graphics_->SetBlendMode(BLEND_REPLACE);
  1537. graphics_->SetDepthTest(CMP_ALWAYS);
  1538. graphics_->SetDepthWrite(false);
  1539. graphics_->SetFillMode(FILL_SOLID);
  1540. graphics_->SetClipPlane(false);
  1541. graphics_->SetScissorTest(false);
  1542. graphics_->SetStencilTest(false);
  1543. DrawFullscreenQuad(false);
  1544. }
  1545. bool View::IsNecessary(const RenderPathCommand& command)
  1546. {
  1547. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1548. !batchQueues_[command.passIndex_].IsEmpty());
  1549. }
  1550. bool View::CheckViewportRead(const RenderPathCommand& command)
  1551. {
  1552. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1553. {
  1554. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1555. return true;
  1556. }
  1557. return false;
  1558. }
  1559. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1560. {
  1561. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1562. {
  1563. if (!command.outputNames_[i].Compare("viewport", false))
  1564. return true;
  1565. }
  1566. return false;
  1567. }
  1568. bool View::CheckPingpong(unsigned index)
  1569. {
  1570. // Current command must be a viewport-reading & writing quad to begin the pingpong chain
  1571. RenderPathCommand& current = renderPath_->commands_[index];
  1572. if (current.type_ != CMD_QUAD || !CheckViewportRead(current) || !CheckViewportWrite(current))
  1573. return false;
  1574. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1575. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1576. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1577. {
  1578. RenderPathCommand& command = renderPath_->commands_[i];
  1579. if (!IsNecessary(command))
  1580. continue;
  1581. if (CheckViewportWrite(command))
  1582. {
  1583. if (command.type_ != CMD_QUAD)
  1584. return false;
  1585. }
  1586. }
  1587. return true;
  1588. }
  1589. void View::AllocateScreenBuffers()
  1590. {
  1591. bool needSubstitute = false;
  1592. unsigned numViewportTextures = 0;
  1593. depthOnlyDummyTexture_ = 0;
  1594. #ifdef URHO3D_OPENGL
  1595. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1596. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1597. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1598. Graphics::GetRGBAFormat()))
  1599. needSubstitute = true;
  1600. // Also need substitute if rendering to backbuffer using a custom (readable) depth buffer
  1601. if (!renderTarget_ && !needSubstitute)
  1602. {
  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() && command.outputNames_.Size() && !command.outputNames_[0].Compare("viewport",
  1609. false))
  1610. {
  1611. needSubstitute = true;
  1612. break;
  1613. }
  1614. }
  1615. }
  1616. #endif
  1617. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1618. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1619. needSubstitute = true;
  1620. // If viewport is smaller than whole texture/backbuffer in deferred rendering, need to reserve a buffer, as the G-buffer
  1621. // textures will be sized equal to the viewport
  1622. if (viewSize_.x_ < rtSize_.x_ || viewSize_.y_ < rtSize_.y_)
  1623. {
  1624. if (deferred_)
  1625. needSubstitute = true;
  1626. else if (!needSubstitute)
  1627. {
  1628. // Check also if using MRT without deferred rendering and rendering to the viewport and another texture,
  1629. // or using custom depth
  1630. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1631. {
  1632. const RenderPathCommand& command = renderPath_->commands_[i];
  1633. if (!IsNecessary(command))
  1634. continue;
  1635. if (command.depthStencilName_.Length())
  1636. needSubstitute = true;
  1637. if (!needSubstitute && command.outputNames_.Size() > 1)
  1638. {
  1639. for (unsigned j = 0; j < command.outputNames_.Size(); ++j)
  1640. {
  1641. if (!command.outputNames_[j].Compare("viewport", false))
  1642. {
  1643. needSubstitute = true;
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. if (needSubstitute)
  1649. break;
  1650. }
  1651. }
  1652. }
  1653. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1654. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1655. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1656. if (renderer_->GetHDRRendering())
  1657. {
  1658. format = Graphics::GetRGBAFloat16Format();
  1659. needSubstitute = true;
  1660. }
  1661. #ifdef URHO3D_OPENGL
  1662. if (deferred_ && !renderer_->GetHDRRendering())
  1663. format = Graphics::GetRGBAFormat();
  1664. #endif
  1665. // Check for commands which read the viewport, or pingpong between viewport textures
  1666. bool hasViewportRead = false;
  1667. bool hasPingpong = false;
  1668. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1669. {
  1670. const RenderPathCommand& command = renderPath_->commands_[i];
  1671. if (!IsNecessary(command))
  1672. continue;
  1673. if (CheckViewportRead(command))
  1674. hasViewportRead = true;
  1675. if (!hasPingpong && CheckPingpong(i))
  1676. hasPingpong = true;
  1677. }
  1678. if (hasViewportRead)
  1679. {
  1680. ++numViewportTextures;
  1681. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1682. // is specified, there is no choice
  1683. #ifdef GL_ES_VERSION_2_0
  1684. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1685. needSubstitute = true;
  1686. #endif
  1687. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1688. // does not support reading a cube map
  1689. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1690. needSubstitute = true;
  1691. // If rendering to a texture, but the viewport is less than the whole texture, use a substitute to ensure
  1692. // postprocessing shaders will never read outside the viewport
  1693. if (renderTarget_ && (viewSize_.x_ < renderTarget_->GetWidth() || viewSize_.y_ < renderTarget_->GetHeight()))
  1694. needSubstitute = true;
  1695. if (hasPingpong && !needSubstitute)
  1696. ++numViewportTextures;
  1697. }
  1698. // Allocate screen buffers with filtering active in case the quad commands need that
  1699. // Follow the sRGB mode of the destination render target
  1700. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1701. substituteRenderTarget_ = needSubstitute ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true,
  1702. sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1703. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1704. {
  1705. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, true, sRGB) :
  1706. (Texture2D*)0;
  1707. }
  1708. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1709. if (numViewportTextures == 1 && substituteRenderTarget_)
  1710. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1711. // Allocate extra render targets defined by the rendering path
  1712. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1713. {
  1714. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1715. if (!rtInfo.enabled_)
  1716. continue;
  1717. float width = rtInfo.size_.x_;
  1718. float height = rtInfo.size_.y_;
  1719. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1720. {
  1721. width = (float)viewSize_.x_ / Max(width, M_EPSILON);
  1722. height = (float)viewSize_.y_ / Max(height, M_EPSILON);
  1723. }
  1724. else if (rtInfo.sizeMode_ == SIZE_VIEWPORTMULTIPLIER)
  1725. {
  1726. width = (float)viewSize_.x_ * width;
  1727. height = (float)viewSize_.y_ * height;
  1728. }
  1729. int intWidth = (int)(width + 0.5f);
  1730. int intHeight = (int)(height + 0.5f);
  1731. // If the rendertarget is persistent, key it with a hash derived from the RT name and the view's pointer
  1732. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(intWidth, intHeight, rtInfo.format_, rtInfo.filtered_,
  1733. rtInfo.sRGB_, rtInfo.persistent_ ? StringHash(rtInfo.name_).Value() + (unsigned)(size_t)this : 0);
  1734. }
  1735. }
  1736. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1737. {
  1738. if (!source)
  1739. return;
  1740. PROFILE(BlitFramebuffer);
  1741. // If blitting to the destination rendertarget, use the actual viewport. Intermediate textures on the other hand
  1742. // are always viewport-sized
  1743. IntVector2 srcSize(source->GetWidth(), source->GetHeight());
  1744. IntVector2 destSize = destination ? IntVector2(destination->GetWidth(), destination->GetHeight()) : IntVector2(
  1745. graphics_->GetWidth(), graphics_->GetHeight());
  1746. IntRect srcRect = (source->GetRenderSurface() == renderTarget_) ? viewRect_ : IntRect(0, 0, srcSize.x_, srcSize.y_);
  1747. IntRect destRect = (destination == renderTarget_) ? viewRect_ : IntRect(0, 0, destSize.x_, destSize.y_);
  1748. graphics_->SetBlendMode(BLEND_REPLACE);
  1749. graphics_->SetDepthTest(CMP_ALWAYS);
  1750. graphics_->SetDepthWrite(depthWrite);
  1751. graphics_->SetFillMode(FILL_SOLID);
  1752. graphics_->SetClipPlane(false);
  1753. graphics_->SetScissorTest(false);
  1754. graphics_->SetStencilTest(false);
  1755. graphics_->SetRenderTarget(0, destination);
  1756. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1757. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1758. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1759. graphics_->SetViewport(destRect);
  1760. static const String shaderName("CopyFramebuffer");
  1761. graphics_->SetShaders(graphics_->GetShader(VS, shaderName), graphics_->GetShader(PS, shaderName));
  1762. SetGBufferShaderParameters(srcSize, srcRect);
  1763. graphics_->SetTexture(TU_DIFFUSE, source);
  1764. DrawFullscreenQuad(false);
  1765. }
  1766. void View::DrawFullscreenQuad(bool nearQuad)
  1767. {
  1768. Geometry* geometry = renderer_->GetQuadGeometry();
  1769. Matrix3x4 model = Matrix3x4::IDENTITY;
  1770. Matrix4 projection = Matrix4::IDENTITY;
  1771. #ifdef URHO3D_OPENGL
  1772. if (camera_ && camera_->GetFlipVertical())
  1773. projection.m11_ = -1.0f;
  1774. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1775. #else
  1776. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1777. #endif
  1778. graphics_->SetCullMode(CULL_NONE);
  1779. graphics_->SetShaderParameter(VSP_MODEL, model);
  1780. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1781. graphics_->ClearTransformSources();
  1782. geometry->Draw(graphics_);
  1783. }
  1784. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1785. {
  1786. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1787. float halfViewSize = camera->GetHalfViewSize();
  1788. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1789. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1790. {
  1791. Drawable* occluder = *i;
  1792. bool erase = false;
  1793. if (!occluder->IsInView(frame_, true))
  1794. occluder->UpdateBatches(frame_);
  1795. // Check occluder's draw distance (in main camera view)
  1796. float maxDistance = occluder->GetDrawDistance();
  1797. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1798. {
  1799. // Check that occluder is big enough on the screen
  1800. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1801. float diagonal = box.Size().Length();
  1802. float compare;
  1803. if (!camera->IsOrthographic())
  1804. compare = diagonal * halfViewSize / occluder->GetDistance();
  1805. else
  1806. compare = diagonal * invOrthoSize;
  1807. if (compare < occluderSizeThreshold_)
  1808. erase = true;
  1809. else
  1810. {
  1811. // Store amount of triangles divided by screen size as a sorting key
  1812. // (best occluders are big and have few triangles)
  1813. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1814. }
  1815. }
  1816. else
  1817. erase = true;
  1818. if (erase)
  1819. i = occluders.Erase(i);
  1820. else
  1821. ++i;
  1822. }
  1823. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1824. if (occluders.Size())
  1825. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1826. }
  1827. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1828. {
  1829. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1830. buffer->Clear();
  1831. for (unsigned i = 0; i < occluders.Size(); ++i)
  1832. {
  1833. Drawable* occluder = occluders[i];
  1834. if (i > 0)
  1835. {
  1836. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1837. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1838. continue;
  1839. }
  1840. // Check for running out of triangles
  1841. if (!occluder->DrawOcclusion(buffer))
  1842. break;
  1843. }
  1844. buffer->BuildDepthHierarchy();
  1845. }
  1846. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1847. {
  1848. Light* light = query.light_;
  1849. LightType type = light->GetLightType();
  1850. const Frustum& frustum = camera_->GetFrustum();
  1851. // Check if light should be shadowed
  1852. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1853. // If shadow distance non-zero, check it
  1854. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1855. isShadowed = false;
  1856. // OpenGL ES can not support point light shadows
  1857. #ifdef GL_ES_VERSION_2_0
  1858. if (isShadowed && type == LIGHT_POINT)
  1859. isShadowed = false;
  1860. #endif
  1861. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1862. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1863. query.litGeometries_.Clear();
  1864. switch (type)
  1865. {
  1866. case LIGHT_DIRECTIONAL:
  1867. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1868. {
  1869. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1870. query.litGeometries_.Push(geometries_[i]);
  1871. }
  1872. break;
  1873. case LIGHT_SPOT:
  1874. {
  1875. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY,
  1876. camera_->GetViewMask());
  1877. octree_->GetDrawables(octreeQuery);
  1878. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1879. {
  1880. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1881. query.litGeometries_.Push(tempDrawables[i]);
  1882. }
  1883. }
  1884. break;
  1885. case LIGHT_POINT:
  1886. {
  1887. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1888. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1889. octree_->GetDrawables(octreeQuery);
  1890. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1891. {
  1892. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1893. query.litGeometries_.Push(tempDrawables[i]);
  1894. }
  1895. }
  1896. break;
  1897. }
  1898. // If no lit geometries or not shadowed, no need to process shadow cameras
  1899. if (query.litGeometries_.Empty() || !isShadowed)
  1900. {
  1901. query.numSplits_ = 0;
  1902. return;
  1903. }
  1904. // Determine number of shadow cameras and setup their initial positions
  1905. SetupShadowCameras(query);
  1906. // Process each split for shadow casters
  1907. query.shadowCasters_.Clear();
  1908. for (unsigned i = 0; i < query.numSplits_; ++i)
  1909. {
  1910. Camera* shadowCamera = query.shadowCameras_[i];
  1911. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1912. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1913. // For point light check that the face is visible: if not, can skip the split
  1914. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1915. continue;
  1916. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1917. if (type == LIGHT_DIRECTIONAL)
  1918. {
  1919. if (minZ_ > query.shadowFarSplits_[i])
  1920. continue;
  1921. if (maxZ_ < query.shadowNearSplits_[i])
  1922. continue;
  1923. // Reuse lit geometry query for all except directional lights
  1924. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1925. camera_->GetViewMask());
  1926. octree_->GetDrawables(query);
  1927. }
  1928. // Check which shadow casters actually contribute to the shadowing
  1929. ProcessShadowCasters(query, tempDrawables, i);
  1930. }
  1931. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1932. // only cost has been the shadow camera setup & queries
  1933. if (query.shadowCasters_.Empty())
  1934. query.numSplits_ = 0;
  1935. }
  1936. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1937. {
  1938. Light* light = query.light_;
  1939. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1940. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1941. const Matrix3x4& lightView = shadowCamera->GetView();
  1942. const Matrix4& lightProj = shadowCamera->GetProjection();
  1943. LightType type = light->GetLightType();
  1944. query.shadowCasterBox_[splitIndex].defined_ = false;
  1945. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1946. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1947. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1948. Frustum lightViewFrustum;
  1949. if (type != LIGHT_DIRECTIONAL)
  1950. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1951. else
  1952. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1953. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1954. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1955. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1956. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1957. return;
  1958. BoundingBox lightViewBox;
  1959. BoundingBox lightProjBox;
  1960. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1961. {
  1962. Drawable* drawable = *i;
  1963. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1964. // Check for that first
  1965. if (!drawable->GetCastShadows())
  1966. continue;
  1967. // Check shadow mask
  1968. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1969. continue;
  1970. // For point light, check that this drawable is inside the split shadow camera frustum
  1971. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1972. continue;
  1973. // Check shadow distance
  1974. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1975. // times. However, this should not cause problems as no scene modification happens at this point.
  1976. if (!drawable->IsInView(frame_, true))
  1977. drawable->UpdateBatches(frame_);
  1978. float maxShadowDistance = drawable->GetShadowDistance();
  1979. float drawDistance = drawable->GetDrawDistance();
  1980. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1981. maxShadowDistance = drawDistance;
  1982. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1983. continue;
  1984. // Project shadow caster bounding box to light view space for visibility check
  1985. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1986. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1987. {
  1988. // Merge to shadow caster bounding box (only needed for focused spot lights) and add to the list
  1989. if (type == LIGHT_SPOT && light->GetShadowFocus().focus_)
  1990. {
  1991. lightProjBox = lightViewBox.Projected(lightProj);
  1992. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1993. }
  1994. query.shadowCasters_.Push(drawable);
  1995. }
  1996. }
  1997. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1998. }
  1999. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  2000. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  2001. {
  2002. if (shadowCamera->IsOrthographic())
  2003. {
  2004. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  2005. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  2006. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2007. }
  2008. else
  2009. {
  2010. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  2011. if (drawable->IsInView(frame_))
  2012. return true;
  2013. // For perspective lights, extrusion direction depends on the position of the shadow caster
  2014. Vector3 center = lightViewBox.Center();
  2015. Ray extrusionRay(center, center);
  2016. float extrusionDistance = shadowCamera->GetFarClip();
  2017. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  2018. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  2019. float sizeFactor = extrusionDistance / originalDistance;
  2020. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  2021. // than necessary, so the test will be conservative
  2022. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  2023. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  2024. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  2025. lightViewBox.Merge(extrudedBox);
  2026. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2027. }
  2028. }
  2029. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  2030. {
  2031. unsigned width = shadowMap->GetWidth();
  2032. unsigned height = shadowMap->GetHeight();
  2033. switch (light->GetLightType())
  2034. {
  2035. case LIGHT_DIRECTIONAL:
  2036. {
  2037. int numSplits = light->GetNumShadowSplits();
  2038. if (numSplits == 1)
  2039. return IntRect(0, 0, width, height);
  2040. else if (numSplits == 2)
  2041. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  2042. else
  2043. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  2044. (splitIndex / 2 + 1) * height / 2);
  2045. }
  2046. case LIGHT_SPOT:
  2047. return IntRect(0, 0, width, height);
  2048. case LIGHT_POINT:
  2049. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  2050. (splitIndex / 2 + 1) * height / 3);
  2051. }
  2052. return IntRect();
  2053. }
  2054. void View::SetupShadowCameras(LightQueryResult& query)
  2055. {
  2056. Light* light = query.light_;
  2057. int splits = 0;
  2058. switch (light->GetLightType())
  2059. {
  2060. case LIGHT_DIRECTIONAL:
  2061. {
  2062. const CascadeParameters& cascade = light->GetShadowCascade();
  2063. float nearSplit = camera_->GetNearClip();
  2064. float farSplit;
  2065. int numSplits = light->GetNumShadowSplits();
  2066. while (splits < numSplits)
  2067. {
  2068. // If split is completely beyond camera far clip, we are done
  2069. if (nearSplit > camera_->GetFarClip())
  2070. break;
  2071. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  2072. if (farSplit <= nearSplit)
  2073. break;
  2074. // Setup the shadow camera for the split
  2075. Camera* shadowCamera = renderer_->GetShadowCamera();
  2076. query.shadowCameras_[splits] = shadowCamera;
  2077. query.shadowNearSplits_[splits] = nearSplit;
  2078. query.shadowFarSplits_[splits] = farSplit;
  2079. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  2080. nearSplit = farSplit;
  2081. ++splits;
  2082. }
  2083. }
  2084. break;
  2085. case LIGHT_SPOT:
  2086. {
  2087. Camera* shadowCamera = renderer_->GetShadowCamera();
  2088. query.shadowCameras_[0] = shadowCamera;
  2089. Node* cameraNode = shadowCamera->GetNode();
  2090. Node* lightNode = light->GetNode();
  2091. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  2092. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2093. shadowCamera->SetFarClip(light->GetRange());
  2094. shadowCamera->SetFov(light->GetFov());
  2095. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  2096. splits = 1;
  2097. }
  2098. break;
  2099. case LIGHT_POINT:
  2100. {
  2101. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  2102. {
  2103. Camera* shadowCamera = renderer_->GetShadowCamera();
  2104. query.shadowCameras_[i] = shadowCamera;
  2105. Node* cameraNode = shadowCamera->GetNode();
  2106. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  2107. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  2108. cameraNode->SetDirection(*directions[i]);
  2109. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2110. shadowCamera->SetFarClip(light->GetRange());
  2111. shadowCamera->SetFov(90.0f);
  2112. shadowCamera->SetAspectRatio(1.0f);
  2113. }
  2114. splits = MAX_CUBEMAP_FACES;
  2115. }
  2116. break;
  2117. }
  2118. query.numSplits_ = splits;
  2119. }
  2120. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  2121. {
  2122. Node* shadowCameraNode = shadowCamera->GetNode();
  2123. Node* lightNode = light->GetNode();
  2124. float extrusionDistance = camera_->GetFarClip();
  2125. const FocusParameters& parameters = light->GetShadowFocus();
  2126. // Calculate initial position & rotation
  2127. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  2128. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  2129. // Calculate main camera shadowed frustum in light's view space
  2130. farSplit = Min(farSplit, camera_->GetFarClip());
  2131. // Use the scene Z bounds to limit frustum size if applicable
  2132. if (parameters.focus_)
  2133. {
  2134. nearSplit = Max(minZ_, nearSplit);
  2135. farSplit = Min(maxZ_, farSplit);
  2136. }
  2137. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  2138. Polyhedron frustumVolume;
  2139. frustumVolume.Define(splitFrustum);
  2140. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  2141. if (parameters.focus_)
  2142. {
  2143. BoundingBox litGeometriesBox;
  2144. for (unsigned i = 0; i < geometries_.Size(); ++i)
  2145. {
  2146. Drawable* drawable = geometries_[i];
  2147. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  2148. (GetLightMask(drawable) & light->GetLightMask()))
  2149. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  2150. }
  2151. if (litGeometriesBox.defined_)
  2152. {
  2153. frustumVolume.Clip(litGeometriesBox);
  2154. // If volume became empty, restore it to avoid zero size
  2155. if (frustumVolume.Empty())
  2156. frustumVolume.Define(splitFrustum);
  2157. }
  2158. }
  2159. // Transform frustum volume to light space
  2160. const Matrix3x4& lightView = shadowCamera->GetView();
  2161. frustumVolume.Transform(lightView);
  2162. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  2163. BoundingBox shadowBox;
  2164. if (!parameters.nonUniform_)
  2165. shadowBox.Define(Sphere(frustumVolume));
  2166. else
  2167. shadowBox.Define(frustumVolume);
  2168. shadowCamera->SetOrthographic(true);
  2169. shadowCamera->SetAspectRatio(1.0f);
  2170. shadowCamera->SetNearClip(0.0f);
  2171. shadowCamera->SetFarClip(shadowBox.max_.z_);
  2172. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  2173. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  2174. }
  2175. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2176. const BoundingBox& shadowCasterBox)
  2177. {
  2178. const FocusParameters& parameters = light->GetShadowFocus();
  2179. float shadowMapWidth = (float)(shadowViewport.Width());
  2180. LightType type = light->GetLightType();
  2181. if (type == LIGHT_DIRECTIONAL)
  2182. {
  2183. BoundingBox shadowBox;
  2184. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  2185. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  2186. shadowBox.min_.y_ = -shadowBox.max_.y_;
  2187. shadowBox.min_.x_ = -shadowBox.max_.x_;
  2188. // Requantize and snap to shadow map texels
  2189. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2190. }
  2191. if (type == LIGHT_SPOT && parameters.focus_)
  2192. {
  2193. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2194. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2195. float viewSize = Max(viewSizeX, viewSizeY);
  2196. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2197. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2198. float quantize = parameters.quantize_ * invOrthoSize;
  2199. float minView = parameters.minView_ * invOrthoSize;
  2200. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2201. if (viewSize < 1.0f)
  2202. shadowCamera->SetZoom(1.0f / viewSize);
  2203. }
  2204. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2205. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2206. if (shadowCamera->GetZoom() >= 1.0f)
  2207. {
  2208. if (light->GetLightType() != LIGHT_POINT)
  2209. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2210. else
  2211. {
  2212. #ifdef URHO3D_OPENGL
  2213. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2214. #else
  2215. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2216. #endif
  2217. }
  2218. }
  2219. }
  2220. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2221. const BoundingBox& viewBox)
  2222. {
  2223. Node* shadowCameraNode = shadowCamera->GetNode();
  2224. const FocusParameters& parameters = light->GetShadowFocus();
  2225. float shadowMapWidth = (float)(shadowViewport.Width());
  2226. float minX = viewBox.min_.x_;
  2227. float minY = viewBox.min_.y_;
  2228. float maxX = viewBox.max_.x_;
  2229. float maxY = viewBox.max_.y_;
  2230. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2231. Vector2 viewSize(maxX - minX, maxY - minY);
  2232. // Quantize size to reduce swimming
  2233. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2234. if (parameters.nonUniform_)
  2235. {
  2236. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2237. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2238. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2239. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2240. }
  2241. else if (parameters.focus_)
  2242. {
  2243. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2244. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2245. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2246. viewSize.y_ = viewSize.x_;
  2247. }
  2248. shadowCamera->SetOrthoSize(viewSize);
  2249. // Center shadow camera to the view space bounding box
  2250. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2251. Vector3 adjust(center.x_, center.y_, 0.0f);
  2252. shadowCameraNode->Translate(rot * adjust, TS_WORLD);
  2253. // If the shadow map viewport is known, snap to whole texels
  2254. if (shadowMapWidth > 0.0f)
  2255. {
  2256. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2257. // Take into account that shadow map border will not be used
  2258. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2259. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2260. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2261. shadowCameraNode->Translate(rot * snap, TS_WORLD);
  2262. }
  2263. }
  2264. void View::FindZone(Drawable* drawable)
  2265. {
  2266. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2267. int bestPriority = M_MIN_INT;
  2268. Zone* newZone = 0;
  2269. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2270. // (possibly incorrect) and must be re-evaluated on the next frame
  2271. bool temporary = !camera_->GetFrustum().IsInside(center);
  2272. // First check if the current zone remains a conclusive result
  2273. Zone* lastZone = drawable->GetZone();
  2274. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2275. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2276. newZone = lastZone;
  2277. else
  2278. {
  2279. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2280. {
  2281. Zone* zone = *i;
  2282. int priority = zone->GetPriority();
  2283. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2284. {
  2285. newZone = zone;
  2286. bestPriority = priority;
  2287. }
  2288. }
  2289. }
  2290. drawable->SetZone(newZone, temporary);
  2291. }
  2292. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2293. {
  2294. if (!material)
  2295. return renderer_->GetDefaultMaterial()->GetTechniques()[0].technique_;
  2296. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2297. // If only one technique, no choice
  2298. if (techniques.Size() == 1)
  2299. return techniques[0].technique_;
  2300. else
  2301. {
  2302. float lodDistance = drawable->GetLodDistance();
  2303. // Check for suitable technique. Techniques should be ordered like this:
  2304. // Most distant & highest quality
  2305. // Most distant & lowest quality
  2306. // Second most distant & highest quality
  2307. // ...
  2308. for (unsigned i = 0; i < techniques.Size(); ++i)
  2309. {
  2310. const TechniqueEntry& entry = techniques[i];
  2311. Technique* tech = entry.technique_;
  2312. if (!tech || (!tech->IsSupported()) || materialQuality_ < entry.qualityLevel_)
  2313. continue;
  2314. if (lodDistance >= entry.lodDistance_)
  2315. return tech;
  2316. }
  2317. // If no suitable technique found, fallback to the last
  2318. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2319. }
  2320. }
  2321. void View::CheckMaterialForAuxView(Material* material)
  2322. {
  2323. const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material->GetTextures();
  2324. for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
  2325. {
  2326. Texture* texture = i->second_.Get();
  2327. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2328. {
  2329. // Have to check cube & 2D textures separately
  2330. if (texture->GetType() == Texture2D::GetTypeStatic())
  2331. {
  2332. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2333. RenderSurface* target = tex2D->GetRenderSurface();
  2334. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2335. target->QueueUpdate();
  2336. }
  2337. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2338. {
  2339. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2340. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2341. {
  2342. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2343. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2344. target->QueueUpdate();
  2345. }
  2346. }
  2347. }
  2348. }
  2349. // Flag as processed so we can early-out next time we come across this material on the same frame
  2350. material->MarkForAuxView(frame_.frameNumber_);
  2351. }
  2352. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2353. {
  2354. if (!batch.material_)
  2355. batch.material_ = renderer_->GetDefaultMaterial();
  2356. // Convert to instanced if possible
  2357. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer())
  2358. batch.geometryType_ = GEOM_INSTANCED;
  2359. if (batch.geometryType_ == GEOM_INSTANCED)
  2360. {
  2361. BatchGroupKey key(batch);
  2362. HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchQueue.batchGroups_.Find(key);
  2363. if (i == batchQueue.batchGroups_.End())
  2364. {
  2365. // Create a new group based on the batch
  2366. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2367. BatchGroup newGroup(batch);
  2368. newGroup.geometryType_ = GEOM_STATIC;
  2369. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2370. newGroup.CalculateSortKey();
  2371. i = batchQueue.batchGroups_.Insert(MakePair(key, newGroup));
  2372. }
  2373. int oldSize = i->second_.instances_.Size();
  2374. i->second_.AddTransforms(batch);
  2375. // Convert to using instancing shaders when the instancing limit is reached
  2376. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2377. {
  2378. i->second_.geometryType_ = GEOM_INSTANCED;
  2379. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2380. i->second_.CalculateSortKey();
  2381. }
  2382. }
  2383. else
  2384. {
  2385. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2386. batch.CalculateSortKey();
  2387. // If batch is static with multiple world transforms and cannot instance, we must push copies of the batch individually
  2388. if (batch.geometryType_ == GEOM_STATIC && batch.numWorldTransforms_ > 1)
  2389. {
  2390. unsigned numTransforms = batch.numWorldTransforms_;
  2391. batch.numWorldTransforms_ = 1;
  2392. for (unsigned i = 0; i < numTransforms; ++i)
  2393. {
  2394. // Move the transform pointer to generate copies of the batch which only refer to 1 world transform
  2395. batchQueue.batches_.Push(batch);
  2396. ++batch.worldTransform_;
  2397. }
  2398. }
  2399. else
  2400. batchQueue.batches_.Push(batch);
  2401. }
  2402. }
  2403. void View::PrepareInstancingBuffer()
  2404. {
  2405. PROFILE(PrepareInstancingBuffer);
  2406. unsigned totalInstances = 0;
  2407. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2408. totalInstances += i->second_.GetNumInstances();
  2409. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2410. {
  2411. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2412. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2413. totalInstances += i->litBaseBatches_.GetNumInstances();
  2414. totalInstances += i->litBatches_.GetNumInstances();
  2415. }
  2416. if (!totalInstances || !renderer_->ResizeInstancingBuffer(totalInstances))
  2417. return;
  2418. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2419. unsigned freeIndex = 0;
  2420. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2421. if (!dest)
  2422. return;
  2423. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2424. i->second_.SetTransforms(dest, freeIndex);
  2425. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2426. {
  2427. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2428. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2429. i->litBaseBatches_.SetTransforms(dest, freeIndex);
  2430. i->litBatches_.SetTransforms(dest, freeIndex);
  2431. }
  2432. instancingBuffer->Unlock();
  2433. }
  2434. void View::SetupLightVolumeBatch(Batch& batch)
  2435. {
  2436. Light* light = batch.lightQueue_->light_;
  2437. LightType type = light->GetLightType();
  2438. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2439. float lightDist;
  2440. graphics_->SetBlendMode(light->IsNegative() ? BLEND_SUBTRACT : BLEND_ADD);
  2441. graphics_->SetDepthBias(0.0f, 0.0f);
  2442. graphics_->SetDepthWrite(false);
  2443. graphics_->SetFillMode(FILL_SOLID);
  2444. graphics_->SetClipPlane(false);
  2445. if (type != LIGHT_DIRECTIONAL)
  2446. {
  2447. if (type == LIGHT_POINT)
  2448. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2449. else
  2450. lightDist = light->GetFrustum().Distance(cameraPos);
  2451. // Draw front faces if not inside light volume
  2452. if (lightDist < camera_->GetNearClip() * 2.0f)
  2453. {
  2454. renderer_->SetCullMode(CULL_CW, camera_);
  2455. graphics_->SetDepthTest(CMP_GREATER);
  2456. }
  2457. else
  2458. {
  2459. renderer_->SetCullMode(CULL_CCW, camera_);
  2460. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2461. }
  2462. }
  2463. else
  2464. {
  2465. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2466. // refresh the directional light's model transform before rendering
  2467. light->GetVolumeTransform(camera_);
  2468. graphics_->SetCullMode(CULL_NONE);
  2469. graphics_->SetDepthTest(CMP_ALWAYS);
  2470. }
  2471. graphics_->SetScissorTest(false);
  2472. if (!noStencil_)
  2473. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2474. else
  2475. graphics_->SetStencilTest(false);
  2476. }
  2477. void View::RenderShadowMap(const LightBatchQueue& queue)
  2478. {
  2479. PROFILE(RenderShadowMap);
  2480. Texture2D* shadowMap = queue.shadowMap_;
  2481. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2482. graphics_->SetColorWrite(false);
  2483. graphics_->SetFillMode(FILL_SOLID);
  2484. graphics_->SetClipPlane(false);
  2485. graphics_->SetStencilTest(false);
  2486. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2487. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  2488. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  2489. graphics_->SetDepthStencil(shadowMap);
  2490. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2491. graphics_->Clear(CLEAR_DEPTH);
  2492. // Set shadow depth bias
  2493. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2494. // Render each of the splits
  2495. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2496. {
  2497. float multiplier = 1.0f;
  2498. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2499. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2500. {
  2501. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2502. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2503. // Quantize multiplier to prevent creation of too many rasterizer states on D3D11
  2504. multiplier = (int)(multiplier * 10.0f) / 10.0f;
  2505. }
  2506. // Perform further modification of depth bias on OpenGL ES, as shadow calculations' precision is limited
  2507. float addition = 0.0f;
  2508. #ifdef GL_ES_VERSION_2_0
  2509. multiplier *= renderer_->GetMobileShadowBiasMul();
  2510. addition = renderer_->GetMobileShadowBiasAdd();
  2511. #endif
  2512. graphics_->SetDepthBias(multiplier * parameters.constantBias_ + addition, multiplier * parameters.slopeScaledBias_);
  2513. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2514. if (!shadowQueue.shadowBatches_.IsEmpty())
  2515. {
  2516. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2517. shadowQueue.shadowBatches_.Draw(this, false, false, true);
  2518. }
  2519. }
  2520. graphics_->SetColorWrite(true);
  2521. graphics_->SetDepthBias(0.0f, 0.0f);
  2522. }
  2523. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2524. {
  2525. // If using the backbuffer, return the backbuffer depth-stencil
  2526. if (!renderTarget)
  2527. return 0;
  2528. // Then check for linked depth-stencil
  2529. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2530. // Finally get one from Renderer
  2531. if (!depthStencil)
  2532. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2533. return depthStencil;
  2534. }
  2535. }