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