View.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  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. mode_ = graphics_->GetRenderMode();
  82. // In deferred mode, check for the render texture being too large
  83. if (mode_ != RENDER_FORWARD && renderTarget)
  84. {
  85. if (renderTarget->GetWidth() > graphics_->GetWidth() || renderTarget->GetHeight() > graphics_->GetHeight())
  86. {
  87. // Display message only once per rendertarget, do not spam each frame
  88. if (gBufferErrorDisplayed_.Find(renderTarget) == gBufferErrorDisplayed_.End())
  89. {
  90. gBufferErrorDisplayed_.Insert(renderTarget);
  91. LOGERROR("Render texture is larger than the G-buffer, can not render");
  92. }
  93. return false;
  94. }
  95. }
  96. octree_ = octree;
  97. camera_ = viewport.camera_;
  98. renderTarget_ = renderTarget;
  99. if (!renderTarget)
  100. depthStencil_ = 0;
  101. else
  102. {
  103. // In Direct3D9 deferred rendering, always use the system depth stencil for the whole time
  104. // to ensure it is as large as the G-buffer
  105. #ifdef USE_OPENGL
  106. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  107. #else
  108. if (mode_ == RENDER_FORWARD)
  109. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  110. else
  111. depthStencil_ = 0;
  112. #endif
  113. }
  114. zone_ = renderer_->GetDefaultZone();
  115. // Validate the rect and calculate size. If zero rect, use whole render target size
  116. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  117. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  118. if (viewport.rect_ != IntRect::ZERO)
  119. {
  120. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  121. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  122. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  123. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  124. }
  125. else
  126. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  127. width_ = screenRect_.right_ - screenRect_.left_;
  128. height_ = screenRect_.bottom_ - screenRect_.top_;
  129. // Set possible quality overrides from the camera
  130. drawShadows_ = renderer_->GetDrawShadows();
  131. materialQuality_ = renderer_->GetMaterialQuality();
  132. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  133. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  134. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  135. materialQuality_ = QUALITY_LOW;
  136. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  137. drawShadows_ = false;
  138. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  139. maxOccluderTriangles_ = 0;
  140. return true;
  141. }
  142. void View::Update(const FrameInfo& frame)
  143. {
  144. if (!camera_ || !octree_)
  145. return;
  146. frame_.camera_ = camera_;
  147. frame_.timeStep_ = frame.timeStep_;
  148. frame_.frameNumber_ = frame.frameNumber_;
  149. frame_.viewSize_ = IntVector2(width_, height_);
  150. // Clear old light scissor cache, geometry, light, occluder & batch lists
  151. lightScissorCache_.Clear();
  152. geometries_.Clear();
  153. geometryDepthBounds_.Clear();
  154. lights_.Clear();
  155. occluders_.Clear();
  156. shadowOccluders_.Clear();
  157. gBufferQueue_.Clear();
  158. baseQueue_.Clear();
  159. extraQueue_.Clear();
  160. transparentQueue_.Clear();
  161. noShadowLightQueue_.Clear();
  162. lightQueues_.Clear();
  163. // Do not update if camera projection is illegal
  164. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  165. if (!camera_->IsProjectionValid())
  166. return;
  167. // Set automatic aspect ratio if required
  168. if (camera_->GetAutoAspectRatio())
  169. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  170. // Reset projection jitter if was used last frame
  171. camera_->SetProjectionOffset(Vector2::ZERO);
  172. // Reset shadow map use count; they can be reused between views as each is rendered completely at a time
  173. renderer_->ResetShadowMapUseCount();
  174. GetDrawables();
  175. GetBatches();
  176. }
  177. void View::Render()
  178. {
  179. if (!octree_ || !camera_)
  180. return;
  181. // Forget parameter sources from the previous view
  182. graphics_->ClearParameterSources();
  183. // If stream offset is supported, write all instance transforms to a single large buffer
  184. // Else we must lock the instance buffer for each batch group
  185. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  186. PrepareInstancingBuffer();
  187. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  188. // again to ensure correct projection will be used
  189. if (camera_->GetAutoAspectRatio())
  190. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  191. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during rendering
  192. if (renderTarget_)
  193. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  194. else
  195. graphics_->SetViewTexture(0);
  196. graphics_->SetFillMode(FILL_SOLID);
  197. // Calculate view-global shader parameters
  198. CalculateShaderParameters();
  199. // If not reusing shadowmaps, render all of them first
  200. if (!renderer_->reuseShadowMaps_)
  201. {
  202. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  203. {
  204. LightBatchQueue& queue = lightQueues_[i];
  205. if (queue.light_->GetShadowMap())
  206. RenderShadowMap(queue);
  207. }
  208. }
  209. if (mode_ == RENDER_FORWARD)
  210. RenderBatchesForward();
  211. else
  212. RenderBatchesDeferred();
  213. graphics_->SetViewTexture(0);
  214. // If this is a main view, draw the associated debug geometry now
  215. if (!renderTarget_)
  216. {
  217. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  218. if (scene)
  219. {
  220. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  221. if (debug)
  222. {
  223. debug->SetView(camera_);
  224. debug->Render();
  225. }
  226. }
  227. }
  228. // "Forget" the camera, octree and zone after rendering
  229. camera_ = 0;
  230. octree_ = 0;
  231. zone_ = 0;
  232. frame_.camera_ = 0;
  233. }
  234. void View::GetDrawables()
  235. {
  236. PROFILE(GetDrawables);
  237. Vector3 cameraPos = camera_->GetWorldPosition();
  238. // Get zones & find the zone camera is in
  239. PODVector<Zone*> zones;
  240. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>& >(zones), cameraPos, DRAWABLE_ZONE, camera_->GetViewMask());
  241. octree_->GetDrawables(query);
  242. int highestZonePriority = M_MIN_INT;
  243. for (unsigned i = 0; i < zones.Size(); ++i)
  244. {
  245. Zone* zone = zones[i];
  246. if (zone->IsInside(cameraPos) && zone->GetPriority() > highestZonePriority)
  247. {
  248. zone_ = zone;
  249. highestZonePriority = zone->GetPriority();
  250. }
  251. }
  252. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  253. bool useOcclusion = false;
  254. OcclusionBuffer* buffer = 0;
  255. if (maxOccluderTriangles_ > 0)
  256. {
  257. FrustumOctreeQuery query(occluders_, camera_->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(), true, false);
  258. octree_->GetDrawables(query);
  259. UpdateOccluders(occluders_, camera_);
  260. if (occluders_.Size())
  261. {
  262. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  263. DrawOccluders(buffer, occluders_);
  264. buffer->BuildDepthHierarchy();
  265. useOcclusion = true;
  266. }
  267. }
  268. if (!useOcclusion)
  269. {
  270. // Get geometries & lights without occlusion
  271. FrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  272. octree_->GetDrawables(query);
  273. }
  274. else
  275. {
  276. // Get geometries & lights using occlusion
  277. OccludedFrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  278. camera_->GetViewMask());
  279. octree_->GetDrawables(query);
  280. }
  281. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  282. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  283. sceneBox_.defined_ = false;
  284. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  285. sceneViewBox_.defined_ = false;
  286. Matrix3x4 view(camera_->GetInverseWorldTransform());
  287. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  288. {
  289. Drawable* drawable = tempDrawables_[i];
  290. drawable->UpdateDistance(frame_);
  291. // If draw distance non-zero, check it
  292. float maxDistance = drawable->GetDrawDistance();
  293. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  294. continue;
  295. unsigned flags = drawable->GetDrawableFlags();
  296. if (flags & DRAWABLE_GEOMETRY)
  297. {
  298. drawable->ClearLights();
  299. drawable->MarkInView(frame_);
  300. drawable->UpdateGeometry(frame_);
  301. // Expand the scene bounding boxes
  302. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  303. BoundingBox geoview_Box = geomBox.Transformed(view);
  304. sceneBox_.Merge(geomBox);
  305. sceneViewBox_.Merge(geoview_Box);
  306. // Store depth info to speed up split directional light queries
  307. GeometryDepthBounds bounds;
  308. bounds.min_ = geoview_Box.min_.z_;
  309. bounds.max_ = geoview_Box.max_.z_;
  310. geometryDepthBounds_.Push(bounds);
  311. geometries_.Push(drawable);
  312. }
  313. else if (flags & DRAWABLE_LIGHT)
  314. {
  315. Light* light = static_cast<Light*>(drawable);
  316. // Skip if light is culled by the zone
  317. if (!(light->GetViewMask() & zone_->GetViewMask()))
  318. continue;
  319. light->MarkInView(frame_);
  320. lights_.Push(light);
  321. }
  322. }
  323. // Sort the lights to brightest/closest first
  324. for (unsigned i = 0; i < lights_.Size(); ++i)
  325. lights_[i]->SetIntensitySortValue(cameraPos);
  326. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  327. }
  328. void View::GetBatches()
  329. {
  330. HashSet<LitTransparencyCheck> litTransparencies;
  331. HashSet<Drawable*> maxLightsDrawables;
  332. Map<Light*, unsigned> lightQueueIndex;
  333. // Go through geometries for base pass batches
  334. {
  335. PROFILE(GetBaseBatches);
  336. for (unsigned i = 0; i < geometries_.Size(); ++i)
  337. {
  338. Drawable* drawable = geometries_[i];
  339. unsigned numBatches = drawable->GetNumBatches();
  340. for (unsigned j = 0; j < numBatches; ++j)
  341. {
  342. Batch baseBatch;
  343. drawable->GetBatch(frame_, j, baseBatch);
  344. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  345. if (!baseBatch.geometry_ || !tech)
  346. continue;
  347. // Check here if the material technique refers to a render target texture with camera(s) attached
  348. // Only check this for the main view (null rendertarget)
  349. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  350. CheckMaterialForAuxView(baseBatch.material_);
  351. // Fill the rest of the batch
  352. baseBatch.camera_ = camera_;
  353. baseBatch.distance_ = drawable->GetDistance();
  354. Pass* pass = 0;
  355. // In deferred mode, check for a G-buffer batch first
  356. if (mode_ != RENDER_FORWARD)
  357. {
  358. pass = tech->GetPass(PASS_GBUFFER);
  359. if (pass)
  360. {
  361. renderer_->SetBatchShaders(baseBatch, tech, pass);
  362. baseBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  363. gBufferQueue_.AddBatch(baseBatch);
  364. // Check also for an additional pass (possibly for emissive)
  365. pass = tech->GetPass(PASS_EXTRA);
  366. if (pass)
  367. {
  368. renderer_->SetBatchShaders(baseBatch, tech, pass);
  369. baseQueue_.AddBatch(baseBatch);
  370. }
  371. continue;
  372. }
  373. }
  374. // Then check for forward rendering base pass
  375. pass = tech->GetPass(PASS_BASE);
  376. if (pass)
  377. {
  378. renderer_->SetBatchShaders(baseBatch, tech, pass);
  379. if (pass->GetBlendMode() == BLEND_REPLACE)
  380. {
  381. baseBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  382. baseQueue_.AddBatch(baseBatch);
  383. }
  384. else
  385. {
  386. baseBatch.hasPriority_ = true;
  387. transparentQueue_.AddBatch(baseBatch, true);
  388. }
  389. continue;
  390. }
  391. else
  392. {
  393. // If no base pass, finally check for extra / custom pass
  394. pass = tech->GetPass(PASS_EXTRA);
  395. if (pass)
  396. {
  397. baseBatch.hasPriority_ = false;
  398. renderer_->SetBatchShaders(baseBatch, tech, pass);
  399. extraQueue_.AddBatch(baseBatch);
  400. }
  401. }
  402. }
  403. }
  404. }
  405. // Go through lights
  406. {
  407. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  408. unsigned lightQueueCount = 0;
  409. for (unsigned i = 0; i < lights_.Size(); ++i)
  410. {
  411. Light* light = lights_[i];
  412. unsigned splits = ProcessLight(light);
  413. if (!splits)
  414. continue;
  415. // Prepare lit object + shadow caster queues for each split
  416. if (lightQueues_.Size() < lightQueueCount + splits)
  417. lightQueues_.Resize(lightQueueCount + splits);
  418. unsigned prevLightQueueCount = lightQueueCount;
  419. for (unsigned j = 0; j < splits; ++j)
  420. {
  421. Light* splitLight = splitLights_[j];
  422. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  423. lightQueue.light_ = splitLight;
  424. lightQueue.shadowBatches_.Clear();
  425. lightQueue.litBatches_.Clear();
  426. lightQueue.volumeBatches_.Clear();
  427. lightQueue.lastSplit_ = false;
  428. // Loop through shadow casters
  429. Camera* shadowCamera = splitLight->GetShadowCamera();
  430. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  431. {
  432. Drawable* drawable = shadowCasters_[j][k];
  433. unsigned numBatches = drawable->GetNumBatches();
  434. for (unsigned l = 0; l < numBatches; ++l)
  435. {
  436. Batch shadowBatch;
  437. drawable->GetBatch(frame_, l, shadowBatch);
  438. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  439. if (!shadowBatch.geometry_ || !tech)
  440. continue;
  441. Pass* pass = tech->GetPass(PASS_SHADOW);
  442. // Skip if material has no shadow pass
  443. if (!pass)
  444. continue;
  445. // Fill the rest of the batch
  446. shadowBatch.camera_ = shadowCamera;
  447. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  448. shadowBatch.light_ = splitLight;
  449. shadowBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  450. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  451. lightQueue.shadowBatches_.AddBatch(shadowBatch);
  452. }
  453. }
  454. // Loop through lit geometries
  455. if (litGeometries_[j].Size())
  456. {
  457. bool storeLightQueue = true;
  458. for (unsigned k = 0; k < litGeometries_[j].Size(); ++k)
  459. {
  460. Drawable* drawable = litGeometries_[j][k];
  461. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  462. if (!drawable->GetMaxLights())
  463. GetLitBatches(drawable, light, splitLight, &lightQueue, litTransparencies);
  464. else
  465. {
  466. drawable->AddLight(splitLight);
  467. maxLightsDrawables.Insert(drawable);
  468. }
  469. }
  470. // Store the light queue, and light volume batch in deferred mode
  471. if (mode_ != RENDER_FORWARD)
  472. {
  473. Batch volumeBatch;
  474. volumeBatch.geometry_ = renderer_->GetLightGeometry(splitLight);
  475. volumeBatch.worldTransform_ = &splitLight->GetVolumeTransform(*camera_);
  476. volumeBatch.overrideView_ = splitLight->GetLightType() == LIGHT_DIRECTIONAL;
  477. volumeBatch.camera_ = camera_;
  478. volumeBatch.light_ = splitLight;
  479. volumeBatch.distance_ = splitLight->GetDistance();
  480. renderer_->SetLightVolumeShaders(volumeBatch);
  481. // If light is a split point light, it must be treated as shadowed in any case for correct stencil clearing
  482. if (splitLight->GetShadowMap() || splitLight->GetLightType() == LIGHT_SPLITPOINT)
  483. lightQueue.volumeBatches_.Push(volumeBatch);
  484. else
  485. {
  486. storeLightQueue = false;
  487. noShadowLightQueue_.AddBatch(volumeBatch, true);
  488. }
  489. }
  490. if (storeLightQueue)
  491. {
  492. lightQueueIndex[splitLight] = lightQueueCount;
  493. ++lightQueueCount;
  494. }
  495. }
  496. }
  497. // Mark the last split
  498. if (lightQueueCount != prevLightQueueCount)
  499. lightQueues_[lightQueueCount - 1].lastSplit_ = true;
  500. }
  501. // Resize the light queue vector now that final size is known
  502. lightQueues_.Resize(lightQueueCount);
  503. }
  504. // Process drawables with limited light count
  505. if (maxLightsDrawables.Size())
  506. {
  507. PROFILE(GetMaxLightsBatches);
  508. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables.Begin(); i != maxLightsDrawables.End(); ++i)
  509. {
  510. Drawable* drawable = *i;
  511. drawable->LimitLights();
  512. const PODVector<Light*>& lights = drawable->GetLights();
  513. for (unsigned i = 0; i < lights.Size(); ++i)
  514. {
  515. Light* splitLight = lights[i];
  516. Light* light = splitLight->GetOriginalLight();
  517. if (!light)
  518. light = splitLight;
  519. // Find the correct light queue again
  520. LightBatchQueue* queue = 0;
  521. Map<Light*, unsigned>::Iterator j = lightQueueIndex.Find(splitLight);
  522. if (j != lightQueueIndex.End())
  523. queue = &lightQueues_[j->second_];
  524. GetLitBatches(drawable, light, splitLight, queue, litTransparencies);
  525. }
  526. }
  527. }
  528. // All batches have been collected. Sort them now
  529. SortBatches();
  530. }
  531. void View::GetLitBatches(Drawable* drawable, Light* light, Light* splitLight, LightBatchQueue* lightQueue,
  532. HashSet<LitTransparencyCheck>& litTransparencies)
  533. {
  534. bool splitPointLight = splitLight->GetLightType() == LIGHT_SPLITPOINT;
  535. // Whether to allow shadows for transparencies, or for forward lit objects in deferred mode
  536. bool allowShadows = !renderer_->reuseShadowMaps_ && !splitPointLight;
  537. unsigned numBatches = drawable->GetNumBatches();
  538. for (unsigned i = 0; i < numBatches; ++i)
  539. {
  540. Batch litBatch;
  541. drawable->GetBatch(frame_, i, litBatch);
  542. Technique* tech = GetTechnique(drawable, litBatch.material_);
  543. if (!litBatch.geometry_ || !tech)
  544. continue;
  545. // If material uses opaque G-buffer rendering, skip
  546. if (mode_ != RENDER_FORWARD && tech->HasPass(PASS_GBUFFER))
  547. continue;
  548. Pass* pass = 0;
  549. bool priority = false;
  550. // Get lit pass
  551. if (!pass)
  552. pass = tech->GetPass(PASS_LIGHT);
  553. // Skip if material does not receive light at all
  554. if (!pass)
  555. continue;
  556. // Fill the rest of the batch
  557. litBatch.camera_ = camera_;
  558. litBatch.distance_ = drawable->GetDistance();
  559. litBatch.light_ = splitLight;
  560. litBatch.hasPriority_ = priority;
  561. // Check from the ambient pass whether the object is opaque
  562. Pass* ambientPass = tech->GetPass(PASS_BASE);
  563. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  564. {
  565. if (mode_ == RENDER_FORWARD)
  566. {
  567. if (lightQueue)
  568. {
  569. renderer_->SetBatchShaders(litBatch, tech, pass);
  570. lightQueue->litBatches_.AddBatch(litBatch);
  571. }
  572. }
  573. else
  574. {
  575. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  576. baseQueue_.AddBatch(litBatch);
  577. }
  578. }
  579. else
  580. {
  581. if (splitPointLight)
  582. {
  583. // Check if already lit
  584. LitTransparencyCheck check(light, drawable, i);
  585. if (litTransparencies.Find(check) != litTransparencies.End())
  586. continue;
  587. // Use the original light instead of the split one, to choose correct scissor
  588. litBatch.light_ = light;
  589. litTransparencies.Insert(check);
  590. }
  591. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  592. transparentQueue_.AddBatch(litBatch, true);
  593. }
  594. }
  595. }
  596. void View::RenderBatchesForward()
  597. {
  598. {
  599. // Render opaque objects' base passes
  600. PROFILE(RenderBasePass);
  601. graphics_->SetColorWrite(true);
  602. graphics_->SetStencilTest(false);
  603. graphics_->SetRenderTarget(0, renderTarget_);
  604. graphics_->SetDepthStencil(depthStencil_);
  605. graphics_->SetViewport(screenRect_);
  606. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  607. RenderBatchQueue(baseQueue_);
  608. }
  609. {
  610. // Render shadow maps + opaque objects' shadowed additive lighting
  611. PROFILE(RenderLights);
  612. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  613. {
  614. LightBatchQueue& queue = lightQueues_[i];
  615. // If reusing shadowmaps, render each of them before the lit batches
  616. if (renderer_->reuseShadowMaps_ && queue.light_->GetShadowMap())
  617. RenderShadowMap(queue);
  618. graphics_->SetRenderTarget(0, renderTarget_);
  619. graphics_->SetDepthStencil(depthStencil_);
  620. graphics_->SetViewport(screenRect_);
  621. RenderForwardLightBatchQueue(queue.litBatches_, queue.light_);
  622. // Clear the stencil buffer after the last split
  623. if (queue.lastSplit_)
  624. {
  625. LightType type = queue.light_->GetLightType();
  626. if (type == LIGHT_SPLITPOINT || type == LIGHT_DIRECTIONAL)
  627. DrawSplitLightToStencil(*camera_, queue.light_, true);
  628. }
  629. }
  630. }
  631. graphics_->SetRenderTarget(0, renderTarget_);
  632. graphics_->SetDepthStencil(depthStencil_);
  633. graphics_->SetViewport(screenRect_);
  634. if (!extraQueue_.IsEmpty())
  635. {
  636. // Render extra / custom passes
  637. PROFILE(RenderExtraPass);
  638. RenderBatchQueue(extraQueue_);
  639. }
  640. if (!transparentQueue_.IsEmpty())
  641. {
  642. // Render transparent objects last (both base passes & additive lighting)
  643. PROFILE(RenderTransparent);
  644. RenderBatchQueue(transparentQueue_, true);
  645. }
  646. }
  647. void View::RenderBatchesDeferred()
  648. {
  649. Texture2D* diffBuffer = graphics_->GetDiffBuffer();
  650. Texture2D* normalBuffer = graphics_->GetNormalBuffer();
  651. Texture2D* depthBuffer = graphics_->GetDepthBuffer();
  652. // Check for deferred antialiasing (edge filter) in deferred mode. Only use it on the main view (null rendertarget)
  653. bool edgeFilter = !renderTarget_ && graphics_->GetMultiSample() > 1;
  654. RenderSurface* renderBuffer = edgeFilter ? graphics_->GetScreenBuffer()->GetRenderSurface() : renderTarget_;
  655. // Calculate shader parameters needed only in deferred rendering
  656. Vector3 nearVector, farVector;
  657. camera_->GetFrustumSize(nearVector, farVector);
  658. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  659. float gBufferWidth = (float)diffBuffer->GetWidth();
  660. float gBufferHeight = (float)diffBuffer->GetHeight();
  661. float widthRange = 0.5f * width_ / gBufferWidth;
  662. float heightRange = 0.5f * height_ / gBufferHeight;
  663. #ifdef USE_OPENGL
  664. Vector4 bufferUVOffset(((float)screenRect_.left_) / gBufferWidth + widthRange,
  665. ((float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  666. // Hardware depth is non-linear in perspective views, so calculate the depth reconstruction parameters
  667. float farClip = camera_->GetFarClip();
  668. float nearClip = camera_->GetNearClip();
  669. Vector4 depthReconstruct = Vector4::ZERO;
  670. depthReconstruct.x_ = farClip / (farClip - nearClip);
  671. depthReconstruct.y_ = -nearClip / (farClip - nearClip);
  672. shaderParameters_[PSP_DEPTHRECONSTRUCT] = depthReconstruct;
  673. #else
  674. Vector4 bufferUVOffset((0.5f + (float)screenRect_.left_) / gBufferWidth + widthRange,
  675. (0.5f + (float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  676. #endif
  677. Vector4 viewportSize((float)screenRect_.left_ / gBufferWidth, (float)screenRect_.top_ / gBufferHeight,
  678. (float)screenRect_.right_ / gBufferWidth, (float)screenRect_.bottom_ / gBufferHeight);
  679. shaderParameters_[VSP_FRUSTUMSIZE] = viewportParams;
  680. shaderParameters_[VSP_GBUFFEROFFSETS] = bufferUVOffset;
  681. {
  682. // Clear and render the G-buffer
  683. PROFILE(RenderGBuffer);
  684. graphics_->SetColorWrite(true);
  685. graphics_->SetScissorTest(false);
  686. graphics_->SetStencilTest(false);
  687. #ifdef USE_OPENGL
  688. // On OpenGL, clear the diffuse and depth buffers normally
  689. graphics_->SetRenderTarget(0, diffBuffer);
  690. graphics_->SetDepthStencil(depthBuffer);
  691. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  692. graphics_->SetRenderTarget(1, normalBuffer);
  693. #else
  694. // On Direct3D9, clear only depth and stencil at first (fillrate optimization)
  695. graphics_->SetRenderTarget(0, diffBuffer);
  696. graphics_->SetRenderTarget(1, normalBuffer);
  697. graphics_->SetRenderTarget(2, depthBuffer);
  698. graphics_->SetDepthStencil(depthStencil_);
  699. graphics_->SetViewport(screenRect_);
  700. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  701. #endif
  702. RenderBatchQueue(gBufferQueue_);
  703. graphics_->SetAlphaTest(false);
  704. graphics_->SetBlendMode(BLEND_REPLACE);
  705. #ifndef USE_OPENGL
  706. // On Direct3D9, clear now the parts of G-Buffer that were not rendered into
  707. graphics_->SetDepthTest(CMP_LESSEQUAL);
  708. graphics_->SetDepthWrite(false);
  709. graphics_->ResetRenderTarget(2);
  710. graphics_->SetRenderTarget(1, depthBuffer);
  711. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("GBufferFill"),
  712. renderer_->GetPixelShader("GBufferFill"), false, shaderParameters_);
  713. #endif
  714. }
  715. {
  716. PROFILE(RenderAmbientQuad);
  717. // Render ambient color & fog. On OpenGL the depth buffer will be copied now
  718. graphics_->SetDepthTest(CMP_ALWAYS);
  719. graphics_->SetRenderTarget(0, renderBuffer);
  720. graphics_->ResetRenderTarget(1);
  721. #ifdef USE_OPENGL
  722. graphics_->SetDepthWrite(true);
  723. #else
  724. graphics_->ResetRenderTarget(2);
  725. #endif
  726. graphics_->SetDepthStencil(depthStencil_);
  727. graphics_->SetViewport(screenRect_);
  728. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  729. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  730. String pixelShaderName = "Ambient";
  731. #ifdef USE_OPENGL
  732. if (camera_->IsOrthographic())
  733. pixelShaderName += "Ortho";
  734. // On OpenGL, set up a stencil operation to reset the stencil during ambient quad rendering
  735. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_ZERO, OP_KEEP, OP_KEEP);
  736. #endif
  737. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Ambient"),
  738. renderer_->GetPixelShader("Ambient"), false, shaderParameters_);
  739. #ifdef USE_OPENGL
  740. graphics_->SetStencilTest(false);
  741. #endif
  742. }
  743. {
  744. // Render lights
  745. PROFILE(RenderLights);
  746. // Shadowed lights
  747. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  748. {
  749. LightBatchQueue& queue = lightQueues_[i];
  750. // If reusing shadowmaps, render each of them before the lit batches
  751. if (renderer_->reuseShadowMaps_ && queue.light_->GetShadowMap())
  752. RenderShadowMap(queue);
  753. // Light volume batches are not sorted as there should be only one of them
  754. if (queue.volumeBatches_.Size())
  755. {
  756. graphics_->SetRenderTarget(0, renderBuffer);
  757. graphics_->SetDepthStencil(depthStencil_);
  758. graphics_->SetViewport(screenRect_);
  759. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  760. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  761. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  762. for (unsigned j = 0; j < queue.volumeBatches_.Size(); ++j)
  763. {
  764. renderer_->SetupLightBatch(queue.volumeBatches_[j]);
  765. queue.volumeBatches_[j].Draw(graphics_, shaderParameters_);
  766. }
  767. // If was the last split of a split point light, clear the stencil by rendering the point light again
  768. if (queue.lastSplit_ && queue.light_->GetLightType() == LIGHT_SPLITPOINT)
  769. DrawSplitLightToStencil(*camera_, queue.light_, true);
  770. }
  771. }
  772. // Non-shadowed lights
  773. if (noShadowLightQueue_.sortedBatches_.Size())
  774. {
  775. graphics_->SetRenderTarget(0, renderBuffer);
  776. graphics_->SetDepthStencil(depthStencil_);
  777. graphics_->SetViewport(screenRect_);
  778. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  779. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  780. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  781. for (unsigned i = 0; i < noShadowLightQueue_.sortedBatches_.Size(); ++i)
  782. {
  783. renderer_->SetupLightBatch(*noShadowLightQueue_.sortedBatches_[i]);
  784. noShadowLightQueue_.sortedBatches_[i]->Draw(graphics_, shaderParameters_);
  785. }
  786. }
  787. }
  788. {
  789. // Render base passes
  790. PROFILE(RenderBasePass);
  791. graphics_->SetStencilTest(false);
  792. graphics_->SetTexture(TU_DIFFBUFFER, 0);
  793. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  794. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  795. graphics_->SetRenderTarget(0, renderBuffer);
  796. graphics_->SetDepthStencil(depthStencil_);
  797. graphics_->SetViewport(screenRect_);
  798. RenderBatchQueue(baseQueue_, true);
  799. }
  800. if (!extraQueue_.IsEmpty())
  801. {
  802. // Render extra / custom passes
  803. PROFILE(RenderExtraPass);
  804. RenderBatchQueue(extraQueue_);
  805. }
  806. if (!transparentQueue_.IsEmpty())
  807. {
  808. // Render transparent objects last (both ambient & additive lighting)
  809. PROFILE(RenderTransparent);
  810. RenderBatchQueue(transparentQueue_, true);
  811. }
  812. // Render deferred antialiasing now if enabled
  813. if (edgeFilter)
  814. {
  815. PROFILE(RenderEdgeFilter);
  816. const EdgeFilterParameters& parameters = renderer_->GetEdgeFilter();
  817. ShaderVariation* vs = renderer_->GetVertexShader("EdgeFilter");
  818. ShaderVariation* ps = renderer_->GetPixelShader("EdgeFilter");
  819. HashMap<StringHash, Vector4> shaderParameters(shaderParameters_);
  820. shaderParameters[PSP_EDGEFILTERPARAMS] = Vector4(parameters.radius_, parameters.threshold_, parameters.strength_, 0.0f);
  821. shaderParameters[PSP_SAMPLEOFFSETS] = Vector4(1.0f / gBufferWidth, 1.0f / gBufferHeight, 0.0f, 0.0f);
  822. graphics_->SetAlphaTest(false);
  823. graphics_->SetBlendMode(BLEND_REPLACE);
  824. graphics_->SetDepthTest(CMP_ALWAYS),
  825. graphics_->SetStencilTest(false);
  826. graphics_->SetRenderTarget(0, renderTarget_);
  827. graphics_->SetDepthStencil(depthStencil_);
  828. graphics_->SetViewport(screenRect_);
  829. graphics_->SetTexture(TU_DIFFBUFFER, graphics_->GetScreenBuffer());
  830. renderer_->DrawFullScreenQuad(*camera_, vs, ps, false, shaderParameters);
  831. }
  832. }
  833. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  834. {
  835. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  836. float halfViewSize = camera->GetHalfViewSize();
  837. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  838. Vector3 cameraPos = camera->GetWorldPosition();
  839. for (unsigned i = 0; i < occluders.Size(); ++i)
  840. {
  841. Drawable* occluder = occluders[i];
  842. occluder->UpdateDistance(frame_);
  843. bool erase = false;
  844. // Check occluder's draw distance (in main camera view)
  845. float maxDistance = occluder->GetDrawDistance();
  846. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  847. erase = true;
  848. // Check that occluder is big enough on the screen
  849. const BoundingBox& box = occluder->GetWorldBoundingBox();
  850. float diagonal = (box.max_ - box.min_).LengthFast();
  851. float compare;
  852. if (!camera->IsOrthographic())
  853. compare = diagonal * halfViewSize / occluder->GetDistance();
  854. else
  855. compare = diagonal * invOrthoSize;
  856. if (compare < occluderSizeThreshold_)
  857. erase = true;
  858. if (!erase)
  859. {
  860. unsigned totalTriangles = 0;
  861. unsigned batches = occluder->GetNumBatches();
  862. Batch tempBatch;
  863. for (unsigned j = 0; j < batches; ++j)
  864. {
  865. occluder->GetBatch(frame_, j, tempBatch);
  866. if (tempBatch.geometry_)
  867. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  868. }
  869. // Store amount of triangles divided by screen size as a sorting key
  870. // (best occluders are big and have few triangles)
  871. occluder->SetSortValue((float)totalTriangles / compare);
  872. }
  873. else
  874. {
  875. occluders.Erase(occluders.Begin() + i);
  876. --i;
  877. }
  878. }
  879. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  880. if (occluders.Size())
  881. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  882. }
  883. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  884. {
  885. for (unsigned i = 0; i < occluders.Size(); ++i)
  886. {
  887. Drawable* occluder = occluders[i];
  888. if (i > 0)
  889. {
  890. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  891. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  892. continue;
  893. }
  894. occluder->UpdateGeometry(frame_);
  895. // Check for running out of triangles
  896. if (!occluder->DrawOcclusion(buffer))
  897. return;
  898. }
  899. }
  900. unsigned View::ProcessLight(Light* light)
  901. {
  902. unsigned numLitGeometries = 0;
  903. unsigned numShadowCasters = 0;
  904. unsigned numSplits;
  905. // Check if light should be shadowed
  906. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  907. // If shadow distance non-zero, check it
  908. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  909. isShadowed = false;
  910. // If light has no ramp textures defined, set defaults
  911. if (light->GetLightType() != LIGHT_DIRECTIONAL && !light->GetRampTexture())
  912. light->SetRampTexture(renderer_->GetDefaultLightRamp());
  913. if (light->GetLightType() == LIGHT_SPOT && !light->GetShapeTexture())
  914. light->SetShapeTexture(renderer_->GetDefaultLightSpot());
  915. // Split the light if necessary
  916. if (isShadowed)
  917. numSplits = SplitLight(light);
  918. else
  919. {
  920. // No splitting, use the original light
  921. splitLights_[0] = light;
  922. numSplits = 1;
  923. }
  924. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  925. bool useOcclusion = false;
  926. OcclusionBuffer* buffer = 0;
  927. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  928. {
  929. // This shadow camera is never used for actually querying shadow casters, just occluders
  930. Camera* shadowCamera = renderer_->CreateShadowCamera();
  931. light->SetShadowCamera(shadowCamera);
  932. SetupShadowCamera(light, true);
  933. // Get occluders, which must be shadow-casting themselves
  934. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(), true,
  935. true);
  936. octree_->GetDrawables(query);
  937. UpdateOccluders(shadowOccluders_, shadowCamera);
  938. if (shadowOccluders_.Size())
  939. {
  940. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  941. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  942. DrawOccluders(buffer, shadowOccluders_);
  943. buffer->BuildDepthHierarchy();
  944. useOcclusion = true;
  945. }
  946. }
  947. // Process each split for shadow camera update, lit geometries, and shadow casters
  948. for (unsigned i = 0; i < numSplits; ++i)
  949. {
  950. litGeometries_[i].Clear();
  951. shadowCasters_[i].Clear();
  952. }
  953. for (unsigned i = 0; i < numSplits; ++i)
  954. {
  955. Light* split = splitLights_[i];
  956. LightType type = split->GetLightType();
  957. bool isSplitShadowed = isShadowed && split->GetCastShadows();
  958. Camera* shadowCamera = 0;
  959. // If shadow casting, choose the shadow map & update shadow camera
  960. if (isSplitShadowed)
  961. {
  962. shadowCamera = renderer_->CreateShadowCamera();
  963. split->SetShadowMap(renderer_->GetShadowMap(splitLights_[i]->GetShadowResolution()));
  964. // Check if managed to get a shadow map. Otherwise must convert to non-shadowed
  965. if (split->GetShadowMap())
  966. {
  967. split->SetShadowCamera(shadowCamera);
  968. SetupShadowCamera(split);
  969. }
  970. else
  971. {
  972. isSplitShadowed = false;
  973. split->SetShadowCamera(0);
  974. }
  975. }
  976. else
  977. {
  978. split->SetShadowCamera(0);
  979. split->SetShadowMap(0);
  980. }
  981. BoundingBox geometryBox;
  982. BoundingBox shadowCasterBox;
  983. switch (type)
  984. {
  985. case LIGHT_DIRECTIONAL:
  986. // Loop through visible geometries and check if they belong to this split
  987. {
  988. float nearSplit = split->GetNearSplit() - split->GetNearFadeRange();
  989. float farSplit = split->GetFarSplit();
  990. // If split extends to the whole visible frustum, no depth check necessary
  991. bool optimize = nearSplit <= camera_->GetNearClip() && farSplit >= camera_->GetFarClip();
  992. // If whole visible scene is outside the split, can reject trivially
  993. if (sceneViewBox_.min_.z_ > farSplit || sceneViewBox_.max_.z_ < nearSplit)
  994. {
  995. split->SetShadowMap(0);
  996. continue;
  997. }
  998. bool generateBoxes = isSplitShadowed && split->GetShadowFocus().focus_;
  999. Matrix3x4 lightView;
  1000. if (shadowCamera)
  1001. lightView = shadowCamera->GetInverseWorldTransform();
  1002. if (!optimize)
  1003. {
  1004. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1005. {
  1006. Drawable* drawable = geometries_[j];
  1007. const GeometryDepthBounds& bounds = geometryDepthBounds_[j];
  1008. // Check bounds and light mask
  1009. if (bounds.min_ <= farSplit && bounds.max_ >= nearSplit && drawable->GetLightMask() &
  1010. split->GetLightMask())
  1011. {
  1012. litGeometries_[i].Push(drawable);
  1013. if (generateBoxes)
  1014. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1015. }
  1016. }
  1017. }
  1018. else
  1019. {
  1020. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1021. {
  1022. Drawable* drawable = geometries_[j];
  1023. // Need to check light mask only
  1024. if (drawable->GetLightMask() & split->GetLightMask())
  1025. {
  1026. litGeometries_[i].Push(drawable);
  1027. if (generateBoxes)
  1028. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1029. }
  1030. }
  1031. }
  1032. }
  1033. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  1034. if (isSplitShadowed && litGeometries_[i].Size())
  1035. {
  1036. Camera* shadowCamera = split->GetShadowCamera();
  1037. if (!useOcclusion)
  1038. {
  1039. // Get potential shadow casters without occlusion
  1040. FrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY,
  1041. camera_->GetViewMask());
  1042. octree_->GetDrawables(query);
  1043. }
  1044. else
  1045. {
  1046. // Get potential shadow casters with occlusion
  1047. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  1048. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1049. octree_->GetDrawables(query);
  1050. }
  1051. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, false, isSplitShadowed);
  1052. }
  1053. break;
  1054. case LIGHT_POINT:
  1055. {
  1056. SphereOctreeQuery query(tempDrawables_, Sphere(split->GetWorldPosition(), split->GetRange()), DRAWABLE_GEOMETRY,
  1057. camera_->GetViewMask());
  1058. octree_->GetDrawables(query);
  1059. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, false);
  1060. }
  1061. break;
  1062. case LIGHT_SPOT:
  1063. case LIGHT_SPLITPOINT:
  1064. {
  1065. FrustumOctreeQuery query(tempDrawables_, splitLights_[i]->GetFrustum(), DRAWABLE_GEOMETRY,
  1066. camera_->GetViewMask());
  1067. octree_->GetDrawables(query);
  1068. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, isSplitShadowed);
  1069. }
  1070. break;
  1071. }
  1072. // Optimization: if a particular split has no shadow casters, render as unshadowed
  1073. if (!shadowCasters_[i].Size())
  1074. split->SetShadowMap(0);
  1075. // Focus shadow camera as applicable
  1076. if (split->GetShadowMap())
  1077. {
  1078. if (split->GetShadowFocus().focus_)
  1079. FocusShadowCamera(split, geometryBox, shadowCasterBox);
  1080. // Set a zoom factor to ensure that we do not render to the shadow map border
  1081. // (clamp addressing is necessary because border mode /w hardware shadow maps is not supported by all GPUs)
  1082. Camera* shadowCamera = split->GetShadowCamera();
  1083. Texture2D* shadowMap = split->GetShadowMap();
  1084. if (shadowCamera->GetZoom() >= 1.0f)
  1085. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((float)(shadowMap->GetWidth() - 2) /
  1086. (float)shadowMap->GetWidth()));
  1087. }
  1088. // Update count of total lit geometries & shadow casters
  1089. numLitGeometries += litGeometries_[i].Size();
  1090. numShadowCasters += shadowCasters_[i].Size();
  1091. }
  1092. // If no lit geometries at all, no need to process further
  1093. if (!numLitGeometries)
  1094. numSplits = 0;
  1095. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  1096. else if (!numShadowCasters)
  1097. {
  1098. if (numSplits > 1)
  1099. {
  1100. // Make sure there are no duplicates
  1101. HashSet<Drawable*> allLitGeometries;
  1102. for (unsigned i = 0; i < numSplits; ++i)
  1103. {
  1104. for (Vector<Drawable*>::Iterator j = litGeometries_[i].Begin(); j != litGeometries_[i].End(); ++j)
  1105. allLitGeometries.Insert(*j);
  1106. }
  1107. litGeometries_[0].Resize(allLitGeometries.Size());
  1108. unsigned index = 0;
  1109. for (HashSet<Drawable*>::Iterator i = allLitGeometries.Begin(); i != allLitGeometries.End(); ++i)
  1110. litGeometries_[0][index++] = *i;
  1111. }
  1112. splitLights_[0] = light;
  1113. splitLights_[0]->SetShadowMap(0);
  1114. numSplits = 1;
  1115. }
  1116. return numSplits;
  1117. }
  1118. void View::ProcessLightQuery(unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& geometryBox,
  1119. BoundingBox& shadowCasterBox, bool getLitGeometries, bool getShadowCasters)
  1120. {
  1121. Light* light = splitLights_[splitIndex];
  1122. Matrix3x4 lightView;
  1123. Matrix4 lightProj;
  1124. Frustum lightViewFrustum;
  1125. BoundingBox lightViewFrustumBox;
  1126. bool mergeBoxes = light->GetLightType() != LIGHT_SPLITPOINT && light->GetShadowMap() && light->GetShadowFocus().focus_;
  1127. bool projectBoxes = false;
  1128. Camera* shadowCamera = light->GetShadowCamera();
  1129. if (shadowCamera)
  1130. {
  1131. bool projectBoxes = !shadowCamera->IsOrthographic();
  1132. lightView = shadowCamera->GetInverseWorldTransform();
  1133. lightProj = shadowCamera->GetProjection();
  1134. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  1135. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  1136. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  1137. // rendered into unnecessary splits
  1138. if (light->GetLightType() != LIGHT_DIRECTIONAL)
  1139. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1140. else
  1141. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, light->GetNearSplit() -
  1142. light->GetNearFadeRange()), Min(sceneViewBox_.max_.z_, light->GetFarSplit())).Transformed(lightView);
  1143. lightViewFrustumBox.Define(lightViewFrustum);
  1144. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1145. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1146. getShadowCasters = false;
  1147. }
  1148. else
  1149. getShadowCasters = false;
  1150. BoundingBox lightViewBox;
  1151. BoundingBox lightProjBox;
  1152. for (unsigned i = 0; i < result.Size(); ++i)
  1153. {
  1154. Drawable* drawable = static_cast<Drawable*>(result[i]);
  1155. drawable->UpdateDistance(frame_);
  1156. bool boxGenerated = false;
  1157. // If draw distance non-zero, check it
  1158. float maxDistance = drawable->GetDrawDistance();
  1159. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  1160. continue;
  1161. // Check light mask
  1162. if (!(drawable->GetLightMask() & light->GetLightMask()))
  1163. continue;
  1164. // Get lit geometry only if inside main camera frustum this frame
  1165. if (getLitGeometries && drawable->IsInView(frame_))
  1166. {
  1167. if (mergeBoxes)
  1168. {
  1169. // Transform bounding box into light view space, and to projection space if needed
  1170. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1171. if (!projectBoxes)
  1172. geometryBox.Merge(lightViewBox);
  1173. else
  1174. {
  1175. lightProjBox = lightViewBox.Projected(lightProj);
  1176. geometryBox.Merge(lightProjBox);
  1177. }
  1178. boxGenerated = true;
  1179. }
  1180. litGeometries_[splitIndex].Push(drawable);
  1181. }
  1182. // Shadow caster need not be inside main camera frustum: in that case try to detect whether
  1183. // the shadow projection intersects the view
  1184. if (getShadowCasters && drawable->GetCastShadows())
  1185. {
  1186. // If shadow distance non-zero, check it
  1187. float maxShadowDistance = drawable->GetShadowDistance();
  1188. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1189. continue;
  1190. if (!boxGenerated)
  1191. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1192. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1193. {
  1194. if (mergeBoxes)
  1195. {
  1196. if (!projectBoxes)
  1197. shadowCasterBox.Merge(lightViewBox);
  1198. else
  1199. {
  1200. if (!boxGenerated)
  1201. lightProjBox = lightViewBox.Projected(lightProj);
  1202. shadowCasterBox.Merge(lightProjBox);
  1203. }
  1204. }
  1205. // Update geometry now if not updated yet
  1206. if (!drawable->IsInView(frame_))
  1207. {
  1208. drawable->MarkInShadowView(frame_);
  1209. drawable->UpdateGeometry(frame_);
  1210. }
  1211. shadowCasters_[splitIndex].Push(drawable);
  1212. }
  1213. }
  1214. }
  1215. }
  1216. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1217. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1218. {
  1219. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  1220. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  1221. if (drawable->IsOccluder())
  1222. return true;
  1223. if (shadowCamera->IsOrthographic())
  1224. {
  1225. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1226. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1227. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1228. }
  1229. else
  1230. {
  1231. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1232. if (drawable->IsInView(frame_))
  1233. return true;
  1234. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1235. Vector3 center = lightViewBox.Center();
  1236. Ray extrusionRay(center, center.Normalized());
  1237. float extrusionDistance = shadowCamera->GetFarClip();
  1238. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1239. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1240. float sizeFactor = extrusionDistance / originalDistance;
  1241. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1242. // than necessary, so the test will be conservative
  1243. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1244. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1245. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1246. lightViewBox.Merge(extrudedBox);
  1247. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1248. }
  1249. }
  1250. void View::SetupShadowCamera(Light* light, bool shadowOcclusion)
  1251. {
  1252. Camera* shadowCamera = light->GetShadowCamera();
  1253. Node* cameraNode = shadowCamera->GetNode();
  1254. const FocusParameters& parameters = light->GetShadowFocus();
  1255. // Reset zoom
  1256. shadowCamera->SetZoom(1.0f);
  1257. switch (light->GetLightType())
  1258. {
  1259. case LIGHT_DIRECTIONAL:
  1260. {
  1261. float extrusionDistance = camera_->GetFarClip();
  1262. // Calculate initial position & rotation
  1263. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1264. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1265. Quaternion rot(Vector3::FORWARD, lightWorldDirection);
  1266. cameraNode->SetTransform(pos, rot);
  1267. // Calculate main camera shadowed frustum in light's view space
  1268. float sceneMaxZ = camera_->GetFarClip();
  1269. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  1270. if (shadowOcclusion || parameters.focus_)
  1271. sceneMaxZ = Min(sceneViewBox_.max_.z_, sceneMaxZ);
  1272. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1273. Frustum lightViewSplitFrustum = camera_->GetSplitFrustum(light->GetNearSplit() - light->GetNearFadeRange(),
  1274. Min(light->GetFarSplit(), sceneMaxZ)).Transformed(lightView);
  1275. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  1276. BoundingBox shadowBox;
  1277. if (!shadowOcclusion && parameters.nonUniform_)
  1278. shadowBox.Define(lightViewSplitFrustum);
  1279. else
  1280. {
  1281. Sphere shadowSphere;
  1282. shadowSphere.Define(lightViewSplitFrustum);
  1283. shadowBox.Define(shadowSphere);
  1284. }
  1285. shadowCamera->SetOrthographic(true);
  1286. shadowCamera->SetNearClip(0.0f);
  1287. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1288. // Center shadow camera on the bounding box, snap to whole texels
  1289. QuantizeDirShadowCamera(light, shadowBox);
  1290. }
  1291. break;
  1292. case LIGHT_SPOT:
  1293. case LIGHT_SPLITPOINT:
  1294. {
  1295. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1296. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1297. shadowCamera->SetFarClip(light->GetRange());
  1298. shadowCamera->SetOrthographic(false);
  1299. shadowCamera->SetFov(light->GetFov());
  1300. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1301. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  1302. if (light->GetLightType() == LIGHT_SPOT && parameters.zoomOut_)
  1303. {
  1304. // Make sure the out-zooming does not start while we are inside the spot
  1305. float distance = Max((camera_->GetInverseWorldTransform() * light->GetWorldPosition()).z_ - light->GetRange(),
  1306. 1.0f);
  1307. float lightPixels = (((float)height_ * light->GetRange() * camera_->GetZoom() * 0.5f) / distance);
  1308. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  1309. if (lightPixels < SHADOW_MIN_PIXELS)
  1310. lightPixels = SHADOW_MIN_PIXELS;
  1311. float zoomLevel = Min(lightPixels / (float)light->GetShadowMap()->GetHeight(), 1.0f);
  1312. shadowCamera->SetZoom(zoomLevel);
  1313. }
  1314. }
  1315. break;
  1316. }
  1317. }
  1318. void View::FocusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  1319. {
  1320. // If either no geometries or no shadow casters, do nothing
  1321. if (!geometryBox.defined_ || !shadowCasterBox.defined_)
  1322. return;
  1323. Camera* shadowCamera = light->GetShadowCamera();
  1324. const FocusParameters& parameters = light->GetShadowFocus();
  1325. switch (light->GetLightType())
  1326. {
  1327. case LIGHT_DIRECTIONAL:
  1328. {
  1329. BoundingBox combinedBox;
  1330. combinedBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1331. combinedBox.max_.x_ = shadowCamera->GetAspectRatio() * combinedBox.max_.y_;
  1332. combinedBox.min_.y_ = -combinedBox.max_.y_;
  1333. combinedBox.min_.x_ = -combinedBox.max_.x_;
  1334. combinedBox.Intersect(geometryBox);
  1335. combinedBox.Intersect(shadowCasterBox);
  1336. QuantizeDirShadowCamera(light, combinedBox);
  1337. }
  1338. break;
  1339. case LIGHT_SPOT:
  1340. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  1341. if (shadowCamera->GetZoom() >= 1.0f)
  1342. {
  1343. BoundingBox combinedBox(-1.0f, 1.0f);
  1344. combinedBox.Intersect(geometryBox);
  1345. combinedBox.Intersect(shadowCasterBox);
  1346. float viewSizeX = Max(fabsf(combinedBox.min_.x_), fabsf(combinedBox.max_.x_));
  1347. float viewSizeY = Max(fabsf(combinedBox.min_.y_), fabsf(combinedBox.max_.y_));
  1348. float viewSize = Max(viewSizeX, viewSizeY);
  1349. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1350. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1351. float quantize = parameters.quantize_ * invOrthoSize;
  1352. float minView = parameters.minView_ * invOrthoSize;
  1353. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1354. if (viewSize < 1.0f)
  1355. shadowCamera->SetZoom(1.0f / viewSize);
  1356. }
  1357. break;
  1358. }
  1359. }
  1360. void View::QuantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  1361. {
  1362. Camera* shadowCamera = light->GetShadowCamera();
  1363. Node* cameraNode = shadowCamera->GetNode();
  1364. const FocusParameters& parameters = light->GetShadowFocus();
  1365. float minX = viewBox.min_.x_;
  1366. float minY = viewBox.min_.y_;
  1367. float maxX = viewBox.max_.x_;
  1368. float maxY = viewBox.max_.y_;
  1369. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1370. Vector2 viewSize(maxX - minX, maxY - minY);
  1371. // Quantize size to reduce swimming
  1372. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1373. if (parameters.nonUniform_)
  1374. {
  1375. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1376. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1377. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1378. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1379. }
  1380. else if (parameters.focus_)
  1381. {
  1382. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1383. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1384. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1385. viewSize.y_ = viewSize.x_;
  1386. }
  1387. shadowCamera->SetOrthoSize(viewSize);
  1388. // Center shadow camera to the view space bounding box
  1389. Vector3 pos = shadowCamera->GetWorldPosition();
  1390. Quaternion rot = shadowCamera->GetWorldRotation();
  1391. Vector3 adjust(center.x_, center.y_, 0.0f);
  1392. cameraNode->Translate(rot * adjust);
  1393. // If there is a shadow map, snap to its whole texels
  1394. Texture2D* shadowMap = light->GetShadowMap();
  1395. if (shadowMap)
  1396. {
  1397. Vector3 viewPos(rot.Inverse() * shadowCamera->GetWorldPosition());
  1398. // Take into account that shadow map border will not be used
  1399. float invActualSize = 1.0f / (float)(shadowMap->GetWidth() - 2);
  1400. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1401. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1402. cameraNode->Translate(rot * snap);
  1403. }
  1404. }
  1405. void View::OptimizeLightByScissor(Light* light)
  1406. {
  1407. if (light)
  1408. graphics_->SetScissorTest(true, GetLightScissor(light));
  1409. else
  1410. graphics_->SetScissorTest(false);
  1411. }
  1412. const Rect& View::GetLightScissor(Light* light)
  1413. {
  1414. Map<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1415. if (i != lightScissorCache_.End())
  1416. return i->second_;
  1417. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1418. Matrix4 projection(camera_->GetProjection());
  1419. switch (light->GetLightType())
  1420. {
  1421. case LIGHT_POINT:
  1422. {
  1423. BoundingBox viewBox = light->GetWorldBoundingBox().Transformed(view);
  1424. return lightScissorCache_[light] = viewBox.Projected(projection);
  1425. }
  1426. case LIGHT_SPOT:
  1427. case LIGHT_SPLITPOINT:
  1428. {
  1429. Frustum viewFrustum = light->GetFrustum().Transformed(view);
  1430. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1431. }
  1432. default:
  1433. return lightScissorCache_[light] = Rect::FULL;
  1434. }
  1435. }
  1436. unsigned View::SplitLight(Light* light)
  1437. {
  1438. LightType type = light->GetLightType();
  1439. if (type == LIGHT_DIRECTIONAL)
  1440. {
  1441. const CascadeParameters& cascade = light->GetShadowCascade();
  1442. unsigned splits = cascade.splits_;
  1443. if (splits > MAX_LIGHT_SPLITS - 1)
  1444. splits = MAX_LIGHT_SPLITS - 1;
  1445. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  1446. float farClip = Min(cascade.shadowRange_, camera_->GetFarClip()); // Shadow range end
  1447. float nearClip = Max(camera_->GetNearClip(), M_MIN_NEARCLIP); // Shadow range start
  1448. bool createExtraSplit = farClip < camera_->GetFarClip();
  1449. // Practical split scheme (Zhang et al.)
  1450. unsigned i;
  1451. for (i = 0; i < splits; ++i)
  1452. {
  1453. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  1454. float splitFadeRange = Max(cascade.splitFadeRange_, 0.001f);
  1455. float iPerM = (float)i / (float)splits;
  1456. float log = nearClip * powf(farClip / nearClip, iPerM);
  1457. float uniform = nearClip + (farClip - nearClip) * iPerM;
  1458. float nearSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1459. float nearFadeRange = nearSplit * splitFadeRange;
  1460. iPerM = (float)(i + 1) / (float)splits;
  1461. log = nearClip * powf(farClip / nearClip, iPerM);
  1462. uniform = nearClip + (farClip - nearClip) * iPerM;
  1463. float farSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1464. float farFadeRange = farSplit * splitFadeRange;
  1465. // If split is completely beyond camera far clip, we are done
  1466. if ((nearSplit - nearFadeRange) > camera_->GetFarClip())
  1467. break;
  1468. Light* splitLight = renderer_->CreateSplitLight(light);
  1469. splitLights_[i] = splitLight;
  1470. // Though the near clip was previously clamped, use the real near clip value for the first split,
  1471. // so that there are no unlit portions
  1472. if (i)
  1473. splitLight->SetNearSplit(nearSplit);
  1474. else
  1475. splitLight->SetNearSplit(camera_->GetNearClip());
  1476. splitLight->SetNearFadeRange(nearFadeRange);
  1477. splitLight->SetFarSplit(farSplit);
  1478. // If not creating an extra split, the final split should not fade
  1479. splitLight->SetFarFadeRange((createExtraSplit || i < splits - 1) ? farFadeRange : 0.0f);
  1480. // Create an extra unshadowed split if necessary
  1481. if (createExtraSplit && i == splits - 1)
  1482. {
  1483. Light* splitLight = renderer_->CreateSplitLight(light);
  1484. splitLights_[i + 1] = splitLight;
  1485. splitLight->SetNearSplit(farSplit);
  1486. splitLight->SetNearFadeRange(farFadeRange);
  1487. splitLight->SetCastShadows(false);
  1488. }
  1489. }
  1490. if (createExtraSplit)
  1491. return i + 1;
  1492. else
  1493. return i;
  1494. }
  1495. if (type == LIGHT_POINT)
  1496. {
  1497. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1498. {
  1499. Light* splitLight = renderer_->CreateSplitLight(light);
  1500. Node* lightNode = splitLight->GetNode();
  1501. splitLights_[i] = splitLight;
  1502. splitLight->SetLightType(LIGHT_SPLITPOINT);
  1503. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1504. lightNode->SetDirection(directions[i]);
  1505. splitLight->SetFov(90.0f);
  1506. splitLight->SetAspectRatio(1.0f);
  1507. }
  1508. return MAX_CUBEMAP_FACES;
  1509. }
  1510. // A spot light does not actually need splitting. However, we may be rendering several views,
  1511. // and in some the light might be unshadowed, so better create an unique copy
  1512. Light* splitLight = renderer_->CreateSplitLight(light);
  1513. splitLights_[0] = splitLight;
  1514. return 1;
  1515. }
  1516. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1517. {
  1518. if (!material)
  1519. material = renderer_->GetDefaultMaterial();
  1520. if (!material)
  1521. return 0;
  1522. float lodDistance = drawable->GetLodDistance();
  1523. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1524. if (techniques.Empty())
  1525. return 0;
  1526. // Check for suitable technique. Techniques should be ordered like this:
  1527. // Most distant & highest quality
  1528. // Most distant & lowest quality
  1529. // Second most distant & highest quality
  1530. // ...
  1531. for (unsigned i = 0; i < techniques.Size(); ++i)
  1532. {
  1533. const TechniqueEntry& entry = techniques[i];
  1534. Technique* technique = entry.technique_;
  1535. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1536. continue;
  1537. if (lodDistance >= entry.lodDistance_)
  1538. return technique;
  1539. }
  1540. // If no suitable technique found, fallback to the last
  1541. return techniques.Back().technique_;
  1542. }
  1543. void View::CheckMaterialForAuxView(Material* material)
  1544. {
  1545. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1546. for (unsigned i = 0; i < textures.Size(); ++i)
  1547. {
  1548. // Have to check cube & 2D textures separately
  1549. Texture* texture = textures[i];
  1550. if (texture)
  1551. {
  1552. if (texture->GetType() == Texture2D::GetTypeStatic())
  1553. {
  1554. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1555. RenderSurface* target = tex2D->GetRenderSurface();
  1556. if (target)
  1557. {
  1558. const Viewport& viewport = target->GetViewport();
  1559. if (viewport.scene_ && viewport.camera_)
  1560. renderer_->AddView(target, viewport);
  1561. }
  1562. }
  1563. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1564. {
  1565. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1566. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1567. {
  1568. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1569. if (target)
  1570. {
  1571. const Viewport& viewport = target->GetViewport();
  1572. if (viewport.scene_ && viewport.camera_)
  1573. renderer_->AddView(target, viewport);
  1574. }
  1575. }
  1576. }
  1577. }
  1578. }
  1579. // Set frame number so that we can early-out next time we come across this material on the same frame
  1580. material->MarkForAuxView(frame_.frameNumber_);
  1581. }
  1582. void View::SortBatches()
  1583. {
  1584. PROFILE(SortBatches);
  1585. if (mode_ != RENDER_FORWARD)
  1586. {
  1587. gBufferQueue_.SortFrontToBack();
  1588. noShadowLightQueue_.SortFrontToBack();
  1589. }
  1590. baseQueue_.SortFrontToBack();
  1591. extraQueue_.SortFrontToBack();
  1592. transparentQueue_.SortBackToFront();
  1593. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1594. {
  1595. lightQueues_[i].shadowBatches_.SortFrontToBack();
  1596. lightQueues_[i].litBatches_.SortFrontToBack();
  1597. }
  1598. }
  1599. void View::PrepareInstancingBuffer()
  1600. {
  1601. PROFILE(PrepareInstancingBuffer);
  1602. unsigned totalInstances = 0;
  1603. if (mode_ != RENDER_FORWARD)
  1604. totalInstances += gBufferQueue_.GetNumInstances();
  1605. totalInstances += baseQueue_.GetNumInstances();
  1606. totalInstances += extraQueue_.GetNumInstances();
  1607. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1608. {
  1609. totalInstances += lightQueues_[i].shadowBatches_.GetNumInstances();
  1610. totalInstances += lightQueues_[i].litBatches_.GetNumInstances();
  1611. }
  1612. // If fail to set buffer size, fall back to per-group locking
  1613. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1614. {
  1615. unsigned freeIndex = 0;
  1616. void* lockedData = renderer_->instancingBuffer_->Lock(0, totalInstances, LOCK_DISCARD);
  1617. if (lockedData)
  1618. {
  1619. if (mode_ != RENDER_FORWARD)
  1620. gBufferQueue_.SetTransforms(lockedData, freeIndex);
  1621. baseQueue_.SetTransforms(lockedData, freeIndex);
  1622. extraQueue_.SetTransforms(lockedData, freeIndex);
  1623. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1624. {
  1625. lightQueues_[i].shadowBatches_.SetTransforms(lockedData, freeIndex);
  1626. lightQueues_[i].litBatches_.SetTransforms(lockedData, freeIndex);
  1627. }
  1628. renderer_->instancingBuffer_->Unlock();
  1629. }
  1630. }
  1631. }
  1632. void View::CalculateShaderParameters()
  1633. {
  1634. Time* time = GetSubsystem<Time>();
  1635. float farClip = camera_->GetFarClip();
  1636. float nearClip = camera_->GetNearClip();
  1637. float fogStart = Min(zone_->GetFogStart(), farClip);
  1638. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  1639. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  1640. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  1641. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1642. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1643. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1644. shaderParameters_.Clear();
  1645. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1646. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1647. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1648. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1649. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1650. }
  1651. void View::DrawSplitLightToStencil(Camera& camera, Light* light, bool clear)
  1652. {
  1653. Matrix3x4 view(camera.GetInverseWorldTransform());
  1654. switch (light->GetLightType())
  1655. {
  1656. case LIGHT_SPLITPOINT:
  1657. if (!clear)
  1658. {
  1659. Matrix4 projection(camera.GetProjection());
  1660. const Matrix3x4& model = light->GetVolumeTransform(camera);
  1661. float lightExtent = light->GetVolumeExtent();
  1662. float lightViewDist = (light->GetWorldPosition() - camera.GetWorldPosition()).LengthFast();
  1663. bool drawBackFaces = lightViewDist < (lightExtent + camera.GetNearClip());
  1664. graphics_->SetAlphaTest(false);
  1665. graphics_->SetColorWrite(false);
  1666. graphics_->SetDepthWrite(false);
  1667. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1668. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATEREQUAL : CMP_LESSEQUAL);
  1669. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1670. graphics_->SetShaderParameter(VSP_MODEL, model);
  1671. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1672. graphics_->ClearTransformSources();
  1673. // Draw the faces to stencil which we should draw (where no light has not been rendered yet)
  1674. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1675. renderer_->spotLightGeometry_->Draw(graphics_);
  1676. // Draw the other faces to stencil to mark where we should not draw ("frees up" the pixels for other faces)
  1677. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1678. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_KEEP, OP_KEEP, 1);
  1679. renderer_->spotLightGeometry_->Draw(graphics_);
  1680. // Now set stencil test for rendering the lit geometries (also marks the pixels so that they will not be used again)
  1681. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1682. graphics_->SetColorWrite(true);
  1683. }
  1684. else
  1685. {
  1686. // Clear stencil with a scissored clear operation
  1687. OptimizeLightByScissor(light->GetOriginalLight());
  1688. graphics_->Clear(CLEAR_STENCIL);
  1689. graphics_->SetScissorTest(false);
  1690. graphics_->SetStencilTest(false);
  1691. }
  1692. break;
  1693. case LIGHT_DIRECTIONAL:
  1694. // If light encompasses whole frustum, no drawing to stencil necessary
  1695. if (light->GetNearSplit() <= camera.GetNearClip() && light->GetFarSplit() >= camera.GetFarClip())
  1696. {
  1697. graphics_->SetStencilTest(false);
  1698. return;
  1699. }
  1700. else
  1701. {
  1702. if (!clear)
  1703. {
  1704. // Get projection without jitter offset to ensure the whole screen is filled
  1705. Matrix4 projection(camera.GetProjection(false));
  1706. Matrix3x4 nearTransform(light->GetDirLightTransform(camera, true));
  1707. Matrix3x4 farTransform(light->GetDirLightTransform(camera, false));
  1708. graphics_->SetAlphaTest(false);
  1709. graphics_->SetColorWrite(false);
  1710. graphics_->SetDepthWrite(false);
  1711. graphics_->SetCullMode(CULL_NONE);
  1712. // If the split begins at the near plane (first split), draw at split far plane, otherwise at near plane
  1713. bool firstSplit = light->GetNearSplit() <= camera.GetNearClip();
  1714. graphics_->SetDepthTest(firstSplit ? CMP_GREATEREQUAL : CMP_LESSEQUAL);
  1715. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1716. graphics_->SetShaderParameter(VSP_MODEL, firstSplit ? farTransform : nearTransform);
  1717. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1718. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1719. graphics_->ClearTransformSources();
  1720. renderer_->dirLightGeometry_->Draw(graphics_);
  1721. graphics_->SetColorWrite(true);
  1722. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1723. }
  1724. else
  1725. {
  1726. // Clear the whole stencil
  1727. graphics_->SetScissorTest(false);
  1728. graphics_->Clear(CLEAR_STENCIL);
  1729. graphics_->SetStencilTest(false);
  1730. }
  1731. }
  1732. break;
  1733. }
  1734. }
  1735. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor, bool disableScissor)
  1736. {
  1737. VertexBuffer* instancingBuffer = 0;
  1738. if (renderer_->GetDynamicInstancing())
  1739. instancingBuffer = renderer_->instancingBuffer_;
  1740. if (disableScissor)
  1741. graphics_->SetScissorTest(false);
  1742. graphics_->SetStencilTest(false);
  1743. // Priority instanced
  1744. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1745. queue.priorityBatchGroups_.End(); ++i)
  1746. {
  1747. const BatchGroup& group = i->second_;
  1748. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1749. }
  1750. // Priority non-instanced
  1751. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1752. {
  1753. Batch* batch = *i;
  1754. batch->Draw(graphics_, shaderParameters_);
  1755. }
  1756. // Non-priority instanced
  1757. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1758. queue.batchGroups_.End(); ++i)
  1759. {
  1760. const BatchGroup& group = i->second_;
  1761. if (useScissor && group.light_)
  1762. OptimizeLightByScissor(group.light_);
  1763. else
  1764. graphics_->SetScissorTest(false);
  1765. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1766. }
  1767. // Non-priority non-instanced
  1768. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1769. {
  1770. Batch* batch = *i;
  1771. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1772. if (useScissor && batch->light_ && !batch->hasPriority_)
  1773. OptimizeLightByScissor(batch->light_);
  1774. else
  1775. graphics_->SetScissorTest(false);
  1776. batch->Draw(graphics_, shaderParameters_);
  1777. }
  1778. }
  1779. void View::RenderForwardLightBatchQueue(const BatchQueue& queue, Light* light)
  1780. {
  1781. VertexBuffer* instancingBuffer = 0;
  1782. if (renderer_->GetDynamicInstancing())
  1783. instancingBuffer = renderer_->instancingBuffer_;
  1784. graphics_->SetScissorTest(false);
  1785. graphics_->SetStencilTest(false);
  1786. // Priority instanced
  1787. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1788. queue.priorityBatchGroups_.End(); ++i)
  1789. {
  1790. const BatchGroup& group = i->second_;
  1791. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1792. }
  1793. // Priority non-instanced
  1794. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1795. {
  1796. Batch* batch = *i;
  1797. batch->Draw(graphics_, shaderParameters_);
  1798. }
  1799. // All base passes have been drawn. Optimize at this point by both scissor and stencil
  1800. if (light)
  1801. {
  1802. OptimizeLightByScissor(light);
  1803. LightType type = light->GetLightType();
  1804. if (type == LIGHT_SPLITPOINT || type == LIGHT_DIRECTIONAL)
  1805. DrawSplitLightToStencil(*camera_, light);
  1806. }
  1807. // Non-priority instanced
  1808. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1809. queue.batchGroups_.End(); ++i)
  1810. {
  1811. const BatchGroup& group = i->second_;
  1812. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1813. }
  1814. // Non-priority non-instanced
  1815. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1816. {
  1817. Batch* batch = *i;
  1818. batch->Draw(graphics_, shaderParameters_);
  1819. }
  1820. }
  1821. void View::RenderShadowMap(const LightBatchQueue& queue)
  1822. {
  1823. PROFILE(RenderShadowMap);
  1824. Texture2D* shadowMap = queue.light_->GetShadowMap();
  1825. graphics_->SetColorWrite(false);
  1826. graphics_->SetStencilTest(false);
  1827. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1828. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1829. graphics_->SetDepthStencil(shadowMap);
  1830. graphics_->Clear(CLEAR_DEPTH);
  1831. // Set shadow depth bias. Adjust according to the global shadow map resolution
  1832. BiasParameters parameters = queue.light_->GetShadowBias();
  1833. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1834. if (shadowMapSize <= 512)
  1835. parameters.constantBias_ *= 2.0f;
  1836. else if (shadowMapSize >= 2048)
  1837. parameters.constantBias_ *= 0.5f;
  1838. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1839. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1840. // However, do not do this for point lights
  1841. if (queue.light_->GetLightType() != LIGHT_SPLITPOINT)
  1842. {
  1843. float zoom = Min(queue.light_->GetShadowCamera()->GetZoom(),
  1844. (float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth());
  1845. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1846. graphics_->SetScissorTest(true, zoomRect, false);
  1847. }
  1848. else
  1849. graphics_->SetScissorTest(false);
  1850. // Draw instanced and non-instanced shadow casters
  1851. RenderBatchQueue(queue.shadowBatches_, false, false);
  1852. graphics_->SetColorWrite(true);
  1853. graphics_->SetDepthBias(0.0f, 0.0f);
  1854. }