View.cpp 117 KB

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