View.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "Renderer.h"
  34. #include "Profiler.h"
  35. #include "Scene.h"
  36. #include "ShaderVariation.h"
  37. #include "Sort.h"
  38. #include "Technique.h"
  39. #include "Texture2D.h"
  40. #include "TextureCube.h"
  41. #include "VertexBuffer.h"
  42. #include "View.h"
  43. #include "WorkQueue.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const Vector3 directions[] =
  47. {
  48. Vector3(1.0f, 0.0f, 0.0f),
  49. Vector3(-1.0f, 0.0f, 0.0f),
  50. Vector3(0.0f, 1.0f, 0.0f),
  51. Vector3(0.0f, -1.0f, 0.0f),
  52. Vector3(0.0f, 0.0f, 1.0f),
  53. Vector3(0.0f, 0.0f, -1.0f)
  54. };
  55. static const int CHECK_DRAWABLES_PER_WORK_ITEM = 64;
  56. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  57. {
  58. View* view = reinterpret_cast<View*>(item->aux_);
  59. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  60. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  61. Drawable** unculledStart = &view->tempDrawables_[0][0] + view->unculledDrawableStart_;
  62. OcclusionBuffer* buffer = view->occlusionBuffer_;
  63. while (start != end)
  64. {
  65. Drawable* drawable = *start;
  66. bool useOcclusion = start < unculledStart;
  67. unsigned char flags = drawable->GetDrawableFlags();
  68. ++start;
  69. if (flags & DRAWABLE_ZONE)
  70. continue;
  71. drawable->UpdateDistance(view->frame_);
  72. // If draw distance non-zero, check it
  73. float maxDistance = drawable->GetDrawDistance();
  74. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  75. continue;
  76. if (buffer && useOcclusion && !buffer->IsVisible(drawable->GetWorldBoundingBox()))
  77. continue;
  78. drawable->MarkInView(view->frame_);
  79. // For geometries, clear lights and find new zone if necessary
  80. if (flags & DRAWABLE_GEOMETRY)
  81. {
  82. drawable->ClearLights();
  83. if (!drawable->GetZone() && !view->cameraZoneOverride_)
  84. view->FindZone(drawable, threadIndex);
  85. }
  86. }
  87. }
  88. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  89. {
  90. View* view = reinterpret_cast<View*>(item->aux_);
  91. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  92. view->ProcessLight(*query, threadIndex);
  93. }
  94. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  95. {
  96. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  97. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  98. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  99. while (start != end)
  100. {
  101. Drawable* drawable = *start;
  102. drawable->UpdateGeometry(frame);
  103. ++start;
  104. }
  105. }
  106. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  107. {
  108. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  109. queue->SortFrontToBack();
  110. }
  111. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  112. {
  113. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  114. queue->SortBackToFront();
  115. }
  116. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  117. {
  118. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  119. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  120. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  121. start->litBatches_.SortFrontToBack();
  122. }
  123. OBJECTTYPESTATIC(View);
  124. View::View(Context* context) :
  125. Object(context),
  126. graphics_(GetSubsystem<Graphics>()),
  127. renderer_(GetSubsystem<Renderer>()),
  128. octree_(0),
  129. camera_(0),
  130. cameraZone_(0),
  131. farClipZone_(0),
  132. renderTarget_(0),
  133. depthStencil_(0)
  134. {
  135. frame_.camera_ = 0;
  136. // Create octree query vectors for each thread
  137. tempDrawables_.Resize(GetSubsystem<WorkQueue>()->GetNumThreads() + 1);
  138. tempZones_.Resize(GetSubsystem<WorkQueue>()->GetNumThreads() + 1);
  139. }
  140. View::~View()
  141. {
  142. }
  143. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  144. {
  145. if (!viewport.scene_ || !viewport.camera_)
  146. return false;
  147. // If scene is loading asynchronously, it is incomplete and should not be rendered
  148. if (viewport.scene_->IsAsyncLoading())
  149. return false;
  150. Octree* octree = viewport.scene_->GetComponent<Octree>();
  151. if (!octree)
  152. return false;
  153. // Check for the render texture being too large
  154. if (renderer_->GetLightPrepass() && renderTarget)
  155. {
  156. if (renderTarget->GetWidth() > graphics_->GetWidth() || renderTarget->GetHeight() > graphics_->GetHeight())
  157. {
  158. // Display message only once per render target, do not spam each frame
  159. if (gBufferErrorDisplayed_.Find(renderTarget) == gBufferErrorDisplayed_.End())
  160. {
  161. gBufferErrorDisplayed_.Insert(renderTarget);
  162. LOGERROR("Render texture is larger than the G-buffer, can not render");
  163. }
  164. return false;
  165. }
  166. }
  167. octree_ = octree;
  168. camera_ = viewport.camera_;
  169. renderTarget_ = renderTarget;
  170. if (!renderTarget)
  171. depthStencil_ = 0;
  172. else
  173. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  174. // Validate the rect and calculate size. If zero rect, use whole render target size
  175. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  176. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  177. if (viewport.rect_ != IntRect::ZERO)
  178. {
  179. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  180. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  181. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  182. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  183. }
  184. else
  185. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  186. width_ = screenRect_.right_ - screenRect_.left_;
  187. height_ = screenRect_.bottom_ - screenRect_.top_;
  188. // Set possible quality overrides from the camera
  189. drawShadows_ = renderer_->GetDrawShadows();
  190. materialQuality_ = renderer_->GetMaterialQuality();
  191. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  192. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  193. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  194. materialQuality_ = QUALITY_LOW;
  195. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  196. drawShadows_ = false;
  197. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  198. maxOccluderTriangles_ = 0;
  199. return true;
  200. }
  201. void View::Update(const FrameInfo& frame)
  202. {
  203. if (!camera_ || !octree_)
  204. return;
  205. frame_.camera_ = camera_;
  206. frame_.timeStep_ = frame.timeStep_;
  207. frame_.frameNumber_ = frame.frameNumber_;
  208. frame_.viewSize_ = IntVector2(width_, height_);
  209. // Clear old light scissor cache, geometry, light, occluder & batch lists
  210. lightScissorCache_.Clear();
  211. geometries_.Clear();
  212. allGeometries_.Clear();
  213. geometryDepthBounds_.Clear();
  214. lights_.Clear();
  215. zones_.Clear();
  216. occluders_.Clear();
  217. baseQueue_.Clear();
  218. preAlphaQueue_.Clear();
  219. gbufferQueue_.Clear();
  220. alphaQueue_.Clear();
  221. postAlphaQueue_.Clear();
  222. lightQueues_.Clear();
  223. vertexLightQueues_.Clear();
  224. // Do not update if camera projection is illegal
  225. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  226. if (!camera_->IsProjectionValid())
  227. return;
  228. // Set automatic aspect ratio if required
  229. if (camera_->GetAutoAspectRatio())
  230. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  231. // Cache the camera frustum to avoid recalculating it constantly
  232. frustum_ = camera_->GetFrustum();
  233. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  234. renderer_->ResetShadowMapAllocations();
  235. GetDrawables();
  236. GetBatches();
  237. UpdateGeometries();
  238. }
  239. void View::Render()
  240. {
  241. if (!octree_ || !camera_)
  242. return;
  243. // Forget parameter sources from the previous view
  244. graphics_->ClearParameterSources();
  245. // If stream offset is supported, write all instance transforms to a single large buffer
  246. // Else we must lock the instance buffer for each batch group
  247. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  248. PrepareInstancingBuffer();
  249. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  250. // again to ensure correct projection will be used
  251. if (camera_->GetAutoAspectRatio())
  252. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  253. graphics_->SetColorWrite(true);
  254. graphics_->SetFillMode(FILL_SOLID);
  255. // Bind the face selection and indirection cube maps for point light shadows
  256. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  257. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  258. // Render
  259. if (renderer_->GetLightPrepass())
  260. RenderBatchesLightPrepass();
  261. else
  262. RenderBatchesForward();
  263. graphics_->SetScissorTest(false);
  264. graphics_->SetStencilTest(false);
  265. graphics_->ResetStreamFrequencies();
  266. // If this is a main view, draw the associated debug geometry now
  267. if (!renderTarget_)
  268. {
  269. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  270. if (scene)
  271. {
  272. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  273. if (debug)
  274. {
  275. debug->SetView(camera_);
  276. debug->Render();
  277. }
  278. }
  279. }
  280. // "Forget" the camera, octree and zone after rendering
  281. camera_ = 0;
  282. octree_ = 0;
  283. cameraZone_ = 0;
  284. farClipZone_ = 0;
  285. occlusionBuffer_ = 0;
  286. frame_.camera_ = 0;
  287. }
  288. void View::GetDrawables()
  289. {
  290. PROFILE(GetDrawables);
  291. WorkQueue* queue = GetSubsystem<WorkQueue>();
  292. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  293. // Perform one octree query to get everything, then examine the results
  294. FrustumOctreeQuery query(tempDrawables, frustum_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT | DRAWABLE_ZONE);
  295. octree_->GetDrawables(query);
  296. // Add unculled geometries & lights
  297. unculledDrawableStart_ = tempDrawables.Size();
  298. octree_->GetUnculledDrawables(tempDrawables, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  299. // Get zones and occluders first
  300. highestZonePriority_ = M_MIN_INT;
  301. int bestPriority = M_MIN_INT;
  302. Vector3 cameraPos = camera_->GetWorldPosition();
  303. // Get default zone first in case we do not have zones defined
  304. Zone* defaultZone = renderer_->GetDefaultZone();
  305. cameraZone_ = farClipZone_ = defaultZone;
  306. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  307. {
  308. Drawable* drawable = *i;
  309. unsigned char flags = drawable->GetDrawableFlags();
  310. if (flags & DRAWABLE_ZONE)
  311. {
  312. Zone* zone = static_cast<Zone*>(drawable);
  313. zones_.Push(zone);
  314. int priority = zone->GetPriority();
  315. if (priority > highestZonePriority_)
  316. highestZonePriority_ = priority;
  317. if (zone->IsInside(cameraPos) && priority > bestPriority)
  318. {
  319. cameraZone_ = zone;
  320. bestPriority = priority;
  321. }
  322. }
  323. else if (flags & DRAWABLE_GEOMETRY && drawable->IsOccluder())
  324. occluders_.Push(drawable);
  325. }
  326. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  327. cameraZoneOverride_ = cameraZone_->GetOverride();
  328. if (!cameraZoneOverride_)
  329. {
  330. Vector3 farClipPos = cameraPos + camera_->GetNode()->GetWorldDirection() * Vector3(0, 0, camera_->GetFarClip());
  331. bestPriority = M_MIN_INT;
  332. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  333. {
  334. int priority = (*i)->GetPriority();
  335. if ((*i)->IsInside(farClipPos) && priority > bestPriority)
  336. {
  337. farClipZone_ = *i;
  338. bestPriority = priority;
  339. }
  340. }
  341. }
  342. if (farClipZone_ == defaultZone)
  343. farClipZone_ = cameraZone_;
  344. // If occlusion in use, get & render the occluders
  345. occlusionBuffer_ = 0;
  346. if (maxOccluderTriangles_ > 0)
  347. {
  348. UpdateOccluders(occluders_, camera_);
  349. if (occluders_.Size())
  350. {
  351. PROFILE(DrawOcclusion);
  352. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  353. DrawOccluders(occlusionBuffer_, occluders_);
  354. }
  355. }
  356. // Check visibility and find zones for moved drawables in worker threads
  357. {
  358. WorkItem item;
  359. item.workFunction_ = CheckVisibilityWork;
  360. item.aux_ = this;
  361. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  362. while (start != tempDrawables.End())
  363. {
  364. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  365. if (end - start > CHECK_DRAWABLES_PER_WORK_ITEM)
  366. end = start + CHECK_DRAWABLES_PER_WORK_ITEM;
  367. item.start_ = &(*start);
  368. item.end_ = &(*end);
  369. queue->AddWorkItem(item);
  370. start = end;
  371. }
  372. queue->Complete();
  373. }
  374. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  375. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  376. sceneBox_.defined_ = false;
  377. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  378. sceneViewBox_.defined_ = false;
  379. Matrix3x4 view(camera_->GetInverseWorldTransform());
  380. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  381. {
  382. Drawable* drawable = tempDrawables[i];
  383. unsigned char flags = drawable->GetDrawableFlags();
  384. if (flags & DRAWABLE_ZONE || !drawable->IsInView(frame_))
  385. continue;
  386. if (flags & DRAWABLE_GEOMETRY)
  387. {
  388. // Expand the scene bounding boxes. However, do not take "infinite" objects such as the skybox into account,
  389. // as the bounding boxes are also used for shadow focusing
  390. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  391. BoundingBox geomViewBox = geomBox.Transformed(view);
  392. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  393. {
  394. sceneBox_.Merge(geomBox);
  395. sceneViewBox_.Merge(geomViewBox);
  396. }
  397. // Store depth info for split directional light queries
  398. GeometryDepthBounds bounds;
  399. bounds.min_ = geomViewBox.min_.z_;
  400. bounds.max_ = geomViewBox.max_.z_;
  401. geometryDepthBounds_.Push(bounds);
  402. geometries_.Push(drawable);
  403. allGeometries_.Push(drawable);
  404. }
  405. else if (flags & DRAWABLE_LIGHT)
  406. {
  407. Light* light = static_cast<Light*>(drawable);
  408. lights_.Push(light);
  409. }
  410. }
  411. // Sort the lights to brightest/closest first
  412. for (unsigned i = 0; i < lights_.Size(); ++i)
  413. {
  414. Light* light = lights_[i];
  415. light->SetIntensitySortValue(camera_->GetDistance(light->GetWorldPosition()));
  416. }
  417. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  418. }
  419. void View::GetBatches()
  420. {
  421. WorkQueue* queue = GetSubsystem<WorkQueue>();
  422. bool prepass = renderer_->GetLightPrepass();
  423. // Process lit geometries and shadow casters for each light
  424. {
  425. PROFILE_MULTIPLE(ProcessLights, lights_.Size());
  426. lightQueryResults_.Resize(lights_.Size());
  427. WorkItem item;
  428. item.workFunction_ = ProcessLightWork;
  429. item.aux_ = this;
  430. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  431. {
  432. LightQueryResult& query = lightQueryResults_[i];
  433. query.light_ = lights_[i];
  434. item.start_ = &query;
  435. queue->AddWorkItem(item);
  436. }
  437. // Ensure all lights have been processed before proceeding
  438. queue->Complete();
  439. }
  440. // Build light queues and lit batches
  441. {
  442. bool fallback = graphics_->GetFallback();
  443. maxLightsDrawables_.Clear();
  444. lightQueueMapping_.Clear();
  445. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  446. {
  447. const LightQueryResult& query = *i;
  448. // If light has no affected geometries, no need to process further
  449. if (query.litGeometries_.Empty())
  450. continue;
  451. PROFILE(GetLightBatches);
  452. Light* light = query.light_;
  453. // Per-pixel light
  454. if (!light->GetPerVertex())
  455. {
  456. unsigned shadowSplits = query.numSplits_;
  457. // Initialize light queue. Store light-to-queue mapping so that the queue can be found later
  458. lightQueues_.Resize(lightQueues_.Size() + 1);
  459. LightBatchQueue& lightQueue = lightQueues_.Back();
  460. lightQueueMapping_[light] = &lightQueue;
  461. lightQueue.light_ = light;
  462. lightQueue.litBatches_.Clear();
  463. lightQueue.volumeBatches_.Clear();
  464. // Allocate shadow map now
  465. lightQueue.shadowMap_ = 0;
  466. if (shadowSplits > 0)
  467. {
  468. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, width_, height_);
  469. // If did not manage to get a shadow map, convert the light to unshadowed
  470. if (!lightQueue.shadowMap_)
  471. shadowSplits = 0;
  472. }
  473. // Setup shadow batch queues
  474. lightQueue.shadowSplits_.Resize(shadowSplits);
  475. for (unsigned j = 0; j < shadowSplits; ++j)
  476. {
  477. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  478. Camera* shadowCamera = query.shadowCameras_[j];
  479. shadowQueue.shadowCamera_ = shadowCamera;
  480. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  481. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  482. // Setup the shadow split viewport and finalize shadow camera parameters
  483. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  484. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  485. // Loop through shadow casters
  486. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  487. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  488. {
  489. Drawable* drawable = *k;
  490. if (!drawable->IsInView(frame_, false))
  491. {
  492. drawable->MarkInView(frame_, false);
  493. allGeometries_.Push(drawable);
  494. }
  495. unsigned numBatches = drawable->GetNumBatches();
  496. for (unsigned l = 0; l < numBatches; ++l)
  497. {
  498. Batch shadowBatch;
  499. drawable->GetBatch(shadowBatch, frame_, l);
  500. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  501. if (!shadowBatch.geometry_ || !tech)
  502. continue;
  503. Pass* pass = tech->GetPass(PASS_SHADOW);
  504. // Skip if material has no shadow pass
  505. if (!pass)
  506. continue;
  507. // Fill the rest of the batch
  508. shadowBatch.camera_ = shadowCamera;
  509. shadowBatch.zone_ = GetZone(drawable);
  510. shadowBatch.lightQueue_ = &lightQueue;
  511. FinalizeBatch(shadowBatch, tech, pass);
  512. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  513. }
  514. }
  515. }
  516. // Process lit geometries
  517. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  518. {
  519. Drawable* drawable = *j;
  520. drawable->AddLight(light);
  521. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  522. if (!drawable->GetMaxLights())
  523. GetLitBatches(drawable, lightQueue);
  524. else
  525. maxLightsDrawables_.Insert(drawable);
  526. }
  527. // In light pre-pass mode, store the light volume batch now
  528. if (prepass)
  529. {
  530. Batch volumeBatch;
  531. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  532. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  533. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  534. volumeBatch.camera_ = camera_;
  535. volumeBatch.lightQueue_ = &lightQueue;
  536. volumeBatch.distance_ = light->GetDistance();
  537. volumeBatch.material_ = 0;
  538. volumeBatch.pass_ = 0;
  539. volumeBatch.zone_ = 0;
  540. renderer_->SetLightVolumeBatchShaders(volumeBatch);
  541. lightQueue.volumeBatches_.Push(volumeBatch);
  542. }
  543. }
  544. // Per-vertex light
  545. else
  546. {
  547. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  548. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  549. {
  550. Drawable* drawable = *j;
  551. drawable->AddVertexLight(light);
  552. }
  553. }
  554. }
  555. }
  556. // Process drawables with limited per-pixel light count
  557. if (maxLightsDrawables_.Size())
  558. {
  559. PROFILE(GetMaxLightsBatches);
  560. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  561. {
  562. Drawable* drawable = *i;
  563. drawable->LimitLights();
  564. const PODVector<Light*>& lights = drawable->GetLights();
  565. for (unsigned i = 0; i < lights.Size(); ++i)
  566. {
  567. Light* light = lights[i];
  568. // Find the correct light queue again
  569. Map<Light*, LightBatchQueue*>::Iterator j = lightQueueMapping_.Find(light);
  570. if (j != lightQueueMapping_.End())
  571. GetLitBatches(drawable, *(j->second_));
  572. }
  573. }
  574. }
  575. // Build base pass batches
  576. {
  577. PROFILE(GetBaseBatches);
  578. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  579. {
  580. Drawable* drawable = *i;
  581. unsigned numBatches = drawable->GetNumBatches();
  582. for (unsigned j = 0; j < numBatches; ++j)
  583. {
  584. Batch baseBatch;
  585. drawable->GetBatch(baseBatch, frame_, j);
  586. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  587. if (!baseBatch.geometry_ || !tech)
  588. continue;
  589. // Check here if the material technique refers to a render target texture with camera(s) attached
  590. // Only check this for the main view (null render target)
  591. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  592. CheckMaterialForAuxView(baseBatch.material_);
  593. // Fill the rest of the batch
  594. baseBatch.camera_ = camera_;
  595. baseBatch.zone_ = GetZone(drawable);
  596. baseBatch.isBase_ = true;
  597. Pass* pass = 0;
  598. // In light prepass mode check for G-buffer and material passes first
  599. if (prepass)
  600. {
  601. pass = tech->GetPass(PASS_GBUFFER);
  602. if (pass)
  603. {
  604. // Allow G-buffer pass instancing only if lightmask matches zone lightmask
  605. baseBatch.lightMask_ = GetLightMask(drawable);
  606. FinalizeBatch(baseBatch, tech, pass, baseBatch.lightMask_ == (baseBatch.zone_->GetLightMask() & 0xff));
  607. gbufferQueue_.AddBatch(baseBatch);
  608. pass = tech->GetPass(PASS_MATERIAL);
  609. }
  610. }
  611. // Next check for forward base pass
  612. if (!pass)
  613. pass = tech->GetPass(PASS_BASE);
  614. if (pass)
  615. {
  616. // Check for vertex lights (both forward unlit and light pre-pass material pass)
  617. const PODVector<Light*>& vertexLights = drawable->GetVertexLights();
  618. if (!vertexLights.Empty())
  619. {
  620. drawable->LimitVertexLights();
  621. // Find a vertex light queue. If not found, create new
  622. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  623. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  624. if (i == vertexLightQueues_.End())
  625. {
  626. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  627. i->second_.light_ = 0;
  628. i->second_.shadowMap_ = 0;
  629. i->second_.vertexLights_ = vertexLights;
  630. }
  631. baseBatch.lightQueue_ = &(i->second_);
  632. }
  633. if (pass->GetBlendMode() == BLEND_REPLACE)
  634. {
  635. FinalizeBatch(baseBatch, tech, pass);
  636. baseQueue_.AddBatch(baseBatch);
  637. }
  638. else
  639. {
  640. // Transparent batches can not be instanced
  641. FinalizeBatch(baseBatch, tech, pass, false);
  642. alphaQueue_.AddBatch(baseBatch);
  643. }
  644. continue;
  645. }
  646. // If no base pass, finally check for pre-alpha / post-alpha custom passes
  647. pass = tech->GetPass(PASS_PREALPHA);
  648. if (pass)
  649. {
  650. FinalizeBatch(baseBatch, tech, pass);
  651. preAlphaQueue_.AddBatch(baseBatch);
  652. continue;
  653. }
  654. pass = tech->GetPass(PASS_POSTALPHA);
  655. if (pass)
  656. {
  657. // Post-alpha pass is treated similarly as alpha, and is not instanced
  658. FinalizeBatch(baseBatch, tech, pass, false);
  659. postAlphaQueue_.AddBatch(baseBatch);
  660. continue;
  661. }
  662. }
  663. }
  664. }
  665. }
  666. void View::UpdateGeometries()
  667. {
  668. PROFILE(UpdateGeometries);
  669. WorkQueue* queue = GetSubsystem<WorkQueue>();
  670. // Sort batches
  671. {
  672. WorkItem item;
  673. item.workFunction_ = SortBatchQueueFrontToBackWork;
  674. item.start_ = &baseQueue_;
  675. queue->AddWorkItem(item);
  676. item.start_ = &preAlphaQueue_;
  677. queue->AddWorkItem(item);
  678. if (renderer_->GetLightPrepass())
  679. {
  680. item.start_ = &gbufferQueue_;
  681. queue->AddWorkItem(item);
  682. }
  683. item.workFunction_ = SortBatchQueueBackToFrontWork;
  684. item.start_ = &alphaQueue_;
  685. queue->AddWorkItem(item);
  686. item.start_ = &postAlphaQueue_;
  687. queue->AddWorkItem(item);
  688. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  689. {
  690. item.workFunction_ = SortLightQueueWork;
  691. item.start_ = &(*i);
  692. queue->AddWorkItem(item);
  693. }
  694. }
  695. // Update geometries. Split into threaded and non-threaded updates.
  696. {
  697. nonThreadedGeometries_.Clear();
  698. threadedGeometries_.Clear();
  699. for (PODVector<Drawable*>::Iterator i = allGeometries_.Begin(); i != allGeometries_.End(); ++i)
  700. {
  701. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  702. if (type == UPDATE_MAIN_THREAD)
  703. nonThreadedGeometries_.Push(*i);
  704. else if (type == UPDATE_WORKER_THREAD)
  705. threadedGeometries_.Push(*i);
  706. }
  707. if (threadedGeometries_.Size())
  708. {
  709. WorkItem item;
  710. item.workFunction_ = UpdateDrawableGeometriesWork;
  711. item.aux_ = const_cast<FrameInfo*>(&frame_);
  712. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  713. while (start != threadedGeometries_.End())
  714. {
  715. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  716. if (end - start > DRAWABLES_PER_WORK_ITEM)
  717. end = start + DRAWABLES_PER_WORK_ITEM;
  718. item.start_ = &(*start);
  719. item.end_ = &(*end);
  720. queue->AddWorkItem(item);
  721. start = end;
  722. }
  723. }
  724. // While the work queue is processed, update non-threaded geometries
  725. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  726. (*i)->UpdateGeometry(frame_);
  727. }
  728. // Finally ensure all threaded work has completed
  729. queue->Complete();
  730. }
  731. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  732. {
  733. Light* light = lightQueue.light_;
  734. // Shadows on transparencies can only be rendered if shadow maps are not reused
  735. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  736. bool hasVertexLights = drawable->GetVertexLights().Size() > 0;
  737. bool prepass = renderer_->GetLightPrepass();
  738. unsigned numBatches = drawable->GetNumBatches();
  739. for (unsigned i = 0; i < numBatches; ++i)
  740. {
  741. Batch litBatch;
  742. drawable->GetBatch(litBatch, frame_, i);
  743. Technique* tech = GetTechnique(drawable, litBatch.material_);
  744. if (!litBatch.geometry_ || !tech)
  745. continue;
  746. // Do not create pixel lit forward passes for materials that render into the G-buffer
  747. if (prepass && tech->HasPass(PASS_GBUFFER))
  748. continue;
  749. Pass* pass = tech->GetPass(PASS_LIGHT);
  750. // Skip if material does not receive light at all
  751. if (!pass)
  752. continue;
  753. // Fill the rest of the batch
  754. litBatch.camera_ = camera_;
  755. litBatch.lightQueue_ = &lightQueue;
  756. litBatch.zone_ = GetZone(drawable);
  757. // Check from the ambient pass whether the object is opaque or transparent
  758. Pass* ambientPass = tech->GetPass(PASS_BASE);
  759. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  760. {
  761. FinalizeBatch(litBatch, tech, pass);
  762. lightQueue.litBatches_.AddBatch(litBatch);
  763. }
  764. else
  765. {
  766. // Transparent batches can not be instanced
  767. FinalizeBatch(litBatch, tech, pass, false, allowTransparentShadows);
  768. alphaQueue_.AddBatch(litBatch);
  769. }
  770. }
  771. }
  772. void View::RenderBatchesForward()
  773. {
  774. // Reset the light optimization stencil reference value
  775. lightStencilValue_ = 1;
  776. // If not reusing shadowmaps, render all of them first
  777. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  778. {
  779. PROFILE(RenderShadowMaps);
  780. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  781. {
  782. if (i->shadowMap_)
  783. RenderShadowMap(*i);
  784. }
  785. }
  786. graphics_->SetRenderTarget(0, renderTarget_);
  787. graphics_->SetDepthStencil(depthStencil_);
  788. graphics_->SetViewport(screenRect_);
  789. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, farClipZone_->GetFogColor());
  790. if (!baseQueue_.IsEmpty())
  791. {
  792. // Render opaque object unlit base pass
  793. PROFILE(RenderBase);
  794. RenderBatchQueue(baseQueue_);
  795. }
  796. if (!lightQueues_.Empty())
  797. {
  798. // Render shadow maps + opaque objects' additive lighting
  799. PROFILE(RenderLights);
  800. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  801. {
  802. // If reusing shadowmaps, render each of them before the lit batches
  803. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  804. {
  805. RenderShadowMap(*i);
  806. graphics_->SetRenderTarget(0, renderTarget_);
  807. graphics_->SetDepthStencil(depthStencil_);
  808. graphics_->SetViewport(screenRect_);
  809. }
  810. RenderLightBatchQueue(i->litBatches_, i->light_);
  811. }
  812. }
  813. graphics_->SetScissorTest(false);
  814. graphics_->SetStencilTest(false);
  815. graphics_->SetRenderTarget(0, renderTarget_);
  816. graphics_->SetDepthStencil(depthStencil_);
  817. graphics_->SetViewport(screenRect_);
  818. if (!preAlphaQueue_.IsEmpty())
  819. {
  820. // Render pre-alpha custom pass
  821. PROFILE(RenderPreAlpha);
  822. RenderBatchQueue(preAlphaQueue_);
  823. }
  824. if (!alphaQueue_.IsEmpty())
  825. {
  826. // Render transparent objects (both base passes & additive lighting)
  827. PROFILE(RenderAlpha);
  828. RenderBatchQueue(alphaQueue_, true);
  829. }
  830. if (!postAlphaQueue_.IsEmpty())
  831. {
  832. // Render pre-alpha custom pass
  833. PROFILE(RenderPostAlpha);
  834. RenderBatchQueue(postAlphaQueue_);
  835. }
  836. }
  837. void View::RenderBatchesLightPrepass()
  838. {
  839. // If not reusing shadowmaps, render all of them first
  840. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  841. {
  842. PROFILE(RenderShadowMaps);
  843. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  844. {
  845. if (i->shadowMap_)
  846. RenderShadowMap(*i);
  847. }
  848. }
  849. Texture2D* normalBuffer = renderer_->GetNormalBuffer();
  850. Texture2D* depthBuffer = renderer_->GetDepthBuffer();
  851. RenderSurface* depthStencil = 0;
  852. // Hardware depth support: render to RGBA normal buffer and read hardware depth
  853. if (graphics_->GetHardwareDepthSupport())
  854. {
  855. depthStencil = depthBuffer->GetRenderSurface();
  856. graphics_->SetRenderTarget(0, normalBuffer);
  857. }
  858. // No hardware depth support: render to RGBA normal buffer and R32F depth
  859. else
  860. {
  861. graphics_->SetRenderTarget(0, normalBuffer);
  862. graphics_->SetRenderTarget(1, depthBuffer);
  863. }
  864. graphics_->SetDepthStencil(depthStencil);
  865. graphics_->SetViewport(screenRect_);
  866. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  867. if (!gbufferQueue_.IsEmpty())
  868. {
  869. // Render G-buffer batches
  870. PROFILE(RenderGBuffer);
  871. RenderBatchQueue(gbufferQueue_);
  872. }
  873. // Clear the light accumulation buffer
  874. Texture2D* lightBuffer = renderer_->GetLightBuffer();
  875. graphics_->ResetRenderTarget(1);
  876. graphics_->SetRenderTarget(0, lightBuffer);
  877. graphics_->SetDepthStencil(depthStencil);
  878. graphics_->SetViewport(screenRect_);
  879. graphics_->Clear(CLEAR_COLOR);
  880. if (!lightQueues_.Empty())
  881. {
  882. // Render shadow maps + light volumes
  883. PROFILE(RenderLights);
  884. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  885. {
  886. // If reusing shadowmaps, render each of them before the lit batches
  887. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  888. {
  889. RenderShadowMap(*i);
  890. graphics_->SetRenderTarget(0, lightBuffer);
  891. graphics_->SetDepthStencil(depthStencil);
  892. graphics_->SetViewport(screenRect_);
  893. }
  894. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  895. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  896. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  897. {
  898. SetupLightVolumeBatch(i->volumeBatches_[j]);
  899. i->volumeBatches_[j].Draw(graphics_, renderer_);
  900. }
  901. }
  902. }
  903. // Clear destination render target with fog color
  904. graphics_->SetScissorTest(false);
  905. graphics_->SetStencilTest(false);
  906. #ifndef USE_OPENGL
  907. graphics_->SetRenderTarget(0, renderTarget_);
  908. #else
  909. // On OpenGL render the final image to the normal buffer first, as FBO and backbuffer rendering can not be mixed
  910. graphics_->SetRenderTarget(0, normalBuffer);
  911. #endif
  912. graphics_->SetDepthStencil(depthStencil);
  913. graphics_->SetViewport(screenRect_);
  914. graphics_->Clear(CLEAR_COLOR, farClipZone_->GetFogColor());
  915. if (!baseQueue_.IsEmpty())
  916. {
  917. // Render opaque objects with deferred lighting result
  918. PROFILE(RenderBase);
  919. graphics_->SetTexture(TU_LIGHTBUFFER, lightBuffer);
  920. RenderBatchQueue(baseQueue_);
  921. }
  922. if (!preAlphaQueue_.IsEmpty())
  923. {
  924. // Render pre-alpha custom pass
  925. PROFILE(RenderPreAlpha);
  926. RenderBatchQueue(preAlphaQueue_);
  927. }
  928. if (!alphaQueue_.IsEmpty())
  929. {
  930. // Render transparent objects (both base passes & additive lighting)
  931. PROFILE(RenderAlpha);
  932. RenderBatchQueue(alphaQueue_, true);
  933. }
  934. if (!postAlphaQueue_.IsEmpty())
  935. {
  936. // Render pre-alpha custom pass
  937. PROFILE(RenderPostAlpha);
  938. RenderBatchQueue(postAlphaQueue_);
  939. }
  940. // Blit the final image to destination render target on OpenGL
  941. /// \todo Depth is reset to far plane, so geometry drawn after the view (for example debug geometry) can not be depth tested
  942. #ifdef USE_OPENGL
  943. graphics_->SetAlphaTest(false);
  944. graphics_->SetBlendMode(BLEND_REPLACE);
  945. graphics_->SetColorWrite(true);
  946. graphics_->SetDepthTest(CMP_ALWAYS);
  947. graphics_->SetDepthWrite(true);
  948. graphics_->SetScissorTest(false);
  949. graphics_->SetStencilTest(false);
  950. graphics_->SetRenderTarget(0, renderTarget_);
  951. graphics_->SetDepthStencil(depthStencil_);
  952. graphics_->SetViewport(screenRect_);
  953. graphics_->SetShaders(renderer_->GetVertexShader("CopyFramebuffer"), renderer_->GetPixelShader("CopyFramebuffer"));
  954. float gBufferWidth = (float)graphics_->GetWidth();
  955. float gBufferHeight = (float)graphics_->GetHeight();
  956. float widthRange = 0.5f * (screenRect_.right_ - screenRect_.left_) / gBufferWidth;
  957. float heightRange = 0.5f * (screenRect_.bottom_ - screenRect_.top_) / gBufferHeight;
  958. Vector4 bufferUVOffset(((float)screenRect_.left_) / gBufferWidth + widthRange,
  959. ((float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  960. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  961. graphics_->SetTexture(TU_DIFFUSE, normalBuffer);
  962. DrawFullscreenQuad(camera_, false);
  963. #endif
  964. }
  965. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  966. {
  967. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  968. float halfViewSize = camera->GetHalfViewSize();
  969. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  970. Vector3 cameraPos = camera->GetWorldPosition();
  971. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  972. {
  973. Drawable* occluder = *i;
  974. bool erase = false;
  975. if (!occluder->IsInView(frame_, false))
  976. occluder->UpdateDistance(frame_);
  977. // Check occluder's draw distance (in main camera view)
  978. float maxDistance = occluder->GetDrawDistance();
  979. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  980. erase = true;
  981. else
  982. {
  983. // Check that occluder is big enough on the screen
  984. const BoundingBox& box = occluder->GetWorldBoundingBox();
  985. float diagonal = (box.max_ - box.min_).LengthFast();
  986. float compare;
  987. if (!camera->IsOrthographic())
  988. compare = diagonal * halfViewSize / occluder->GetDistance();
  989. else
  990. compare = diagonal * invOrthoSize;
  991. if (compare < occluderSizeThreshold_)
  992. erase = true;
  993. else
  994. {
  995. // Store amount of triangles divided by screen size as a sorting key
  996. // (best occluders are big and have few triangles)
  997. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  998. }
  999. }
  1000. if (erase)
  1001. i = occluders.Erase(i);
  1002. else
  1003. ++i;
  1004. }
  1005. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1006. if (occluders.Size())
  1007. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1008. }
  1009. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1010. {
  1011. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1012. buffer->Clear();
  1013. for (unsigned i = 0; i < occluders.Size(); ++i)
  1014. {
  1015. Drawable* occluder = occluders[i];
  1016. if (i > 0)
  1017. {
  1018. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1019. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1020. continue;
  1021. }
  1022. // Check for running out of triangles
  1023. if (!occluder->DrawOcclusion(buffer))
  1024. break;
  1025. }
  1026. buffer->BuildDepthHierarchy();
  1027. }
  1028. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1029. {
  1030. Light* light = query.light_;
  1031. LightType type = light->GetLightType();
  1032. // Check if light should be shadowed
  1033. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1034. // If shadow distance non-zero, check it
  1035. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1036. isShadowed = false;
  1037. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1038. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1039. query.litGeometries_.Clear();
  1040. switch (type)
  1041. {
  1042. case LIGHT_DIRECTIONAL:
  1043. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1044. {
  1045. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1046. query.litGeometries_.Push(geometries_[i]);
  1047. }
  1048. break;
  1049. case LIGHT_SPOT:
  1050. {
  1051. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1052. octree_->GetDrawables(octreeQuery);
  1053. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1054. {
  1055. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1056. query.litGeometries_.Push(tempDrawables[i]);
  1057. }
  1058. }
  1059. break;
  1060. case LIGHT_POINT:
  1061. {
  1062. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetWorldPosition(), light->GetRange()),
  1063. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1064. octree_->GetDrawables(octreeQuery);
  1065. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1066. {
  1067. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1068. query.litGeometries_.Push(tempDrawables[i]);
  1069. }
  1070. }
  1071. break;
  1072. }
  1073. // If no lit geometries or not shadowed, no need to process shadow cameras
  1074. if (query.litGeometries_.Empty() || !isShadowed)
  1075. {
  1076. query.numSplits_ = 0;
  1077. return;
  1078. }
  1079. // Determine number of shadow cameras and setup their initial positions
  1080. SetupShadowCameras(query);
  1081. // Process each split for shadow casters
  1082. query.shadowCasters_.Clear();
  1083. for (unsigned i = 0; i < query.numSplits_; ++i)
  1084. {
  1085. Camera* shadowCamera = query.shadowCameras_[i];
  1086. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  1087. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1088. // For point light check that the face is visible: if not, can skip the split
  1089. if (type == LIGHT_POINT)
  1090. {
  1091. BoundingBox shadowCameraBox(shadowCameraFrustum);
  1092. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  1093. continue;
  1094. }
  1095. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1096. if (type == LIGHT_DIRECTIONAL)
  1097. {
  1098. if (sceneViewBox_.min_.z_ > query.shadowFarSplits_[i])
  1099. continue;
  1100. if (sceneViewBox_.max_.z_ < query.shadowNearSplits_[i])
  1101. continue;
  1102. }
  1103. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  1104. // lit geometries, whose result still exists in tempDrawables
  1105. if (type != LIGHT_SPOT)
  1106. {
  1107. FrustumOctreeQuery octreeQuery(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1108. camera_->GetViewMask(), true);
  1109. octree_->GetDrawables(octreeQuery);
  1110. }
  1111. // Check which shadow casters actually contribute to the shadowing
  1112. ProcessShadowCasters(query, tempDrawables, i);
  1113. }
  1114. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1115. // only cost has been the shadow camera setup & queries
  1116. if (query.shadowCasters_.Empty())
  1117. query.numSplits_ = 0;
  1118. }
  1119. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1120. {
  1121. Light* light = query.light_;
  1122. Matrix3x4 lightView;
  1123. Matrix4 lightProj;
  1124. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1125. lightView = shadowCamera->GetInverseWorldTransform();
  1126. lightProj = shadowCamera->GetProjection();
  1127. bool dirLight = shadowCamera->IsOrthographic();
  1128. query.shadowCasterBox_[splitIndex].defined_ = false;
  1129. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1130. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1131. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1132. Frustum lightViewFrustum;
  1133. if (!dirLight)
  1134. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1135. else
  1136. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, query.shadowNearSplits_[splitIndex]),
  1137. Min(sceneViewBox_.max_.z_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1138. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1139. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1140. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1141. return;
  1142. BoundingBox lightViewBox;
  1143. BoundingBox lightProjBox;
  1144. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1145. {
  1146. Drawable* drawable = *i;
  1147. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  1148. // Check for that first
  1149. if (!drawable->GetCastShadows())
  1150. continue;
  1151. // Note: as lights are processed threaded, it is possible a drawable's UpdateDistance() function is called several
  1152. // times. However, this should not cause problems as no scene modification happens at this point.
  1153. if (!drawable->IsInView(frame_, false))
  1154. drawable->UpdateDistance(frame_);
  1155. // Check shadow distance
  1156. float maxShadowDistance = drawable->GetShadowDistance();
  1157. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1158. continue;
  1159. // Check shadow mask
  1160. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1161. continue;
  1162. // Project shadow caster bounding box to light view space for visibility check
  1163. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1164. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1165. {
  1166. // Merge to shadow caster bounding box and add to the list
  1167. if (dirLight)
  1168. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1169. else
  1170. {
  1171. lightProjBox = lightViewBox.Projected(lightProj);
  1172. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1173. }
  1174. query.shadowCasters_.Push(drawable);
  1175. }
  1176. }
  1177. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1178. }
  1179. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1180. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1181. {
  1182. if (shadowCamera->IsOrthographic())
  1183. {
  1184. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1185. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1186. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1187. }
  1188. else
  1189. {
  1190. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1191. if (drawable->IsInView(frame_))
  1192. return true;
  1193. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1194. Vector3 center = lightViewBox.Center();
  1195. Ray extrusionRay(center, center.Normalized());
  1196. float extrusionDistance = shadowCamera->GetFarClip();
  1197. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1198. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1199. float sizeFactor = extrusionDistance / originalDistance;
  1200. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1201. // than necessary, so the test will be conservative
  1202. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1203. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1204. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1205. lightViewBox.Merge(extrudedBox);
  1206. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1207. }
  1208. }
  1209. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1210. {
  1211. unsigned width = shadowMap->GetWidth();
  1212. unsigned height = shadowMap->GetHeight();
  1213. int maxCascades = renderer_->GetMaxShadowCascades();
  1214. // Due to instruction count limits, light prepass in SM2.0 can only support up to 3 cascades
  1215. #ifndef USE_OPENGL
  1216. if (renderer_->GetLightPrepass() && !graphics_->GetSM3Support())
  1217. maxCascades = Max(maxCascades, 3);
  1218. #endif
  1219. switch (light->GetLightType())
  1220. {
  1221. case LIGHT_DIRECTIONAL:
  1222. if (maxCascades == 1)
  1223. return IntRect(0, 0, width, height);
  1224. else if (maxCascades == 2)
  1225. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1226. else
  1227. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1228. (splitIndex / 2 + 1) * height / 2);
  1229. case LIGHT_SPOT:
  1230. return IntRect(0, 0, width, height);
  1231. case LIGHT_POINT:
  1232. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1233. (splitIndex / 2 + 1) * height / 3);
  1234. }
  1235. return IntRect();
  1236. }
  1237. void View::OptimizeLightByScissor(Light* light)
  1238. {
  1239. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1240. graphics_->SetScissorTest(true, GetLightScissor(light));
  1241. else
  1242. graphics_->SetScissorTest(false);
  1243. }
  1244. void View::OptimizeLightByStencil(Light* light)
  1245. {
  1246. if (light)
  1247. {
  1248. LightType type = light->GetLightType();
  1249. if (type == LIGHT_DIRECTIONAL)
  1250. {
  1251. graphics_->SetStencilTest(false);
  1252. return;
  1253. }
  1254. Geometry* geometry = renderer_->GetLightGeometry(light);
  1255. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1256. Matrix4 projection(camera_->GetProjection());
  1257. float lightDist;
  1258. if (type == LIGHT_POINT)
  1259. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  1260. else
  1261. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  1262. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1263. if (lightDist < M_EPSILON)
  1264. {
  1265. graphics_->SetStencilTest(false);
  1266. return;
  1267. }
  1268. // If the stencil value has wrapped, clear the whole stencil first
  1269. if (!lightStencilValue_)
  1270. {
  1271. graphics_->Clear(CLEAR_STENCIL);
  1272. lightStencilValue_ = 1;
  1273. }
  1274. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1275. // to avoid clipping the front faces.
  1276. if (lightDist < camera_->GetNearClip() * 2.0f)
  1277. {
  1278. graphics_->SetCullMode(CULL_CW);
  1279. graphics_->SetDepthTest(CMP_GREATER);
  1280. }
  1281. else
  1282. {
  1283. graphics_->SetCullMode(CULL_CCW);
  1284. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1285. }
  1286. graphics_->SetColorWrite(false);
  1287. graphics_->SetDepthWrite(false);
  1288. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1289. graphics_->SetShaders(renderer_->GetStencilVS(), renderer_->GetStencilPS());
  1290. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1291. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera_));
  1292. geometry->Draw(graphics_);
  1293. graphics_->ClearTransformSources();
  1294. graphics_->SetColorWrite(true);
  1295. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1296. // Increase stencil value for next light
  1297. ++lightStencilValue_;
  1298. }
  1299. else
  1300. graphics_->SetStencilTest(false);
  1301. }
  1302. const Rect& View::GetLightScissor(Light* light)
  1303. {
  1304. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1305. if (i != lightScissorCache_.End())
  1306. return i->second_;
  1307. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1308. Matrix4 projection(camera_->GetProjection());
  1309. switch (light->GetLightType())
  1310. {
  1311. case LIGHT_POINT:
  1312. {
  1313. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1314. return lightScissorCache_[light] = viewBox.Projected(projection);
  1315. }
  1316. case LIGHT_SPOT:
  1317. {
  1318. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1319. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1320. }
  1321. default:
  1322. return lightScissorCache_[light] = Rect::FULL;
  1323. }
  1324. }
  1325. void View::SetupShadowCameras(LightQueryResult& query)
  1326. {
  1327. Light* light = query.light_;
  1328. LightType type = light->GetLightType();
  1329. int splits = 0;
  1330. if (type == LIGHT_DIRECTIONAL)
  1331. {
  1332. const CascadeParameters& cascade = light->GetShadowCascade();
  1333. float nearSplit = camera_->GetNearClip();
  1334. float farSplit;
  1335. while (splits < renderer_->GetMaxShadowCascades())
  1336. {
  1337. // If split is completely beyond camera far clip, we are done
  1338. if (nearSplit > camera_->GetFarClip())
  1339. break;
  1340. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1341. if (farSplit <= nearSplit)
  1342. break;
  1343. // Setup the shadow camera for the split
  1344. Camera* shadowCamera = renderer_->GetShadowCamera();
  1345. query.shadowCameras_[splits] = shadowCamera;
  1346. query.shadowNearSplits_[splits] = nearSplit;
  1347. query.shadowFarSplits_[splits] = farSplit;
  1348. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1349. nearSplit = farSplit;
  1350. ++splits;
  1351. }
  1352. }
  1353. if (type == LIGHT_SPOT)
  1354. {
  1355. Camera* shadowCamera = renderer_->GetShadowCamera();
  1356. query.shadowCameras_[0] = shadowCamera;
  1357. Node* cameraNode = shadowCamera->GetNode();
  1358. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1359. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1360. shadowCamera->SetFarClip(light->GetRange());
  1361. shadowCamera->SetFov(light->GetFov());
  1362. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1363. splits = 1;
  1364. }
  1365. if (type == LIGHT_POINT)
  1366. {
  1367. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1368. {
  1369. Camera* shadowCamera = renderer_->GetShadowCamera();
  1370. query.shadowCameras_[i] = shadowCamera;
  1371. Node* cameraNode = shadowCamera->GetNode();
  1372. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1373. cameraNode->SetPosition(light->GetWorldPosition());
  1374. cameraNode->SetDirection(directions[i]);
  1375. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1376. shadowCamera->SetFarClip(light->GetRange());
  1377. shadowCamera->SetFov(90.0f);
  1378. shadowCamera->SetAspectRatio(1.0f);
  1379. }
  1380. splits = MAX_CUBEMAP_FACES;
  1381. }
  1382. query.numSplits_ = splits;
  1383. }
  1384. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1385. {
  1386. Node* cameraNode = shadowCamera->GetNode();
  1387. float extrusionDistance = camera_->GetFarClip();
  1388. const FocusParameters& parameters = light->GetShadowFocus();
  1389. // Calculate initial position & rotation
  1390. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1391. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1392. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1393. // Calculate main camera shadowed frustum in light's view space
  1394. farSplit = Min(farSplit, camera_->GetFarClip());
  1395. // Use the scene Z bounds to limit frustum size if applicable
  1396. if (parameters.focus_)
  1397. {
  1398. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1399. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1400. }
  1401. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1402. frustumVolume_.Define(splitFrustum);
  1403. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1404. if (parameters.focus_)
  1405. {
  1406. BoundingBox litGeometriesBox;
  1407. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1408. {
  1409. // Skip "infinite" objects like the skybox
  1410. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1411. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1412. {
  1413. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1414. (GetLightMask(geometries_[i]) & light->GetLightMask()))
  1415. litGeometriesBox.Merge(geomBox);
  1416. }
  1417. }
  1418. if (litGeometriesBox.defined_)
  1419. {
  1420. frustumVolume_.Clip(litGeometriesBox);
  1421. // If volume became empty, restore it to avoid zero size
  1422. if (frustumVolume_.Empty())
  1423. frustumVolume_.Define(splitFrustum);
  1424. }
  1425. }
  1426. // Transform frustum volume to light space
  1427. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1428. frustumVolume_.Transform(lightView);
  1429. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1430. BoundingBox shadowBox;
  1431. if (!parameters.nonUniform_)
  1432. shadowBox.Define(Sphere(frustumVolume_));
  1433. else
  1434. shadowBox.Define(frustumVolume_);
  1435. shadowCamera->SetOrthographic(true);
  1436. shadowCamera->SetAspectRatio(1.0f);
  1437. shadowCamera->SetNearClip(0.0f);
  1438. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1439. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1440. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1441. }
  1442. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1443. const BoundingBox& shadowCasterBox)
  1444. {
  1445. const FocusParameters& parameters = light->GetShadowFocus();
  1446. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1447. LightType type = light->GetLightType();
  1448. if (type == LIGHT_DIRECTIONAL)
  1449. {
  1450. BoundingBox shadowBox;
  1451. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1452. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1453. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1454. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1455. // Requantize and snap to shadow map texels
  1456. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1457. }
  1458. if (type == LIGHT_SPOT)
  1459. {
  1460. if (parameters.focus_)
  1461. {
  1462. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1463. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1464. float viewSize = Max(viewSizeX, viewSizeY);
  1465. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1466. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1467. float quantize = parameters.quantize_ * invOrthoSize;
  1468. float minView = parameters.minView_ * invOrthoSize;
  1469. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1470. if (viewSize < 1.0f)
  1471. shadowCamera->SetZoom(1.0f / viewSize);
  1472. }
  1473. }
  1474. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1475. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1476. if (shadowCamera->GetZoom() >= 1.0f)
  1477. {
  1478. if (light->GetLightType() != LIGHT_POINT)
  1479. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1480. else
  1481. {
  1482. #ifdef USE_OPENGL
  1483. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1484. #else
  1485. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1486. #endif
  1487. }
  1488. }
  1489. }
  1490. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1491. const BoundingBox& viewBox)
  1492. {
  1493. Node* cameraNode = shadowCamera->GetNode();
  1494. const FocusParameters& parameters = light->GetShadowFocus();
  1495. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1496. float minX = viewBox.min_.x_;
  1497. float minY = viewBox.min_.y_;
  1498. float maxX = viewBox.max_.x_;
  1499. float maxY = viewBox.max_.y_;
  1500. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1501. Vector2 viewSize(maxX - minX, maxY - minY);
  1502. // Quantize size to reduce swimming
  1503. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1504. if (parameters.nonUniform_)
  1505. {
  1506. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1507. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1508. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1509. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1510. }
  1511. else if (parameters.focus_)
  1512. {
  1513. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1514. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1515. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1516. viewSize.y_ = viewSize.x_;
  1517. }
  1518. shadowCamera->SetOrthoSize(viewSize);
  1519. // Center shadow camera to the view space bounding box
  1520. Vector3 pos(shadowCamera->GetWorldPosition());
  1521. Quaternion rot(shadowCamera->GetWorldRotation());
  1522. Vector3 adjust(center.x_, center.y_, 0.0f);
  1523. cameraNode->Translate(rot * adjust);
  1524. // If the shadow map viewport is known, snap to whole texels
  1525. if (shadowMapWidth > 0.0f)
  1526. {
  1527. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1528. // Take into account that shadow map border will not be used
  1529. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1530. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1531. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1532. cameraNode->Translate(rot * snap);
  1533. }
  1534. }
  1535. void View::FindZone(Drawable* drawable, unsigned threadIndex)
  1536. {
  1537. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1538. int bestPriority = M_MIN_INT;
  1539. Zone* newZone = 0;
  1540. // If bounding box center is in view, can use the visible zones. Else must query via the octree
  1541. if (frustum_.IsInside(center))
  1542. {
  1543. // First check if the last zone remains a conclusive result
  1544. Zone* lastZone = drawable->GetLastZone();
  1545. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) &&
  1546. lastZone->GetPriority() >= highestZonePriority_)
  1547. newZone = lastZone;
  1548. else
  1549. {
  1550. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1551. {
  1552. int priority = (*i)->GetPriority();
  1553. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1554. {
  1555. newZone = *i;
  1556. bestPriority = priority;
  1557. }
  1558. }
  1559. }
  1560. }
  1561. else
  1562. {
  1563. PODVector<Zone*>& tempZones = tempZones_[threadIndex];
  1564. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(tempZones), center, DRAWABLE_ZONE);
  1565. octree_->GetDrawables(query);
  1566. bestPriority = M_MIN_INT;
  1567. for (PODVector<Zone*>::Iterator i = tempZones.Begin(); i != tempZones.End(); ++i)
  1568. {
  1569. int priority = (*i)->GetPriority();
  1570. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1571. {
  1572. newZone = *i;
  1573. bestPriority = priority;
  1574. }
  1575. }
  1576. }
  1577. drawable->SetZone(newZone);
  1578. }
  1579. Zone* View::GetZone(Drawable* drawable)
  1580. {
  1581. if (cameraZoneOverride_)
  1582. return cameraZone_;
  1583. Zone* drawableZone = drawable->GetZone();
  1584. return drawableZone ? drawableZone : cameraZone_;
  1585. }
  1586. unsigned View::GetLightMask(Drawable* drawable)
  1587. {
  1588. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1589. }
  1590. unsigned View::GetShadowMask(Drawable* drawable)
  1591. {
  1592. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  1593. }
  1594. unsigned long long View::GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  1595. {
  1596. unsigned long long hash = 0;
  1597. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  1598. hash += (unsigned long long)(*i);
  1599. return hash;
  1600. }
  1601. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1602. {
  1603. if (!material)
  1604. material = renderer_->GetDefaultMaterial();
  1605. if (!material)
  1606. return 0;
  1607. float lodDistance = drawable->GetLodDistance();
  1608. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1609. if (techniques.Empty())
  1610. return 0;
  1611. // Check for suitable technique. Techniques should be ordered like this:
  1612. // Most distant & highest quality
  1613. // Most distant & lowest quality
  1614. // Second most distant & highest quality
  1615. // ...
  1616. for (unsigned i = 0; i < techniques.Size(); ++i)
  1617. {
  1618. const TechniqueEntry& entry = techniques[i];
  1619. Technique* technique = entry.technique_;
  1620. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1621. continue;
  1622. if (lodDistance >= entry.lodDistance_)
  1623. return technique;
  1624. }
  1625. // If no suitable technique found, fallback to the last
  1626. return techniques.Back().technique_;
  1627. }
  1628. void View::CheckMaterialForAuxView(Material* material)
  1629. {
  1630. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1631. for (unsigned i = 0; i < textures.Size(); ++i)
  1632. {
  1633. // Have to check cube & 2D textures separately
  1634. Texture* texture = textures[i];
  1635. if (texture)
  1636. {
  1637. if (texture->GetType() == Texture2D::GetTypeStatic())
  1638. {
  1639. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1640. RenderSurface* target = tex2D->GetRenderSurface();
  1641. if (target)
  1642. {
  1643. const Viewport& viewport = target->GetViewport();
  1644. if (viewport.scene_ && viewport.camera_)
  1645. renderer_->AddView(target, viewport);
  1646. }
  1647. }
  1648. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1649. {
  1650. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1651. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1652. {
  1653. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1654. if (target)
  1655. {
  1656. const Viewport& viewport = target->GetViewport();
  1657. if (viewport.scene_ && viewport.camera_)
  1658. renderer_->AddView(target, viewport);
  1659. }
  1660. }
  1661. }
  1662. }
  1663. }
  1664. // Set frame number so that we can early-out next time we come across this material on the same frame
  1665. material->MarkForAuxView(frame_.frameNumber_);
  1666. }
  1667. void View::FinalizeBatch(Batch& batch, Technique* tech, Pass* pass, bool allowInstancing, bool allowShadows)
  1668. {
  1669. // Convert to instanced if possible
  1670. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && !batch.shaderData_ && !batch.overrideView_)
  1671. batch.geometryType_ = GEOM_INSTANCED;
  1672. batch.pass_ = pass;
  1673. renderer_->SetBatchShaders(batch, tech, pass, allowShadows);
  1674. batch.CalculateSortKey();
  1675. }
  1676. void View::PrepareInstancingBuffer()
  1677. {
  1678. PROFILE(PrepareInstancingBuffer);
  1679. unsigned totalInstances = 0;
  1680. bool prepass = renderer_->GetLightPrepass();
  1681. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1682. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  1683. if (prepass)
  1684. totalInstances += gbufferQueue_.GetNumInstances(renderer_);
  1685. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1686. {
  1687. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  1688. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1689. totalInstances += i->litBatches_.GetNumInstances(renderer_);
  1690. }
  1691. // If fail to set buffer size, fall back to per-group locking
  1692. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1693. {
  1694. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1695. unsigned freeIndex = 0;
  1696. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1697. if (lockedData)
  1698. {
  1699. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1700. preAlphaQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1701. if (prepass)
  1702. gbufferQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1703. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1704. {
  1705. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  1706. i->shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1707. i->litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1708. }
  1709. instancingBuffer->Unlock();
  1710. }
  1711. }
  1712. }
  1713. void View::SetupLightVolumeBatch(Batch& batch)
  1714. {
  1715. Light* light = batch.lightQueue_->light_;
  1716. LightType type = light->GetLightType();
  1717. float lightDist;
  1718. graphics_->SetAlphaTest(false);
  1719. graphics_->SetBlendMode(BLEND_ADD);
  1720. graphics_->SetDepthWrite(false);
  1721. if (type != LIGHT_DIRECTIONAL)
  1722. {
  1723. if (type == LIGHT_POINT)
  1724. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  1725. else
  1726. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  1727. // Draw front faces if not inside light volume
  1728. if (lightDist < camera_->GetNearClip() * 2.0f)
  1729. {
  1730. graphics_->SetCullMode(CULL_CW);
  1731. graphics_->SetDepthTest(CMP_GREATER);
  1732. }
  1733. else
  1734. {
  1735. graphics_->SetCullMode(CULL_CCW);
  1736. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1737. }
  1738. }
  1739. else
  1740. {
  1741. graphics_->SetCullMode(CULL_NONE);
  1742. graphics_->SetDepthTest(CMP_ALWAYS);
  1743. }
  1744. graphics_->SetScissorTest(false);
  1745. graphics_->SetStencilTest(true, CMP_LESS, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  1746. }
  1747. void View::DrawFullscreenQuad(Camera* camera, bool nearQuad)
  1748. {
  1749. Light quadDirLight(context_);
  1750. quadDirLight.SetLightType(LIGHT_DIRECTIONAL);
  1751. Matrix3x4 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  1752. graphics_->SetCullMode(CULL_NONE);
  1753. graphics_->SetShaderParameter(VSP_MODEL, model);
  1754. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera->GetProjection());
  1755. graphics_->ClearTransformSources();
  1756. renderer_->GetLightGeometry(&quadDirLight)->Draw(graphics_);
  1757. }
  1758. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1759. {
  1760. graphics_->SetScissorTest(false);
  1761. // During G-buffer rendering, mark opaque pixels to stencil buffer
  1762. bool isGBuffer = &queue == &gbufferQueue_;
  1763. if (!isGBuffer)
  1764. graphics_->SetStencilTest(false);
  1765. // Base instanced
  1766. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBaseBatchGroups_.Begin(); i !=
  1767. queue.sortedBaseBatchGroups_.End(); ++i)
  1768. {
  1769. BatchGroup* group = *i;
  1770. if (isGBuffer)
  1771. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  1772. group->Draw(graphics_, renderer_);
  1773. }
  1774. // Base non-instanced
  1775. for (PODVector<Batch*>::ConstIterator i = queue.sortedBaseBatches_.Begin(); i != queue.sortedBaseBatches_.End(); ++i)
  1776. {
  1777. Batch* batch = *i;
  1778. if (isGBuffer)
  1779. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  1780. batch->Draw(graphics_, renderer_);
  1781. }
  1782. // Non-base instanced
  1783. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1784. {
  1785. BatchGroup* group = *i;
  1786. if (useScissor && group->lightQueue_)
  1787. OptimizeLightByScissor(group->lightQueue_->light_);
  1788. if (isGBuffer)
  1789. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  1790. group->Draw(graphics_, renderer_);
  1791. }
  1792. // Non-base non-instanced
  1793. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1794. {
  1795. Batch* batch = *i;
  1796. if (useScissor)
  1797. {
  1798. if (!batch->isBase_ && batch->lightQueue_)
  1799. OptimizeLightByScissor(batch->lightQueue_->light_);
  1800. else
  1801. graphics_->SetScissorTest(false);
  1802. }
  1803. if (isGBuffer)
  1804. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  1805. batch->Draw(graphics_, renderer_);
  1806. }
  1807. }
  1808. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1809. {
  1810. graphics_->SetScissorTest(false);
  1811. graphics_->SetStencilTest(false);
  1812. // Base instanced
  1813. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBaseBatchGroups_.Begin(); i !=
  1814. queue.sortedBaseBatchGroups_.End(); ++i)
  1815. {
  1816. BatchGroup* group = *i;
  1817. group->Draw(graphics_, renderer_);
  1818. }
  1819. // Base non-instanced
  1820. for (PODVector<Batch*>::ConstIterator i = queue.sortedBaseBatches_.Begin(); i != queue.sortedBaseBatches_.End(); ++i)
  1821. {
  1822. Batch* batch = *i;
  1823. batch->Draw(graphics_, renderer_);
  1824. }
  1825. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1826. OptimizeLightByStencil(light);
  1827. OptimizeLightByScissor(light);
  1828. // Non-base instanced
  1829. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1830. {
  1831. BatchGroup* group = *i;
  1832. group->Draw(graphics_, renderer_);
  1833. }
  1834. // Non-base non-instanced
  1835. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1836. {
  1837. Batch* batch = *i;
  1838. batch->Draw(graphics_, renderer_);
  1839. }
  1840. }
  1841. void View::RenderShadowMap(const LightBatchQueue& queue)
  1842. {
  1843. PROFILE(RenderShadowMap);
  1844. Texture2D* shadowMap = queue.shadowMap_;
  1845. graphics_->SetStencilTest(false);
  1846. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1847. if (!graphics_->GetFallback())
  1848. {
  1849. graphics_->SetColorWrite(false);
  1850. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1851. graphics_->SetDepthStencil(shadowMap);
  1852. graphics_->Clear(CLEAR_DEPTH);
  1853. }
  1854. else
  1855. {
  1856. graphics_->SetColorWrite(true);
  1857. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1858. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1859. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1860. }
  1861. // Set shadow depth bias
  1862. BiasParameters parameters = queue.light_->GetShadowBias();
  1863. // Adjust the light's constant depth bias according to global shadow map resolution
  1864. /// \todo Should remove this adjustment and find a more flexible solution
  1865. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1866. if (shadowMapSize <= 512)
  1867. parameters.constantBias_ *= 2.0f;
  1868. else if (shadowMapSize >= 2048)
  1869. parameters.constantBias_ *= 0.5f;
  1870. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1871. // Render each of the splits
  1872. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1873. {
  1874. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1875. if (!shadowQueue.shadowBatches_.IsEmpty())
  1876. {
  1877. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1878. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1879. // However, do not do this for point lights, which need to render continuously across cube faces
  1880. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1881. if (queue.light_->GetLightType() != LIGHT_POINT)
  1882. {
  1883. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1884. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1885. graphics_->SetScissorTest(true, zoomRect, false);
  1886. }
  1887. else
  1888. graphics_->SetScissorTest(false);
  1889. // Draw instanced and non-instanced shadow casters
  1890. RenderBatchQueue(shadowQueue.shadowBatches_);
  1891. }
  1892. }
  1893. graphics_->SetColorWrite(true);
  1894. graphics_->SetDepthBias(0.0f, 0.0f);
  1895. }