View.cpp 118 KB

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