View.cpp 119 KB

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