View.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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 & VOF_LOW_MATERIAL_QUALITY)
  109. materialQuality_ = QUALITY_LOW;
  110. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  111. drawShadows_ = false;
  112. if (viewOverrideFlags & VOF_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. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  244. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  245. sceneBox_.defined_ = false;
  246. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  247. sceneViewBox_.defined_ = false;
  248. Matrix3x4 view(camera_->GetInverseWorldTransform());
  249. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  250. {
  251. Drawable* drawable = tempDrawables_[i];
  252. drawable->UpdateDistance(frame_);
  253. // If draw distance non-zero, check it
  254. float maxDistance = drawable->GetDrawDistance();
  255. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  256. continue;
  257. unsigned flags = drawable->GetDrawableFlags();
  258. if (flags & DRAWABLE_GEOMETRY)
  259. {
  260. drawable->ClearBasePass();
  261. drawable->MarkInView(frame_);
  262. drawable->UpdateGeometry(frame_);
  263. // Expand the scene bounding boxes. However, do not take "infinite" objects such as the skybox into account,
  264. // as the bounding boxes are also used for shadow focusing
  265. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  266. BoundingBox geomViewBox = geomBox.Transformed(view);
  267. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  268. {
  269. sceneBox_.Merge(geomBox);
  270. sceneViewBox_.Merge(geomViewBox);
  271. }
  272. // Store depth info for split directional light queries
  273. GeometryDepthBounds bounds;
  274. bounds.min_ = geomViewBox.min_.z_;
  275. bounds.max_ = geomViewBox.max_.z_;
  276. geometryDepthBounds_.Push(bounds);
  277. geometries_.Push(drawable);
  278. }
  279. else if (flags & DRAWABLE_LIGHT)
  280. {
  281. Light* light = static_cast<Light*>(drawable);
  282. // Skip if light is culled by the zone
  283. if (!(light->GetViewMask() & zone_->GetViewMask()))
  284. continue;
  285. light->MarkInView(frame_);
  286. lights_.Push(light);
  287. }
  288. }
  289. // Sort the lights to brightest/closest first
  290. for (unsigned i = 0; i < lights_.Size(); ++i)
  291. lights_[i]->SetIntensitySortValue(cameraPos);
  292. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  293. }
  294. void View::GetBatches()
  295. {
  296. maxLightsDrawables_.Clear();
  297. lightQueueIndex_.Clear();
  298. bool fallback = graphics_->GetFallback();
  299. // Go through lights
  300. {
  301. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  302. // Preallocate enough light queues so that we can store pointers to them without having to worry about the
  303. // vector reallocating itself
  304. lightQueues_.Resize(lights_.Size());
  305. unsigned lightQueueCount = 0;
  306. for (unsigned i = 0; i < lights_.Size(); ++i)
  307. {
  308. Light* light = lights_[i];
  309. unsigned shadowSplits = ProcessLight(light);
  310. if (litGeometries_.Empty())
  311. continue;
  312. // Initialize light queue. Store pointer-to-index mapping so that the queue can be found later
  313. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  314. lightQueueIndex_[light] = lightQueueCount;
  315. lightQueue.light_ = light;
  316. lightQueue.litBatches_.Clear();
  317. // Allocate shadow map now
  318. lightQueue.shadowMap_ = 0;
  319. if (shadowSplits > 0)
  320. {
  321. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, width_, height_);
  322. // If did not manage to get a shadow map, convert the light to unshadowed
  323. if (!lightQueue.shadowMap_)
  324. shadowSplits = 0;
  325. }
  326. // Setup shadow batch queues
  327. lightQueue.shadowSplits_.Resize(shadowSplits);
  328. for (unsigned j = 0; j < shadowSplits; ++j)
  329. {
  330. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  331. Camera* shadowCamera = shadowCameras_[j];
  332. shadowQueue.shadowCamera_ = shadowCameras_[j];
  333. shadowQueue.nearSplit_ = shadowNearSplits_[j];
  334. shadowQueue.farSplit_ = shadowFarSplits_[j];
  335. // Setup the shadow split viewport and finalize shadow camera parameters
  336. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  337. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, shadowCasterBox_[j]);
  338. // Loop through shadow casters
  339. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  340. {
  341. Drawable* drawable = shadowCasters_[j][k];
  342. unsigned numBatches = drawable->GetNumBatches();
  343. for (unsigned l = 0; l < numBatches; ++l)
  344. {
  345. Batch shadowBatch;
  346. drawable->GetBatch(frame_, l, shadowBatch);
  347. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  348. if (!shadowBatch.geometry_ || !tech)
  349. continue;
  350. Pass* pass = tech->GetPass(PASS_SHADOW);
  351. // Skip if material has no shadow pass
  352. if (!pass)
  353. continue;
  354. // Fill the rest of the batch
  355. shadowBatch.camera_ = shadowCamera;
  356. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  357. shadowBatch.lightQueue_ = &lightQueue;
  358. shadowBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  359. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  360. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  361. }
  362. }
  363. }
  364. // Loop through lit geometries
  365. for (unsigned j = 0; j < litGeometries_.Size(); ++j)
  366. {
  367. Drawable* drawable = litGeometries_[j];
  368. drawable->AddLight(light);
  369. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  370. if (!drawable->GetMaxLights())
  371. GetLitBatches(drawable, lightQueue);
  372. else
  373. maxLightsDrawables_.Insert(drawable);
  374. }
  375. ++lightQueueCount;
  376. }
  377. // Resize the light queue vector now that final size is known
  378. lightQueues_.Resize(lightQueueCount);
  379. }
  380. // Process drawables with limited light count
  381. if (maxLightsDrawables_.Size())
  382. {
  383. PROFILE(GetMaxLightsBatches);
  384. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  385. {
  386. Drawable* drawable = *i;
  387. drawable->LimitLights();
  388. const PODVector<Light*>& lights = drawable->GetLights();
  389. for (unsigned i = 0; i < lights.Size(); ++i)
  390. {
  391. Light* light = lights[i];
  392. // Find the correct light queue again
  393. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(light);
  394. if (j != lightQueueIndex_.End())
  395. GetLitBatches(drawable, lightQueues_[j->second_]);
  396. }
  397. }
  398. }
  399. // Go through geometries for base pass batches
  400. {
  401. PROFILE(GetBaseBatches);
  402. for (unsigned i = 0; i < geometries_.Size(); ++i)
  403. {
  404. Drawable* drawable = geometries_[i];
  405. unsigned numBatches = drawable->GetNumBatches();
  406. for (unsigned j = 0; j < numBatches; ++j)
  407. {
  408. Batch baseBatch;
  409. drawable->GetBatch(frame_, j, baseBatch);
  410. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  411. if (!baseBatch.geometry_ || !tech)
  412. continue;
  413. // Check here if the material technique refers to a render target texture with camera(s) attached
  414. // Only check this for the main view (null rendertarget)
  415. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  416. CheckMaterialForAuxView(baseBatch.material_);
  417. // If object already has a lit base pass, can skip the unlit base pass
  418. if (drawable->HasBasePass(j))
  419. continue;
  420. // Fill the rest of the batch
  421. baseBatch.camera_ = camera_;
  422. baseBatch.distance_ = drawable->GetDistance();
  423. Pass* pass = 0;
  424. // Check for unlit base pass
  425. pass = tech->GetPass(PASS_BASE);
  426. if (pass)
  427. {
  428. renderer_->SetBatchShaders(baseBatch, tech, pass);
  429. if (pass->GetBlendMode() == BLEND_REPLACE)
  430. {
  431. baseBatch.hasPriority_ = !pass->GetAlphaTest() && !pass->GetAlphaMask();
  432. baseQueue_.AddBatch(baseBatch);
  433. }
  434. else
  435. {
  436. baseBatch.hasPriority_ = true;
  437. transparentQueue_.AddBatch(baseBatch, true);
  438. }
  439. continue;
  440. }
  441. else
  442. {
  443. // If no base pass, finally check for extra / custom pass
  444. pass = tech->GetPass(PASS_EXTRA);
  445. if (pass)
  446. {
  447. baseBatch.hasPriority_ = false;
  448. renderer_->SetBatchShaders(baseBatch, tech, pass);
  449. extraQueue_.AddBatch(baseBatch);
  450. }
  451. }
  452. }
  453. }
  454. }
  455. // All batches have been collected. Sort them now
  456. SortBatches();
  457. }
  458. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  459. {
  460. Light* light = lightQueue.light_;
  461. // Shadows on transparencies can only be rendered if shadow maps are not reused
  462. bool allowTransparentShadows = !renderer_->reuseShadowMaps_;
  463. unsigned numBatches = drawable->GetNumBatches();
  464. for (unsigned i = 0; i < numBatches; ++i)
  465. {
  466. Batch litBatch;
  467. drawable->GetBatch(frame_, i, litBatch);
  468. Technique* tech = GetTechnique(drawable, litBatch.material_);
  469. if (!litBatch.geometry_ || !tech)
  470. continue;
  471. Pass* pass = 0;
  472. bool priority = false;
  473. // For the (first) directional light, check for lit base pass
  474. if (light == lights_[0] && light->GetLightType() == LIGHT_DIRECTIONAL)
  475. {
  476. if (!drawable->HasBasePass(i))
  477. {
  478. pass = tech->GetPass(PASS_LITBASE);
  479. if (pass)
  480. {
  481. priority = true;
  482. drawable->SetBasePass(i);
  483. }
  484. }
  485. }
  486. // If no lit base pass, get ordinary light pass
  487. if (!pass)
  488. pass = tech->GetPass(PASS_LIGHT);
  489. // Skip if material does not receive light at all
  490. if (!pass)
  491. continue;
  492. // Fill the rest of the batch
  493. litBatch.camera_ = camera_;
  494. litBatch.distance_ = drawable->GetDistance();
  495. litBatch.lightQueue_ = &lightQueue;
  496. litBatch.hasPriority_ = priority;
  497. // Check from the ambient pass whether the object is opaque or transparent
  498. Pass* ambientPass = tech->GetPass(PASS_BASE);
  499. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  500. {
  501. renderer_->SetBatchShaders(litBatch, tech, pass);
  502. lightQueue.litBatches_.AddBatch(litBatch);
  503. }
  504. else
  505. {
  506. renderer_->SetBatchShaders(litBatch, tech, pass, allowTransparentShadows);
  507. transparentQueue_.AddBatch(litBatch, true);
  508. }
  509. }
  510. }
  511. void View::RenderBatches()
  512. {
  513. // If not reusing shadowmaps, render all of them first
  514. if (!renderer_->reuseShadowMaps_)
  515. {
  516. PROFILE(RenderShadowMaps);
  517. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  518. {
  519. LightBatchQueue& queue = lightQueues_[i];
  520. if (queue.shadowMap_)
  521. RenderShadowMap(queue);
  522. }
  523. }
  524. {
  525. // Render opaque objects' base passes
  526. PROFILE(RenderBasePass);
  527. graphics_->SetRenderTarget(0, renderTarget_);
  528. graphics_->SetDepthStencil(depthStencil_);
  529. graphics_->SetViewport(screenRect_);
  530. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  531. RenderBatchQueue(baseQueue_);
  532. }
  533. {
  534. // Render shadow maps + opaque objects' shadowed additive lighting
  535. PROFILE(RenderLights);
  536. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  537. {
  538. LightBatchQueue& queue = lightQueues_[i];
  539. // If reusing shadowmaps, render each of them before the lit batches
  540. if (renderer_->reuseShadowMaps_ && queue.shadowMap_)
  541. RenderShadowMap(queue);
  542. graphics_->SetRenderTarget(0, renderTarget_);
  543. graphics_->SetDepthStencil(depthStencil_);
  544. graphics_->SetViewport(screenRect_);
  545. RenderLightBatchQueue(queue.litBatches_, queue.light_);
  546. }
  547. }
  548. graphics_->SetScissorTest(false);
  549. graphics_->SetStencilTest(false);
  550. graphics_->SetRenderTarget(0, renderTarget_);
  551. graphics_->SetDepthStencil(depthStencil_);
  552. graphics_->SetViewport(screenRect_);
  553. if (!extraQueue_.IsEmpty())
  554. {
  555. // Render extra / custom passes
  556. PROFILE(RenderExtraPass);
  557. RenderBatchQueue(extraQueue_);
  558. }
  559. if (!transparentQueue_.IsEmpty())
  560. {
  561. // Render transparent objects last (both base passes & additive lighting)
  562. PROFILE(RenderTransparent);
  563. RenderBatchQueue(transparentQueue_, true);
  564. }
  565. }
  566. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  567. {
  568. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  569. float halfViewSize = camera->GetHalfViewSize();
  570. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  571. Vector3 cameraPos = camera->GetWorldPosition();
  572. for (unsigned i = 0; i < occluders.Size(); ++i)
  573. {
  574. Drawable* occluder = occluders[i];
  575. occluder->UpdateDistance(frame_);
  576. bool erase = false;
  577. // Check occluder's draw distance (in main camera view)
  578. float maxDistance = occluder->GetDrawDistance();
  579. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  580. erase = true;
  581. // Check that occluder is big enough on the screen
  582. const BoundingBox& box = occluder->GetWorldBoundingBox();
  583. float diagonal = (box.max_ - box.min_).LengthFast();
  584. float compare;
  585. if (!camera->IsOrthographic())
  586. compare = diagonal * halfViewSize / occluder->GetDistance();
  587. else
  588. compare = diagonal * invOrthoSize;
  589. if (compare < occluderSizeThreshold_)
  590. erase = true;
  591. if (!erase)
  592. {
  593. unsigned totalTriangles = 0;
  594. unsigned batches = occluder->GetNumBatches();
  595. Batch tempBatch;
  596. for (unsigned j = 0; j < batches; ++j)
  597. {
  598. occluder->GetBatch(frame_, j, tempBatch);
  599. if (tempBatch.geometry_)
  600. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  601. }
  602. // Store amount of triangles divided by screen size as a sorting key
  603. // (best occluders are big and have few triangles)
  604. occluder->SetSortValue((float)totalTriangles / compare);
  605. }
  606. else
  607. {
  608. occluders.Erase(occluders.Begin() + i);
  609. --i;
  610. }
  611. }
  612. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  613. if (occluders.Size())
  614. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  615. }
  616. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  617. {
  618. for (unsigned i = 0; i < occluders.Size(); ++i)
  619. {
  620. Drawable* occluder = occluders[i];
  621. if (i > 0)
  622. {
  623. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  624. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  625. continue;
  626. }
  627. occluder->UpdateGeometry(frame_);
  628. // Check for running out of triangles
  629. if (!occluder->DrawOcclusion(buffer))
  630. return;
  631. }
  632. }
  633. unsigned View::ProcessLight(Light* light)
  634. {
  635. // Check if light should be shadowed
  636. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  637. unsigned shadowSplits = 0;
  638. // If shadow distance non-zero, check it
  639. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  640. isShadowed = false;
  641. LightType type = light->GetLightType();
  642. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  643. litGeometries_.Clear();
  644. switch (type)
  645. {
  646. case LIGHT_DIRECTIONAL:
  647. for (unsigned i = 0; i < geometries_.Size(); ++i)
  648. {
  649. if (geometries_[i]->GetLightMask() & light->GetLightMask())
  650. litGeometries_.Push(geometries_[i]);
  651. }
  652. break;
  653. case LIGHT_SPOT:
  654. {
  655. FrustumOctreeQuery query(tempDrawables_, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  656. octree_->GetDrawables(query);
  657. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  658. {
  659. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  660. litGeometries_.Push(tempDrawables_[i]);
  661. }
  662. }
  663. break;
  664. case LIGHT_POINT:
  665. {
  666. SphereOctreeQuery query(tempDrawables_, Sphere(light->GetWorldPosition(), light->GetRange()), DRAWABLE_GEOMETRY,
  667. camera_->GetViewMask());
  668. octree_->GetDrawables(query);
  669. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  670. {
  671. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  672. litGeometries_.Push(tempDrawables_[i]);
  673. }
  674. }
  675. break;
  676. }
  677. // If no lit geometries or not shadowed, no need to process shadow cameras
  678. if (litGeometries_.Empty() || !isShadowed)
  679. return 0;
  680. // Determine number of shadow cameras and setup their initial positions
  681. shadowSplits = SetupShadowCameras(light);
  682. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  683. bool useOcclusion = false;
  684. OcclusionBuffer* buffer = 0;
  685. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  686. {
  687. // This shadow camera is never used for actually querying shadow casters, just occluders
  688. Camera* shadowCamera = renderer_->CreateShadowCamera();
  689. SetupDirLightShadowCamera(shadowCamera, light, 0.0f, Min(light->GetShadowCascade().GetShadowRange(), camera_->GetFarClip()),
  690. true);
  691. // Get occluders, which must be shadow-casting themselves
  692. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  693. true, true);
  694. octree_->GetDrawables(query);
  695. UpdateOccluders(shadowOccluders_, shadowCamera);
  696. if (shadowOccluders_.Size())
  697. {
  698. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  699. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  700. DrawOccluders(buffer, shadowOccluders_);
  701. buffer->BuildDepthHierarchy();
  702. useOcclusion = true;
  703. }
  704. }
  705. // Process each split for shadow casters
  706. bool hasShadowCasters = false;
  707. for (unsigned i = 0; i < shadowSplits; ++i)
  708. {
  709. shadowCasters_[i].Clear();
  710. shadowCasterBox_[i].defined_ = false;
  711. Camera* shadowCamera = shadowCameras_[i];
  712. if (!useOcclusion)
  713. {
  714. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  715. // lit geometries, whose result still exists in tempDrawables_
  716. if (type != LIGHT_SPOT)
  717. {
  718. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  719. // If a point light face, check that the face is visible: if not, there is no need to query and render
  720. // the shadow casters
  721. if (type == LIGHT_POINT)
  722. {
  723. BoundingBox shadowCameraBox(shadowCameraFrustum);
  724. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  725. continue;
  726. }
  727. FrustumOctreeQuery query(tempDrawables_, shadowCameraFrustum, DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  728. false, true);
  729. octree_->GetDrawables(query);
  730. }
  731. }
  732. else
  733. {
  734. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  735. DRAWABLE_GEOMETRY, camera_->GetViewMask(), false, true);
  736. octree_->GetDrawables(query);
  737. }
  738. // Check which shadow casters actually contribute to the shadowing
  739. ProcessShadowCasters(light, i, tempDrawables_, shadowCasterBox_[i]);
  740. if (shadowCasters_[i].Size())
  741. hasShadowCasters = true;
  742. }
  743. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map
  744. // yet, so the only cost is the shadow camera setup & queries
  745. if (!hasShadowCasters)
  746. shadowSplits = 0;
  747. return shadowSplits;
  748. }
  749. void View::ProcessShadowCasters(Light* light, unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& shadowCasterBox)
  750. {
  751. Matrix3x4 lightView;
  752. Matrix4 lightProj;
  753. Camera* shadowCamera = shadowCameras_[splitIndex];
  754. lightView = shadowCamera->GetInverseWorldTransform();
  755. lightProj = shadowCamera->GetProjection();
  756. bool dirLight = shadowCamera->IsOrthographic();
  757. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  758. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  759. // frustum, so that shadow casters do not get rendered into unnecessary splits
  760. Frustum lightViewFrustum;
  761. if (!dirLight)
  762. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  763. else
  764. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, shadowNearSplits_[splitIndex]),
  765. Min(sceneViewBox_.max_.z_, shadowFarSplits_[splitIndex])).Transformed(lightView);
  766. BoundingBox lightViewFrustumBox(lightViewFrustum);
  767. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  768. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  769. return;
  770. BoundingBox lightViewBox;
  771. BoundingBox lightProjBox;
  772. for (unsigned i = 0; i < result.Size(); ++i)
  773. {
  774. Drawable* drawable = static_cast<Drawable*>(result[i]);
  775. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  776. // Check for that first
  777. if (!drawable->GetCastShadows())
  778. continue;
  779. drawable->UpdateDistance(frame_);
  780. // Check shadow distance
  781. float maxShadowDistance = drawable->GetShadowDistance();
  782. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  783. continue;
  784. // Check light mask
  785. if (!(drawable->GetLightMask() & light->GetLightMask()))
  786. continue;
  787. // Project shadow caster bounding box to light view space for visibility check
  788. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  789. if (drawable->IsInView(frame_) || IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum,
  790. lightViewFrustumBox))
  791. {
  792. // Update geometry now if not updated yet
  793. if (!drawable->IsInView(frame_))
  794. {
  795. drawable->MarkInShadowView(frame_);
  796. drawable->UpdateGeometry(frame_);
  797. }
  798. // Merge to shadow caster bounding box and add to the list
  799. if (dirLight)
  800. shadowCasterBox.Merge(lightViewBox);
  801. else
  802. {
  803. lightProjBox = lightViewBox.Projected(lightProj);
  804. shadowCasterBox.Merge(lightProjBox);
  805. }
  806. shadowCasters_[splitIndex].Push(drawable);
  807. }
  808. }
  809. }
  810. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  811. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  812. {
  813. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  814. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  815. if (drawable->IsOccluder())
  816. return true;
  817. if (shadowCamera->IsOrthographic())
  818. {
  819. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  820. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  821. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  822. }
  823. else
  824. {
  825. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  826. if (drawable->IsInView(frame_))
  827. return true;
  828. // For perspective lights, extrusion direction depends on the position of the shadow caster
  829. Vector3 center = lightViewBox.Center();
  830. Ray extrusionRay(center, center.Normalized());
  831. float extrusionDistance = shadowCamera->GetFarClip();
  832. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  833. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  834. float sizeFactor = extrusionDistance / originalDistance;
  835. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  836. // than necessary, so the test will be conservative
  837. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  838. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  839. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  840. lightViewBox.Merge(extrudedBox);
  841. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  842. }
  843. }
  844. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  845. {
  846. unsigned width = shadowMap->GetWidth();
  847. unsigned height = shadowMap->GetHeight();
  848. int maxCascades = renderer_->GetMaxShadowCascades();
  849. switch (light->GetLightType())
  850. {
  851. case LIGHT_DIRECTIONAL:
  852. if (maxCascades == 1)
  853. return IntRect(0, 0, width, height);
  854. else if (maxCascades == 2)
  855. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  856. else
  857. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  858. (splitIndex / 2 + 1) * height / 2);
  859. case LIGHT_SPOT:
  860. return IntRect(0, 0, width, height);
  861. case LIGHT_POINT:
  862. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  863. (splitIndex / 2 + 1) * height / 3);
  864. }
  865. return IntRect();
  866. }
  867. void View::OptimizeLightByScissor(Light* light)
  868. {
  869. if (light)
  870. graphics_->SetScissorTest(true, GetLightScissor(light));
  871. else
  872. graphics_->SetScissorTest(false);
  873. }
  874. void View::OptimizeLightByStencil(Light* light)
  875. {
  876. if (light && renderer_->GetLightStencilMasking())
  877. {
  878. Geometry* geometry = renderer_->GetLightGeometry(light);
  879. if (geometry)
  880. {
  881. LightType type = light->GetLightType();
  882. // If the stencil value has wrapped, clear the whole stencil first
  883. if (!lightStencilValue_)
  884. {
  885. graphics_->Clear(CLEAR_STENCIL);
  886. lightStencilValue_ = 1;
  887. }
  888. Matrix3x4 view(camera_->GetInverseWorldTransform());
  889. Matrix4 projection(camera_->GetProjection());
  890. float lightDist;
  891. if (type == LIGHT_POINT)
  892. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  893. else
  894. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  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_->stencilVS_, renderer_->stencilPS_);
  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. ++lightStencilValue_;
  918. return;
  919. }
  920. }
  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 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1280. Vector4 depthMode = Vector4::ZERO;
  1281. if (camera_->IsOrthographic())
  1282. {
  1283. depthMode.x_ = 1.0f;
  1284. #ifdef USE_OPENGL
  1285. depthMode.z_ = 0.5f;
  1286. depthMode.w_ = 0.5f;
  1287. #else
  1288. depthMode.z_ = 1.0f;
  1289. #endif
  1290. }
  1291. else
  1292. depthMode.w_ = 1.0f / camera_->GetFarClip();
  1293. shaderParameters_.Clear();
  1294. shaderParameters_[VSP_DEPTHMODE] = depthMode;
  1295. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1296. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1297. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1298. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1299. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1300. }
  1301. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1302. {
  1303. if (useScissor)
  1304. graphics_->SetScissorTest(false);
  1305. graphics_->SetStencilTest(false);
  1306. // Priority instanced
  1307. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1308. queue.sortedPriorityBatchGroups_.End(); ++i)
  1309. {
  1310. BatchGroup* group = *i;
  1311. group->Draw(graphics_, renderer_, shaderParameters_);
  1312. }
  1313. // Priority non-instanced
  1314. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1315. {
  1316. Batch* batch = *i;
  1317. batch->Draw(graphics_, renderer_, shaderParameters_);
  1318. }
  1319. // Non-priority instanced
  1320. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1321. {
  1322. BatchGroup* group = *i;
  1323. if (useScissor && group->lightQueue_)
  1324. OptimizeLightByScissor(group->lightQueue_->light_);
  1325. group->Draw(graphics_, renderer_, shaderParameters_);
  1326. }
  1327. // Non-priority non-instanced
  1328. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1329. {
  1330. Batch* batch = *i;
  1331. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1332. if (useScissor)
  1333. {
  1334. if (!batch->hasPriority_ && batch->lightQueue_)
  1335. OptimizeLightByScissor(batch->lightQueue_->light_);
  1336. else
  1337. graphics_->SetScissorTest(false);
  1338. }
  1339. batch->Draw(graphics_, renderer_, shaderParameters_);
  1340. }
  1341. }
  1342. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1343. {
  1344. graphics_->SetScissorTest(false);
  1345. graphics_->SetStencilTest(false);
  1346. // Priority instanced
  1347. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1348. queue.sortedPriorityBatchGroups_.End(); ++i)
  1349. {
  1350. BatchGroup* group = *i;
  1351. group->Draw(graphics_, renderer_, shaderParameters_);
  1352. }
  1353. // Priority non-instanced
  1354. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1355. {
  1356. Batch* batch = *i;
  1357. batch->Draw(graphics_, renderer_, shaderParameters_);
  1358. }
  1359. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1360. OptimizeLightByStencil(light);
  1361. OptimizeLightByScissor(light);
  1362. // Non-priority instanced
  1363. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1364. {
  1365. BatchGroup* group = *i;
  1366. group->Draw(graphics_, renderer_, shaderParameters_);
  1367. }
  1368. // Non-priority non-instanced
  1369. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1370. {
  1371. Batch* batch = *i;
  1372. batch->Draw(graphics_, renderer_, shaderParameters_);
  1373. }
  1374. }
  1375. void View::RenderShadowMap(const LightBatchQueue& queue)
  1376. {
  1377. PROFILE(RenderShadowMap);
  1378. Texture2D* shadowMap = queue.shadowMap_;
  1379. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1380. if (!graphics_->GetFallback())
  1381. {
  1382. graphics_->SetColorWrite(false);
  1383. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1384. graphics_->SetDepthStencil(shadowMap);
  1385. graphics_->Clear(CLEAR_DEPTH);
  1386. }
  1387. else
  1388. {
  1389. graphics_->SetColorWrite(true);
  1390. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1391. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1392. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1393. }
  1394. // Set shadow depth bias
  1395. BiasParameters parameters = queue.light_->GetShadowBias();
  1396. // Adjust the light's constant depth bias according to global shadow map resolution
  1397. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1398. if (shadowMapSize <= 512)
  1399. parameters.constantBias_ *= 2.0f;
  1400. else if (shadowMapSize >= 2048)
  1401. parameters.constantBias_ *= 0.5f;
  1402. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1403. // Render each of the splits
  1404. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1405. {
  1406. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1407. if (!shadowQueue.shadowBatches_.IsEmpty())
  1408. {
  1409. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1410. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1411. // However, do not do this for point lights, which need to render continuously across cube faces
  1412. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1413. if (queue.light_->GetLightType() != LIGHT_POINT)
  1414. {
  1415. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1416. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1417. graphics_->SetScissorTest(true, zoomRect, false);
  1418. }
  1419. else
  1420. graphics_->SetScissorTest(false);
  1421. // Draw instanced and non-instanced shadow casters
  1422. RenderBatchQueue(shadowQueue.shadowBatches_);
  1423. }
  1424. }
  1425. graphics_->SetColorWrite(true);
  1426. graphics_->SetDepthBias(0.0f, 0.0f);
  1427. graphics_->SetScissorTest(false);
  1428. }