2
0

View.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  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 "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Sort.h"
  39. #include "Technique.h"
  40. #include "Texture2D.h"
  41. #include "TextureCube.h"
  42. #include "VertexBuffer.h"
  43. #include "View.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. OBJECTTYPESTATIC(View);
  56. View::View(Context* context) :
  57. Object(context),
  58. graphics_(GetSubsystem<Graphics>()),
  59. renderer_(GetSubsystem<Renderer>()),
  60. octree_(0),
  61. camera_(0),
  62. zone_(0),
  63. renderTarget_(0),
  64. depthStencil_(0)
  65. {
  66. frame_.camera_ = 0;
  67. }
  68. View::~View()
  69. {
  70. }
  71. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  72. {
  73. if (!viewport.scene_ || !viewport.camera_)
  74. return false;
  75. // If scene is loading asynchronously, it is incomplete and should not be rendered
  76. if (viewport.scene_->IsAsyncLoading())
  77. return false;
  78. Octree* octree = viewport.scene_->GetComponent<Octree>();
  79. if (!octree)
  80. return false;
  81. octree_ = octree;
  82. camera_ = viewport.camera_;
  83. renderTarget_ = renderTarget;
  84. if (!renderTarget)
  85. depthStencil_ = 0;
  86. else
  87. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  88. zone_ = renderer_->GetDefaultZone();
  89. // Validate the rect and calculate size. If zero rect, use whole render target size
  90. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  91. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  92. if (viewport.rect_ != IntRect::ZERO)
  93. {
  94. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  95. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  96. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  97. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  98. }
  99. else
  100. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  101. width_ = screenRect_.right_ - screenRect_.left_;
  102. height_ = screenRect_.bottom_ - screenRect_.top_;
  103. // Set possible quality overrides from the camera
  104. drawShadows_ = renderer_->GetDrawShadows();
  105. materialQuality_ = renderer_->GetMaterialQuality();
  106. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  107. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  108. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  109. materialQuality_ = QUALITY_LOW;
  110. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  111. drawShadows_ = false;
  112. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  113. maxOccluderTriangles_ = 0;
  114. return true;
  115. }
  116. void View::Update(const FrameInfo& frame)
  117. {
  118. if (!camera_ || !octree_)
  119. return;
  120. frame_.camera_ = camera_;
  121. frame_.timeStep_ = frame.timeStep_;
  122. frame_.frameNumber_ = frame.frameNumber_;
  123. frame_.viewSize_ = IntVector2(width_, height_);
  124. // Clear old light scissor cache, geometry, light, occluder & batch lists
  125. lightScissorCache_.Clear();
  126. geometries_.Clear();
  127. geometryDepthBounds_.Clear();
  128. lights_.Clear();
  129. occluders_.Clear();
  130. shadowOccluders_.Clear();
  131. baseQueue_.Clear();
  132. extraQueue_.Clear();
  133. transparentQueue_.Clear();
  134. lightQueues_.Clear();
  135. // Do not update if camera projection is illegal
  136. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  137. if (!camera_->IsProjectionValid())
  138. return;
  139. // Set automatic aspect ratio if required
  140. if (camera_->GetAutoAspectRatio())
  141. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  142. // Cache the camera frustum to avoid recalculating it constantly
  143. frustum_ = camera_->GetFrustum();
  144. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  145. renderer_->ResetShadowMapAllocations();
  146. GetDrawables();
  147. GetBatches();
  148. }
  149. void View::Render()
  150. {
  151. if (!octree_ || !camera_)
  152. return;
  153. // Forget parameter sources from the previous view
  154. graphics_->ClearParameterSources();
  155. // If stream offset is supported, write all instance transforms to a single large buffer
  156. // Else we must lock the instance buffer for each batch group
  157. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  158. PrepareInstancingBuffer();
  159. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  160. // again to ensure correct projection will be used
  161. if (camera_->GetAutoAspectRatio())
  162. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  163. graphics_->SetColorWrite(true);
  164. graphics_->SetFillMode(FILL_SOLID);
  165. graphics_->SetScissorTest(false);
  166. graphics_->SetStencilTest(false);
  167. // Bind the face selection and indirection cube maps for point light shadows
  168. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  169. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  170. // Calculate view-global shader parameters
  171. CalculateShaderParameters();
  172. // Reset the light optimization stencil reference value
  173. lightStencilValue_ = 1;
  174. // Render
  175. RenderBatches();
  176. graphics_->SetScissorTest(false);
  177. graphics_->SetStencilTest(false);
  178. graphics_->ResetStreamFrequencies();
  179. // If this is a main view, draw the associated debug geometry now
  180. if (!renderTarget_)
  181. {
  182. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  183. if (scene)
  184. {
  185. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  186. if (debug)
  187. {
  188. debug->SetView(camera_);
  189. debug->Render();
  190. }
  191. }
  192. }
  193. // "Forget" the camera, octree and zone after rendering
  194. camera_ = 0;
  195. octree_ = 0;
  196. zone_ = 0;
  197. frame_.camera_ = 0;
  198. }
  199. void View::GetDrawables()
  200. {
  201. PROFILE(GetDrawables);
  202. Vector3 cameraPos = camera_->GetWorldPosition();
  203. // Get zones & find the zone camera is in
  204. PointOctreeQuery query(tempDrawables_, cameraPos, DRAWABLE_ZONE, camera_->GetViewMask());
  205. octree_->GetDrawables(query);
  206. int highestZonePriority = M_MIN_INT;
  207. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  208. {
  209. Zone* zone = static_cast<Zone*>(tempDrawables_[i]);
  210. if (zone->IsInside(cameraPos) && zone->GetPriority() > highestZonePriority)
  211. {
  212. zone_ = zone;
  213. highestZonePriority = zone->GetPriority();
  214. }
  215. }
  216. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  217. OcclusionBuffer* buffer = 0;
  218. if (maxOccluderTriangles_ > 0)
  219. {
  220. FrustumOctreeQuery query(occluders_, frustum_, DRAWABLE_GEOMETRY, camera_->GetViewMask(), true, false);
  221. octree_->GetDrawables(query);
  222. UpdateOccluders(occluders_, camera_);
  223. if (occluders_.Size())
  224. {
  225. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  226. DrawOccluders(buffer, occluders_);
  227. buffer->BuildDepthHierarchy();
  228. }
  229. }
  230. if (!buffer)
  231. {
  232. // Get geometries & lights without occlusion
  233. FrustumOctreeQuery query(tempDrawables_, frustum_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  234. octree_->GetDrawables(query);
  235. }
  236. else
  237. {
  238. // Get geometries & lights using occlusion
  239. OccludedFrustumOctreeQuery query(tempDrawables_, frustum_, buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  240. camera_->GetViewMask());
  241. octree_->GetDrawables(query);
  242. }
  243. // Add unculled geometries & lights
  244. octree_->GetUnculledDrawables(tempDrawables_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  245. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  246. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  247. sceneBox_.defined_ = false;
  248. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  249. sceneViewBox_.defined_ = false;
  250. Matrix3x4 view(camera_->GetInverseWorldTransform());
  251. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  252. {
  253. Drawable* drawable = tempDrawables_[i];
  254. drawable->UpdateDistance(frame_);
  255. // If draw distance non-zero, check it
  256. float maxDistance = drawable->GetDrawDistance();
  257. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  258. continue;
  259. unsigned flags = drawable->GetDrawableFlags();
  260. if (flags & DRAWABLE_GEOMETRY)
  261. {
  262. drawable->ClearLights();
  263. drawable->MarkInView(frame_);
  264. drawable->UpdateGeometry(frame_);
  265. // Expand the scene bounding boxes. However, do not take "infinite" objects such as the skybox into account,
  266. // as the bounding boxes are also used for shadow focusing
  267. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  268. BoundingBox geomViewBox = geomBox.Transformed(view);
  269. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  270. {
  271. sceneBox_.Merge(geomBox);
  272. sceneViewBox_.Merge(geomViewBox);
  273. }
  274. // Store depth info for split directional light queries
  275. GeometryDepthBounds bounds;
  276. bounds.min_ = geomViewBox.min_.z_;
  277. bounds.max_ = geomViewBox.max_.z_;
  278. geometryDepthBounds_.Push(bounds);
  279. geometries_.Push(drawable);
  280. }
  281. else if (flags & DRAWABLE_LIGHT)
  282. {
  283. Light* light = static_cast<Light*>(drawable);
  284. // Skip if light is culled by the zone
  285. if (!(light->GetViewMask() & zone_->GetViewMask()))
  286. continue;
  287. light->MarkInView(frame_);
  288. lights_.Push(light);
  289. }
  290. }
  291. // Sort the lights to brightest/closest first
  292. for (unsigned i = 0; i < lights_.Size(); ++i)
  293. lights_[i]->SetIntensitySortValue(cameraPos);
  294. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  295. }
  296. void View::GetBatches()
  297. {
  298. maxLightsDrawables_.Clear();
  299. lightQueueIndex_.Clear();
  300. bool fallback = graphics_->GetFallback();
  301. // Go through lights
  302. {
  303. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  304. // Preallocate enough light queues so that we can store pointers to them without having to worry about the
  305. // vector reallocating itself
  306. lightQueues_.Resize(lights_.Size());
  307. unsigned lightQueueCount = 0;
  308. for (unsigned i = 0; i < lights_.Size(); ++i)
  309. {
  310. Light* light = lights_[i];
  311. unsigned shadowSplits = ProcessLight(light);
  312. if (litGeometries_.Empty())
  313. continue;
  314. // Initialize light queue. Store pointer-to-index mapping so that the queue can be found later
  315. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  316. lightQueueIndex_[light] = lightQueueCount;
  317. lightQueue.light_ = light;
  318. lightQueue.litBatches_.Clear();
  319. // Allocate shadow map now
  320. lightQueue.shadowMap_ = 0;
  321. if (shadowSplits > 0)
  322. {
  323. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, width_, height_);
  324. // If did not manage to get a shadow map, convert the light to unshadowed
  325. if (!lightQueue.shadowMap_)
  326. shadowSplits = 0;
  327. }
  328. // Setup shadow batch queues
  329. lightQueue.shadowSplits_.Resize(shadowSplits);
  330. for (unsigned j = 0; j < shadowSplits; ++j)
  331. {
  332. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  333. Camera* shadowCamera = shadowCameras_[j];
  334. shadowQueue.shadowCamera_ = shadowCameras_[j];
  335. shadowQueue.nearSplit_ = shadowNearSplits_[j];
  336. shadowQueue.farSplit_ = shadowFarSplits_[j];
  337. // Setup the shadow split viewport and finalize shadow camera parameters
  338. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  339. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, shadowCasterBox_[j]);
  340. // Loop through shadow casters
  341. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  342. {
  343. Drawable* drawable = shadowCasters_[j][k];
  344. unsigned numBatches = drawable->GetNumBatches();
  345. for (unsigned l = 0; l < numBatches; ++l)
  346. {
  347. Batch shadowBatch;
  348. drawable->GetBatch(frame_, l, shadowBatch);
  349. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  350. if (!shadowBatch.geometry_ || !tech)
  351. continue;
  352. Pass* pass = tech->GetPass(PASS_SHADOW);
  353. // Skip if material has no shadow pass
  354. if (!pass)
  355. continue;
  356. // Fill the rest of the batch
  357. shadowBatch.camera_ = shadowCamera;
  358. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  359. shadowBatch.lightQueue_ = &lightQueue;
  360. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  361. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  362. }
  363. }
  364. }
  365. // Loop through lit geometries
  366. for (unsigned j = 0; j < litGeometries_.Size(); ++j)
  367. {
  368. Drawable* drawable = litGeometries_[j];
  369. drawable->AddLight(light);
  370. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  371. if (!drawable->GetMaxLights())
  372. GetLitBatches(drawable, lightQueue);
  373. else
  374. maxLightsDrawables_.Insert(drawable);
  375. }
  376. ++lightQueueCount;
  377. }
  378. // Resize the light queue vector now that final size is known
  379. lightQueues_.Resize(lightQueueCount);
  380. }
  381. // Process drawables with limited light count
  382. if (maxLightsDrawables_.Size())
  383. {
  384. PROFILE(GetMaxLightsBatches);
  385. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  386. {
  387. Drawable* drawable = *i;
  388. drawable->LimitLights();
  389. const PODVector<Light*>& lights = drawable->GetLights();
  390. for (unsigned i = 0; i < lights.Size(); ++i)
  391. {
  392. Light* light = lights[i];
  393. // Find the correct light queue again
  394. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(light);
  395. if (j != lightQueueIndex_.End())
  396. GetLitBatches(drawable, lightQueues_[j->second_]);
  397. }
  398. }
  399. }
  400. // Go through geometries for base pass batches
  401. {
  402. PROFILE(GetBaseBatches);
  403. for (unsigned i = 0; i < geometries_.Size(); ++i)
  404. {
  405. Drawable* drawable = geometries_[i];
  406. unsigned numBatches = drawable->GetNumBatches();
  407. for (unsigned j = 0; j < numBatches; ++j)
  408. {
  409. Batch baseBatch;
  410. drawable->GetBatch(frame_, j, baseBatch);
  411. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  412. if (!baseBatch.geometry_ || !tech)
  413. continue;
  414. // Check here if the material technique refers to a render target texture with camera(s) attached
  415. // Only check this for the main view (null rendertarget)
  416. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  417. CheckMaterialForAuxView(baseBatch.material_);
  418. // If object already has a lit base pass, can skip the unlit base pass
  419. if (drawable->HasBasePass(j))
  420. continue;
  421. // Fill the rest of the batch
  422. baseBatch.camera_ = camera_;
  423. baseBatch.distance_ = drawable->GetDistance();
  424. baseBatch.hasPriority_ = true;
  425. Pass* pass = 0;
  426. // Check for unlit base pass
  427. pass = tech->GetPass(PASS_BASE);
  428. if (pass)
  429. {
  430. renderer_->SetBatchShaders(baseBatch, tech, pass);
  431. if (pass->GetBlendMode() == BLEND_REPLACE)
  432. baseQueue_.AddBatch(baseBatch);
  433. else
  434. transparentQueue_.AddBatch(baseBatch, true);
  435. continue;
  436. }
  437. else
  438. {
  439. // If no base pass, finally check for extra / custom pass
  440. pass = tech->GetPass(PASS_EXTRA);
  441. if (pass)
  442. {
  443. renderer_->SetBatchShaders(baseBatch, tech, pass);
  444. extraQueue_.AddBatch(baseBatch);
  445. }
  446. }
  447. }
  448. }
  449. }
  450. // All batches have been collected. Sort them now
  451. SortBatches();
  452. }
  453. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  454. {
  455. Light* light = lightQueue.light_;
  456. Light* firstLight = drawable->GetFirstLight();
  457. // Shadows on transparencies can only be rendered if shadow maps are not reused
  458. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  459. unsigned numBatches = drawable->GetNumBatches();
  460. for (unsigned i = 0; i < numBatches; ++i)
  461. {
  462. Batch litBatch;
  463. drawable->GetBatch(frame_, i, litBatch);
  464. Technique* tech = GetTechnique(drawable, litBatch.material_);
  465. if (!litBatch.geometry_ || !tech)
  466. continue;
  467. Pass* pass = 0;
  468. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  469. if (light == firstLight && !drawable->HasBasePass(i))
  470. {
  471. pass = tech->GetPass(PASS_LITBASE);
  472. if (pass)
  473. {
  474. litBatch.hasPriority_ = true;
  475. drawable->SetBasePass(i);
  476. }
  477. }
  478. // If no lit base pass, get ordinary light pass
  479. if (!pass)
  480. pass = tech->GetPass(PASS_LIGHT);
  481. // Skip if material does not receive light at all
  482. if (!pass)
  483. continue;
  484. // Fill the rest of the batch
  485. litBatch.camera_ = camera_;
  486. litBatch.distance_ = drawable->GetDistance();
  487. litBatch.lightQueue_ = &lightQueue;
  488. // Check from the ambient pass whether the object is opaque or transparent
  489. Pass* ambientPass = tech->GetPass(PASS_BASE);
  490. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  491. {
  492. renderer_->SetBatchShaders(litBatch, tech, pass);
  493. lightQueue.litBatches_.AddBatch(litBatch);
  494. }
  495. else
  496. {
  497. renderer_->SetBatchShaders(litBatch, tech, pass, allowTransparentShadows);
  498. transparentQueue_.AddBatch(litBatch, true);
  499. }
  500. }
  501. }
  502. void View::RenderBatches()
  503. {
  504. // If not reusing shadowmaps, render all of them first
  505. if (!renderer_->GetReuseShadowMaps())
  506. {
  507. PROFILE(RenderShadowMaps);
  508. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  509. {
  510. LightBatchQueue& queue = lightQueues_[i];
  511. if (queue.shadowMap_)
  512. RenderShadowMap(queue);
  513. }
  514. }
  515. {
  516. // Render opaque objects' base passes
  517. PROFILE(RenderBasePass);
  518. graphics_->SetRenderTarget(0, renderTarget_);
  519. graphics_->SetDepthStencil(depthStencil_);
  520. graphics_->SetViewport(screenRect_);
  521. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  522. RenderBatchQueue(baseQueue_);
  523. }
  524. {
  525. // Render shadow maps + opaque objects' shadowed additive lighting
  526. PROFILE(RenderLights);
  527. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  528. {
  529. LightBatchQueue& queue = lightQueues_[i];
  530. // If reusing shadowmaps, render each of them before the lit batches
  531. if (renderer_->GetReuseShadowMaps() && queue.shadowMap_)
  532. RenderShadowMap(queue);
  533. graphics_->SetRenderTarget(0, renderTarget_);
  534. graphics_->SetDepthStencil(depthStencil_);
  535. graphics_->SetViewport(screenRect_);
  536. RenderLightBatchQueue(queue.litBatches_, queue.light_);
  537. }
  538. }
  539. graphics_->SetScissorTest(false);
  540. graphics_->SetStencilTest(false);
  541. graphics_->SetRenderTarget(0, renderTarget_);
  542. graphics_->SetDepthStencil(depthStencil_);
  543. graphics_->SetViewport(screenRect_);
  544. if (!extraQueue_.IsEmpty())
  545. {
  546. // Render extra / custom passes
  547. PROFILE(RenderExtraPass);
  548. RenderBatchQueue(extraQueue_);
  549. }
  550. if (!transparentQueue_.IsEmpty())
  551. {
  552. // Render transparent objects last (both base passes & additive lighting)
  553. PROFILE(RenderTransparent);
  554. RenderBatchQueue(transparentQueue_, true);
  555. }
  556. }
  557. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  558. {
  559. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  560. float halfViewSize = camera->GetHalfViewSize();
  561. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  562. Vector3 cameraPos = camera->GetWorldPosition();
  563. for (unsigned i = 0; i < occluders.Size(); ++i)
  564. {
  565. Drawable* occluder = occluders[i];
  566. occluder->UpdateDistance(frame_);
  567. bool erase = false;
  568. // Check occluder's draw distance (in main camera view)
  569. float maxDistance = occluder->GetDrawDistance();
  570. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  571. erase = true;
  572. // Check that occluder is big enough on the screen
  573. const BoundingBox& box = occluder->GetWorldBoundingBox();
  574. float diagonal = (box.max_ - box.min_).LengthFast();
  575. float compare;
  576. if (!camera->IsOrthographic())
  577. compare = diagonal * halfViewSize / occluder->GetDistance();
  578. else
  579. compare = diagonal * invOrthoSize;
  580. if (compare < occluderSizeThreshold_)
  581. erase = true;
  582. if (!erase)
  583. {
  584. unsigned totalTriangles = 0;
  585. unsigned batches = occluder->GetNumBatches();
  586. Batch tempBatch;
  587. for (unsigned j = 0; j < batches; ++j)
  588. {
  589. occluder->GetBatch(frame_, j, tempBatch);
  590. if (tempBatch.geometry_)
  591. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  592. }
  593. // Store amount of triangles divided by screen size as a sorting key
  594. // (best occluders are big and have few triangles)
  595. occluder->SetSortValue((float)totalTriangles / compare);
  596. }
  597. else
  598. {
  599. occluders.Erase(occluders.Begin() + i);
  600. --i;
  601. }
  602. }
  603. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  604. if (occluders.Size())
  605. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  606. }
  607. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  608. {
  609. for (unsigned i = 0; i < occluders.Size(); ++i)
  610. {
  611. Drawable* occluder = occluders[i];
  612. if (i > 0)
  613. {
  614. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  615. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  616. continue;
  617. }
  618. occluder->UpdateGeometry(frame_);
  619. // Check for running out of triangles
  620. if (!occluder->DrawOcclusion(buffer))
  621. return;
  622. }
  623. }
  624. unsigned View::ProcessLight(Light* light)
  625. {
  626. // Check if light should be shadowed
  627. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  628. unsigned shadowSplits = 0;
  629. // If shadow distance non-zero, check it
  630. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  631. isShadowed = false;
  632. LightType type = light->GetLightType();
  633. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  634. litGeometries_.Clear();
  635. switch (type)
  636. {
  637. case LIGHT_DIRECTIONAL:
  638. for (unsigned i = 0; i < geometries_.Size(); ++i)
  639. {
  640. if (geometries_[i]->GetLightMask() & light->GetLightMask())
  641. litGeometries_.Push(geometries_[i]);
  642. }
  643. break;
  644. case LIGHT_SPOT:
  645. {
  646. FrustumOctreeQuery query(tempDrawables_, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  647. octree_->GetDrawables(query);
  648. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  649. {
  650. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  651. litGeometries_.Push(tempDrawables_[i]);
  652. }
  653. }
  654. break;
  655. case LIGHT_POINT:
  656. {
  657. SphereOctreeQuery query(tempDrawables_, Sphere(light->GetWorldPosition(), light->GetRange()), DRAWABLE_GEOMETRY,
  658. camera_->GetViewMask());
  659. octree_->GetDrawables(query);
  660. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  661. {
  662. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  663. litGeometries_.Push(tempDrawables_[i]);
  664. }
  665. }
  666. break;
  667. }
  668. // If no lit geometries or not shadowed, no need to process shadow cameras
  669. if (litGeometries_.Empty() || !isShadowed)
  670. return 0;
  671. // Determine number of shadow cameras and setup their initial positions
  672. shadowSplits = SetupShadowCameras(light);
  673. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  674. bool useOcclusion = false;
  675. OcclusionBuffer* buffer = 0;
  676. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  677. {
  678. // This shadow camera is never used for actually querying shadow casters, just occluders
  679. Camera* shadowCamera = renderer_->CreateShadowCamera();
  680. SetupDirLightShadowCamera(shadowCamera, light, 0.0f, Min(light->GetShadowCascade().GetShadowRange(), camera_->GetFarClip()),
  681. true);
  682. // Get occluders, which must be shadow-casting themselves
  683. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  684. true, true);
  685. octree_->GetDrawables(query);
  686. UpdateOccluders(shadowOccluders_, shadowCamera);
  687. if (shadowOccluders_.Size())
  688. {
  689. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  690. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  691. DrawOccluders(buffer, shadowOccluders_);
  692. buffer->BuildDepthHierarchy();
  693. useOcclusion = true;
  694. }
  695. }
  696. // Process each split for shadow casters
  697. bool hasShadowCasters = false;
  698. for (unsigned i = 0; i < shadowSplits; ++i)
  699. {
  700. shadowCasters_[i].Clear();
  701. shadowCasterBox_[i].defined_ = false;
  702. Camera* shadowCamera = shadowCameras_[i];
  703. if (!useOcclusion)
  704. {
  705. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  706. // lit geometries, whose result still exists in tempDrawables_
  707. if (type != LIGHT_SPOT)
  708. {
  709. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  710. // If a point light face, check that the face is visible: if not, there is no need to query and render
  711. // the shadow casters
  712. if (type == LIGHT_POINT)
  713. {
  714. BoundingBox shadowCameraBox(shadowCameraFrustum);
  715. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  716. continue;
  717. }
  718. FrustumOctreeQuery query(tempDrawables_, shadowCameraFrustum, DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  719. false, true);
  720. octree_->GetDrawables(query);
  721. }
  722. }
  723. else
  724. {
  725. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  726. DRAWABLE_GEOMETRY, camera_->GetViewMask(), false, true);
  727. octree_->GetDrawables(query);
  728. }
  729. // Check which shadow casters actually contribute to the shadowing
  730. ProcessShadowCasters(light, i, tempDrawables_, shadowCasterBox_[i]);
  731. if (shadowCasters_[i].Size())
  732. hasShadowCasters = true;
  733. }
  734. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  735. // only cost has been the shadow camera setup & queries
  736. if (!hasShadowCasters)
  737. shadowSplits = 0;
  738. return shadowSplits;
  739. }
  740. void View::ProcessShadowCasters(Light* light, unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& shadowCasterBox)
  741. {
  742. Matrix3x4 lightView;
  743. Matrix4 lightProj;
  744. Camera* shadowCamera = shadowCameras_[splitIndex];
  745. lightView = shadowCamera->GetInverseWorldTransform();
  746. lightProj = shadowCamera->GetProjection();
  747. bool dirLight = shadowCamera->IsOrthographic();
  748. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  749. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  750. // frustum, so that shadow casters do not get rendered into unnecessary splits
  751. Frustum lightViewFrustum;
  752. if (!dirLight)
  753. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  754. else
  755. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, shadowNearSplits_[splitIndex]),
  756. Min(sceneViewBox_.max_.z_, shadowFarSplits_[splitIndex])).Transformed(lightView);
  757. BoundingBox lightViewFrustumBox(lightViewFrustum);
  758. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  759. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  760. return;
  761. BoundingBox lightViewBox;
  762. BoundingBox lightProjBox;
  763. for (unsigned i = 0; i < result.Size(); ++i)
  764. {
  765. Drawable* drawable = static_cast<Drawable*>(result[i]);
  766. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  767. // Check for that first
  768. if (!drawable->GetCastShadows())
  769. continue;
  770. drawable->UpdateDistance(frame_);
  771. // Check shadow distance
  772. float maxShadowDistance = drawable->GetShadowDistance();
  773. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  774. continue;
  775. // Check light mask
  776. if (!(drawable->GetLightMask() & light->GetLightMask()))
  777. continue;
  778. // Project shadow caster bounding box to light view space for visibility check
  779. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  780. if (drawable->IsInView(frame_) || IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum,
  781. lightViewFrustumBox))
  782. {
  783. // Update geometry now if not updated yet
  784. if (!drawable->IsInView(frame_))
  785. {
  786. drawable->MarkInShadowView(frame_);
  787. drawable->UpdateGeometry(frame_);
  788. }
  789. // Merge to shadow caster bounding box and add to the list
  790. if (dirLight)
  791. shadowCasterBox.Merge(lightViewBox);
  792. else
  793. {
  794. lightProjBox = lightViewBox.Projected(lightProj);
  795. shadowCasterBox.Merge(lightProjBox);
  796. }
  797. shadowCasters_[splitIndex].Push(drawable);
  798. }
  799. }
  800. }
  801. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  802. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  803. {
  804. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  805. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  806. if (drawable->IsOccluder())
  807. return true;
  808. if (shadowCamera->IsOrthographic())
  809. {
  810. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  811. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  812. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  813. }
  814. else
  815. {
  816. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  817. if (drawable->IsInView(frame_))
  818. return true;
  819. // For perspective lights, extrusion direction depends on the position of the shadow caster
  820. Vector3 center = lightViewBox.Center();
  821. Ray extrusionRay(center, center.Normalized());
  822. float extrusionDistance = shadowCamera->GetFarClip();
  823. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  824. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  825. float sizeFactor = extrusionDistance / originalDistance;
  826. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  827. // than necessary, so the test will be conservative
  828. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  829. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  830. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  831. lightViewBox.Merge(extrudedBox);
  832. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  833. }
  834. }
  835. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  836. {
  837. unsigned width = shadowMap->GetWidth();
  838. unsigned height = shadowMap->GetHeight();
  839. int maxCascades = renderer_->GetMaxShadowCascades();
  840. switch (light->GetLightType())
  841. {
  842. case LIGHT_DIRECTIONAL:
  843. if (maxCascades == 1)
  844. return IntRect(0, 0, width, height);
  845. else if (maxCascades == 2)
  846. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  847. else
  848. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  849. (splitIndex / 2 + 1) * height / 2);
  850. case LIGHT_SPOT:
  851. return IntRect(0, 0, width, height);
  852. case LIGHT_POINT:
  853. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  854. (splitIndex / 2 + 1) * height / 3);
  855. }
  856. return IntRect();
  857. }
  858. void View::OptimizeLightByScissor(Light* light)
  859. {
  860. if (light)
  861. graphics_->SetScissorTest(true, GetLightScissor(light));
  862. else
  863. graphics_->SetScissorTest(false);
  864. }
  865. void View::OptimizeLightByStencil(Light* light)
  866. {
  867. if (light && renderer_->GetLightStencilMasking())
  868. {
  869. Geometry* geometry = renderer_->GetLightGeometry(light);
  870. if (!geometry)
  871. {
  872. graphics_->SetStencilTest(false);
  873. return;
  874. }
  875. LightType type = light->GetLightType();
  876. Matrix3x4 view(camera_->GetInverseWorldTransform());
  877. Matrix4 projection(camera_->GetProjection());
  878. float lightDist;
  879. if (type == LIGHT_POINT)
  880. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  881. else
  882. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  883. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  884. if (lightDist < M_EPSILON)
  885. {
  886. graphics_->SetStencilTest(false);
  887. return;
  888. }
  889. // If the stencil value has wrapped, clear the whole stencil first
  890. if (!lightStencilValue_)
  891. {
  892. graphics_->Clear(CLEAR_STENCIL);
  893. lightStencilValue_ = 1;
  894. }
  895. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  896. // to avoid clipping the front faces.
  897. if (lightDist < camera_->GetNearClip() * 2.0f)
  898. {
  899. graphics_->SetCullMode(CULL_CW);
  900. graphics_->SetDepthTest(CMP_GREATER);
  901. }
  902. else
  903. {
  904. graphics_->SetCullMode(CULL_CCW);
  905. graphics_->SetDepthTest(CMP_LESSEQUAL);
  906. }
  907. graphics_->SetColorWrite(false);
  908. graphics_->SetDepthWrite(false);
  909. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  910. graphics_->SetShaders(renderer_->GetStencilVS(), renderer_->GetStencilPS());
  911. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  912. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform());
  913. geometry->Draw(graphics_);
  914. graphics_->ClearTransformSources();
  915. graphics_->SetColorWrite(true);
  916. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  917. // Increase stencil value for next light
  918. ++lightStencilValue_;
  919. }
  920. else
  921. graphics_->SetStencilTest(false);
  922. }
  923. const Rect& View::GetLightScissor(Light* light)
  924. {
  925. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  926. if (i != lightScissorCache_.End())
  927. return i->second_;
  928. Matrix3x4 view(camera_->GetInverseWorldTransform());
  929. Matrix4 projection(camera_->GetProjection());
  930. switch (light->GetLightType())
  931. {
  932. case LIGHT_POINT:
  933. {
  934. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  935. return lightScissorCache_[light] = viewBox.Projected(projection);
  936. }
  937. case LIGHT_SPOT:
  938. {
  939. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  940. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  941. }
  942. default:
  943. return lightScissorCache_[light] = Rect::FULL;
  944. }
  945. }
  946. unsigned View::SetupShadowCameras(Light* light)
  947. {
  948. LightType type = light->GetLightType();
  949. if (type == LIGHT_DIRECTIONAL)
  950. {
  951. const CascadeParameters& cascade = light->GetShadowCascade();
  952. int splits = 0;
  953. float nearSplit = camera_->GetNearClip();
  954. float farSplit;
  955. while (splits < renderer_->GetMaxShadowCascades())
  956. {
  957. // If split is completely beyond camera far clip, we are done
  958. if (nearSplit > camera_->GetFarClip())
  959. break;
  960. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  961. if (farSplit <= nearSplit)
  962. break;
  963. // Setup the shadow camera for the split
  964. Camera* shadowCamera = renderer_->CreateShadowCamera();
  965. shadowCameras_[splits] = shadowCamera;
  966. shadowNearSplits_[splits] = nearSplit;
  967. shadowFarSplits_[splits] = farSplit;
  968. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit, false);
  969. nearSplit = farSplit;
  970. ++splits;
  971. }
  972. return splits;
  973. }
  974. if (type == LIGHT_SPOT)
  975. {
  976. Camera* shadowCamera = renderer_->CreateShadowCamera();
  977. shadowCameras_[0] = shadowCamera;
  978. Node* cameraNode = shadowCamera->GetNode();
  979. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  980. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  981. shadowCamera->SetFarClip(light->GetRange());
  982. shadowCamera->SetFov(light->GetFov());
  983. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  984. return 1;
  985. }
  986. if (type == LIGHT_POINT)
  987. {
  988. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  989. {
  990. Camera* shadowCamera = renderer_->CreateShadowCamera();
  991. shadowCameras_[i] = shadowCamera;
  992. Node* cameraNode = shadowCamera->GetNode();
  993. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  994. cameraNode->SetPosition(light->GetWorldPosition());
  995. cameraNode->SetDirection(directions[i]);
  996. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  997. shadowCamera->SetFarClip(light->GetRange());
  998. shadowCamera->SetFov(90.0f);
  999. shadowCamera->SetAspectRatio(1.0f);
  1000. }
  1001. return MAX_CUBEMAP_FACES;
  1002. }
  1003. return 0;
  1004. }
  1005. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit, bool shadowOcclusion)
  1006. {
  1007. Node* cameraNode = shadowCamera->GetNode();
  1008. float extrusionDistance = camera_->GetFarClip();
  1009. const FocusParameters& parameters = light->GetShadowFocus();
  1010. // Calculate initial position & rotation
  1011. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1012. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1013. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1014. // Calculate main camera shadowed frustum in light's view space
  1015. farSplit = Min(farSplit, camera_->GetFarClip());
  1016. // Use the scene Z bounds to limit frustum size if applicable
  1017. if (shadowOcclusion || parameters.focus_)
  1018. {
  1019. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1020. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1021. }
  1022. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1023. frustumVolume_.Define(splitFrustum);
  1024. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1025. if (!shadowOcclusion && parameters.focus_)
  1026. {
  1027. PROFILE(ClipFrustumVolume);
  1028. BoundingBox litGeometriesBox;
  1029. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1030. {
  1031. // Skip "infinite" objects like the skybox
  1032. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1033. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1034. {
  1035. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1036. (geometries_[i]->GetLightMask() & light->GetLightMask()))
  1037. litGeometriesBox.Merge(geomBox);
  1038. }
  1039. }
  1040. if (litGeometriesBox.defined_)
  1041. {
  1042. frustumVolume_.Clip(litGeometriesBox);
  1043. // If volume became empty, restore it to avoid zero size
  1044. if (frustumVolume_.Empty())
  1045. frustumVolume_.Define(splitFrustum);
  1046. }
  1047. }
  1048. // Transform frustum volume to light space
  1049. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1050. frustumVolume_.Transform(lightView);
  1051. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1052. BoundingBox shadowBox;
  1053. if (shadowOcclusion || !parameters.nonUniform_)
  1054. shadowBox.Define(Sphere(frustumVolume_));
  1055. else
  1056. shadowBox.Define(frustumVolume_);
  1057. shadowCamera->SetOrthographic(true);
  1058. shadowCamera->SetAspectRatio(1.0f);
  1059. shadowCamera->SetNearClip(0.0f);
  1060. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1061. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1062. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1063. }
  1064. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1065. const BoundingBox& shadowCasterBox)
  1066. {
  1067. const FocusParameters& parameters = light->GetShadowFocus();
  1068. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1069. LightType type = light->GetLightType();
  1070. if (type == LIGHT_DIRECTIONAL)
  1071. {
  1072. BoundingBox shadowBox;
  1073. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1074. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1075. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1076. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1077. // Requantize and snap to shadow map texels
  1078. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1079. }
  1080. if (type == LIGHT_SPOT)
  1081. {
  1082. if (parameters.focus_)
  1083. {
  1084. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1085. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1086. float viewSize = Max(viewSizeX, viewSizeY);
  1087. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1088. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1089. float quantize = parameters.quantize_ * invOrthoSize;
  1090. float minView = parameters.minView_ * invOrthoSize;
  1091. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1092. if (viewSize < 1.0f)
  1093. shadowCamera->SetZoom(1.0f / viewSize);
  1094. }
  1095. }
  1096. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1097. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1098. if (shadowCamera->GetZoom() >= 1.0f)
  1099. {
  1100. if (light->GetLightType() != LIGHT_POINT)
  1101. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1102. else
  1103. {
  1104. #ifdef USE_OPENGL
  1105. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1106. #else
  1107. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1108. #endif
  1109. }
  1110. }
  1111. }
  1112. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1113. const BoundingBox& viewBox)
  1114. {
  1115. Node* cameraNode = shadowCamera->GetNode();
  1116. const FocusParameters& parameters = light->GetShadowFocus();
  1117. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1118. float minX = viewBox.min_.x_;
  1119. float minY = viewBox.min_.y_;
  1120. float maxX = viewBox.max_.x_;
  1121. float maxY = viewBox.max_.y_;
  1122. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1123. Vector2 viewSize(maxX - minX, maxY - minY);
  1124. // Quantize size to reduce swimming
  1125. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1126. if (parameters.nonUniform_)
  1127. {
  1128. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1129. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1130. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1131. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1132. }
  1133. else if (parameters.focus_)
  1134. {
  1135. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1136. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1137. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1138. viewSize.y_ = viewSize.x_;
  1139. }
  1140. shadowCamera->SetOrthoSize(viewSize);
  1141. // Center shadow camera to the view space bounding box
  1142. Vector3 pos(shadowCamera->GetWorldPosition());
  1143. Quaternion rot(shadowCamera->GetWorldRotation());
  1144. Vector3 adjust(center.x_, center.y_, 0.0f);
  1145. cameraNode->Translate(rot * adjust);
  1146. // If the shadow map viewport is known, snap to whole texels
  1147. if (shadowMapWidth > 0.0f)
  1148. {
  1149. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1150. // Take into account that shadow map border will not be used
  1151. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1152. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1153. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1154. cameraNode->Translate(rot * snap);
  1155. }
  1156. }
  1157. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1158. {
  1159. if (!material)
  1160. material = renderer_->GetDefaultMaterial();
  1161. if (!material)
  1162. return 0;
  1163. float lodDistance = drawable->GetLodDistance();
  1164. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1165. if (techniques.Empty())
  1166. return 0;
  1167. // Check for suitable technique. Techniques should be ordered like this:
  1168. // Most distant & highest quality
  1169. // Most distant & lowest quality
  1170. // Second most distant & highest quality
  1171. // ...
  1172. for (unsigned i = 0; i < techniques.Size(); ++i)
  1173. {
  1174. const TechniqueEntry& entry = techniques[i];
  1175. Technique* technique = entry.technique_;
  1176. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1177. continue;
  1178. if (lodDistance >= entry.lodDistance_)
  1179. return technique;
  1180. }
  1181. // If no suitable technique found, fallback to the last
  1182. return techniques.Back().technique_;
  1183. }
  1184. void View::CheckMaterialForAuxView(Material* material)
  1185. {
  1186. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1187. for (unsigned i = 0; i < textures.Size(); ++i)
  1188. {
  1189. // Have to check cube & 2D textures separately
  1190. Texture* texture = textures[i];
  1191. if (texture)
  1192. {
  1193. if (texture->GetType() == Texture2D::GetTypeStatic())
  1194. {
  1195. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1196. RenderSurface* target = tex2D->GetRenderSurface();
  1197. if (target)
  1198. {
  1199. const Viewport& viewport = target->GetViewport();
  1200. if (viewport.scene_ && viewport.camera_)
  1201. renderer_->AddView(target, viewport);
  1202. }
  1203. }
  1204. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1205. {
  1206. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1207. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1208. {
  1209. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1210. if (target)
  1211. {
  1212. const Viewport& viewport = target->GetViewport();
  1213. if (viewport.scene_ && viewport.camera_)
  1214. renderer_->AddView(target, viewport);
  1215. }
  1216. }
  1217. }
  1218. }
  1219. }
  1220. // Set frame number so that we can early-out next time we come across this material on the same frame
  1221. material->MarkForAuxView(frame_.frameNumber_);
  1222. }
  1223. void View::SortBatches()
  1224. {
  1225. PROFILE(SortBatches);
  1226. baseQueue_.SortFrontToBack();
  1227. extraQueue_.SortFrontToBack();
  1228. transparentQueue_.SortBackToFront();
  1229. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1230. {
  1231. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1232. lightQueues_[i].shadowSplits_[j].shadowBatches_.SortFrontToBack();
  1233. lightQueues_[i].litBatches_.SortFrontToBack();
  1234. }
  1235. }
  1236. void View::PrepareInstancingBuffer()
  1237. {
  1238. PROFILE(PrepareInstancingBuffer);
  1239. unsigned totalInstances = 0;
  1240. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1241. totalInstances += extraQueue_.GetNumInstances(renderer_);
  1242. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1243. {
  1244. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1245. totalInstances += lightQueues_[i].shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1246. totalInstances += lightQueues_[i].litBatches_.GetNumInstances(renderer_);
  1247. }
  1248. // If fail to set buffer size, fall back to per-group locking
  1249. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1250. {
  1251. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1252. unsigned freeIndex = 0;
  1253. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1254. if (lockedData)
  1255. {
  1256. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1257. extraQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1258. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1259. {
  1260. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1261. lightQueues_[i].shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1262. lightQueues_[i].litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1263. }
  1264. instancingBuffer->Unlock();
  1265. }
  1266. }
  1267. }
  1268. void View::CalculateShaderParameters()
  1269. {
  1270. Time* time = GetSubsystem<Time>();
  1271. float farClip = camera_->GetFarClip();
  1272. float nearClip = camera_->GetNearClip();
  1273. float fogStart = Min(zone_->GetFogStart(), farClip);
  1274. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  1275. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  1276. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  1277. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1278. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1279. Vector4 depthMode = Vector4::ZERO;
  1280. if (camera_->IsOrthographic())
  1281. {
  1282. depthMode.x_ = 1.0f;
  1283. #ifdef USE_OPENGL
  1284. depthMode.z_ = 0.5f;
  1285. depthMode.w_ = 0.5f;
  1286. #else
  1287. depthMode.z_ = 1.0f;
  1288. #endif
  1289. }
  1290. else
  1291. depthMode.w_ = 1.0f / camera_->GetFarClip();
  1292. shaderParameters_.Clear();
  1293. shaderParameters_[VSP_DEPTHMODE] = depthMode;
  1294. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1295. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1296. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1297. }
  1298. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1299. {
  1300. if (useScissor)
  1301. graphics_->SetScissorTest(false);
  1302. graphics_->SetStencilTest(false);
  1303. // Priority instanced
  1304. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1305. queue.sortedPriorityBatchGroups_.End(); ++i)
  1306. {
  1307. BatchGroup* group = *i;
  1308. group->Draw(graphics_, renderer_, shaderParameters_);
  1309. }
  1310. // Priority non-instanced
  1311. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1312. {
  1313. Batch* batch = *i;
  1314. batch->Draw(graphics_, renderer_, shaderParameters_);
  1315. }
  1316. // Non-priority instanced
  1317. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1318. {
  1319. BatchGroup* group = *i;
  1320. if (useScissor && group->lightQueue_)
  1321. OptimizeLightByScissor(group->lightQueue_->light_);
  1322. group->Draw(graphics_, renderer_, shaderParameters_);
  1323. }
  1324. // Non-priority non-instanced
  1325. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1326. {
  1327. Batch* batch = *i;
  1328. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1329. if (useScissor)
  1330. {
  1331. if (!batch->hasPriority_ && batch->lightQueue_)
  1332. OptimizeLightByScissor(batch->lightQueue_->light_);
  1333. else
  1334. graphics_->SetScissorTest(false);
  1335. }
  1336. batch->Draw(graphics_, renderer_, shaderParameters_);
  1337. }
  1338. }
  1339. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1340. {
  1341. graphics_->SetScissorTest(false);
  1342. graphics_->SetStencilTest(false);
  1343. // Priority instanced
  1344. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1345. queue.sortedPriorityBatchGroups_.End(); ++i)
  1346. {
  1347. BatchGroup* group = *i;
  1348. group->Draw(graphics_, renderer_, shaderParameters_);
  1349. }
  1350. // Priority non-instanced
  1351. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1352. {
  1353. Batch* batch = *i;
  1354. batch->Draw(graphics_, renderer_, shaderParameters_);
  1355. }
  1356. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1357. OptimizeLightByStencil(light);
  1358. OptimizeLightByScissor(light);
  1359. // Non-priority instanced
  1360. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1361. {
  1362. BatchGroup* group = *i;
  1363. group->Draw(graphics_, renderer_, shaderParameters_);
  1364. }
  1365. // Non-priority non-instanced
  1366. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1367. {
  1368. Batch* batch = *i;
  1369. batch->Draw(graphics_, renderer_, shaderParameters_);
  1370. }
  1371. }
  1372. void View::RenderShadowMap(const LightBatchQueue& queue)
  1373. {
  1374. PROFILE(RenderShadowMap);
  1375. Texture2D* shadowMap = queue.shadowMap_;
  1376. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1377. if (!graphics_->GetFallback())
  1378. {
  1379. graphics_->SetColorWrite(false);
  1380. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1381. graphics_->SetDepthStencil(shadowMap);
  1382. graphics_->Clear(CLEAR_DEPTH);
  1383. }
  1384. else
  1385. {
  1386. graphics_->SetColorWrite(true);
  1387. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1388. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1389. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1390. }
  1391. // Set shadow depth bias
  1392. BiasParameters parameters = queue.light_->GetShadowBias();
  1393. // Adjust the light's constant depth bias according to global shadow map resolution
  1394. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1395. if (shadowMapSize <= 512)
  1396. parameters.constantBias_ *= 2.0f;
  1397. else if (shadowMapSize >= 2048)
  1398. parameters.constantBias_ *= 0.5f;
  1399. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1400. // Render each of the splits
  1401. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1402. {
  1403. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1404. if (!shadowQueue.shadowBatches_.IsEmpty())
  1405. {
  1406. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1407. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1408. // However, do not do this for point lights, which need to render continuously across cube faces
  1409. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1410. if (queue.light_->GetLightType() != LIGHT_POINT)
  1411. {
  1412. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1413. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1414. graphics_->SetScissorTest(true, zoomRect, false);
  1415. }
  1416. else
  1417. graphics_->SetScissorTest(false);
  1418. // Draw instanced and non-instanced shadow casters
  1419. RenderBatchQueue(shadowQueue.shadowBatches_);
  1420. }
  1421. }
  1422. graphics_->SetColorWrite(true);
  1423. graphics_->SetDepthBias(0.0f, 0.0f);
  1424. graphics_->SetScissorTest(false);
  1425. }