View.cpp 117 KB

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