View.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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->ClearLights();
  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. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  359. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  360. }
  361. }
  362. }
  363. // Loop through lit geometries
  364. for (unsigned j = 0; j < litGeometries_.Size(); ++j)
  365. {
  366. Drawable* drawable = litGeometries_[j];
  367. // In the occluded & shadowed directional light optimization, we null out pointers instead of removing entries
  368. // from the lit geometry vector. Therefore must be prepared for a null pointer
  369. if (!drawable)
  370. continue;
  371. drawable->AddLight(light);
  372. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  373. if (!drawable->GetMaxLights())
  374. GetLitBatches(drawable, lightQueue);
  375. else
  376. maxLightsDrawables_.Insert(drawable);
  377. }
  378. ++lightQueueCount;
  379. }
  380. // Resize the light queue vector now that final size is known
  381. lightQueues_.Resize(lightQueueCount);
  382. }
  383. // Process drawables with limited light count
  384. if (maxLightsDrawables_.Size())
  385. {
  386. PROFILE(GetMaxLightsBatches);
  387. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  388. {
  389. Drawable* drawable = *i;
  390. drawable->LimitLights();
  391. const PODVector<Light*>& lights = drawable->GetLights();
  392. for (unsigned i = 0; i < lights.Size(); ++i)
  393. {
  394. Light* light = lights[i];
  395. // Find the correct light queue again
  396. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(light);
  397. if (j != lightQueueIndex_.End())
  398. GetLitBatches(drawable, lightQueues_[j->second_]);
  399. }
  400. }
  401. }
  402. // Go through geometries for base pass batches
  403. {
  404. PROFILE(GetBaseBatches);
  405. for (unsigned i = 0; i < geometries_.Size(); ++i)
  406. {
  407. Drawable* drawable = geometries_[i];
  408. unsigned numBatches = drawable->GetNumBatches();
  409. for (unsigned j = 0; j < numBatches; ++j)
  410. {
  411. Batch baseBatch;
  412. drawable->GetBatch(frame_, j, baseBatch);
  413. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  414. if (!baseBatch.geometry_ || !tech)
  415. continue;
  416. // Check here if the material technique refers to a render target texture with camera(s) attached
  417. // Only check this for the main view (null rendertarget)
  418. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  419. CheckMaterialForAuxView(baseBatch.material_);
  420. // If object already has a lit base pass, can skip the unlit base pass
  421. if (drawable->HasBasePass(j))
  422. continue;
  423. // Fill the rest of the batch
  424. baseBatch.camera_ = camera_;
  425. baseBatch.distance_ = drawable->GetDistance();
  426. baseBatch.hasPriority_ = true;
  427. Pass* pass = 0;
  428. // Check for unlit base pass
  429. pass = tech->GetPass(PASS_BASE);
  430. if (pass)
  431. {
  432. renderer_->SetBatchShaders(baseBatch, tech, pass);
  433. if (pass->GetBlendMode() == BLEND_REPLACE)
  434. baseQueue_.AddBatch(baseBatch);
  435. else
  436. transparentQueue_.AddBatch(baseBatch, true);
  437. continue;
  438. }
  439. else
  440. {
  441. // If no base pass, finally check for extra / custom pass
  442. pass = tech->GetPass(PASS_EXTRA);
  443. if (pass)
  444. {
  445. renderer_->SetBatchShaders(baseBatch, tech, pass);
  446. extraQueue_.AddBatch(baseBatch);
  447. }
  448. }
  449. }
  450. }
  451. }
  452. // All batches have been collected. Sort them now
  453. SortBatches();
  454. }
  455. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  456. {
  457. Light* light = lightQueue.light_;
  458. Light* firstLight = drawable->GetFirstLight();
  459. // Shadows on transparencies can only be rendered if shadow maps are not reused
  460. bool allowTransparentShadows = !renderer_->reuseShadowMaps_;
  461. unsigned numBatches = drawable->GetNumBatches();
  462. for (unsigned i = 0; i < numBatches; ++i)
  463. {
  464. Batch litBatch;
  465. drawable->GetBatch(frame_, i, litBatch);
  466. Technique* tech = GetTechnique(drawable, litBatch.material_);
  467. if (!litBatch.geometry_ || !tech)
  468. continue;
  469. Pass* pass = 0;
  470. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  471. if (light == firstLight && !drawable->HasBasePass(i))
  472. {
  473. pass = tech->GetPass(PASS_LITBASE);
  474. if (pass)
  475. {
  476. litBatch.hasPriority_ = true;
  477. drawable->SetBasePass(i);
  478. }
  479. }
  480. // If no lit base pass, get ordinary light pass
  481. if (!pass)
  482. pass = tech->GetPass(PASS_LIGHT);
  483. // Skip if material does not receive light at all
  484. if (!pass)
  485. continue;
  486. // Fill the rest of the batch
  487. litBatch.camera_ = camera_;
  488. litBatch.distance_ = drawable->GetDistance();
  489. litBatch.lightQueue_ = &lightQueue;
  490. // Check from the ambient pass whether the object is opaque or transparent
  491. Pass* ambientPass = tech->GetPass(PASS_BASE);
  492. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  493. {
  494. renderer_->SetBatchShaders(litBatch, tech, pass);
  495. lightQueue.litBatches_.AddBatch(litBatch);
  496. }
  497. else
  498. {
  499. renderer_->SetBatchShaders(litBatch, tech, pass, allowTransparentShadows);
  500. transparentQueue_.AddBatch(litBatch, true);
  501. }
  502. }
  503. }
  504. void View::RenderBatches()
  505. {
  506. // If not reusing shadowmaps, render all of them first
  507. if (!renderer_->reuseShadowMaps_)
  508. {
  509. PROFILE(RenderShadowMaps);
  510. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  511. {
  512. LightBatchQueue& queue = lightQueues_[i];
  513. if (queue.shadowMap_)
  514. RenderShadowMap(queue);
  515. }
  516. }
  517. {
  518. // Render opaque objects' base passes
  519. PROFILE(RenderBasePass);
  520. graphics_->SetRenderTarget(0, renderTarget_);
  521. graphics_->SetDepthStencil(depthStencil_);
  522. graphics_->SetViewport(screenRect_);
  523. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  524. RenderBatchQueue(baseQueue_);
  525. }
  526. {
  527. // Render shadow maps + opaque objects' shadowed additive lighting
  528. PROFILE(RenderLights);
  529. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  530. {
  531. LightBatchQueue& queue = lightQueues_[i];
  532. // If reusing shadowmaps, render each of them before the lit batches
  533. if (renderer_->reuseShadowMaps_ && queue.shadowMap_)
  534. RenderShadowMap(queue);
  535. graphics_->SetRenderTarget(0, renderTarget_);
  536. graphics_->SetDepthStencil(depthStencil_);
  537. graphics_->SetViewport(screenRect_);
  538. RenderLightBatchQueue(queue.litBatches_, queue.light_);
  539. }
  540. }
  541. graphics_->SetScissorTest(false);
  542. graphics_->SetStencilTest(false);
  543. graphics_->SetRenderTarget(0, renderTarget_);
  544. graphics_->SetDepthStencil(depthStencil_);
  545. graphics_->SetViewport(screenRect_);
  546. if (!extraQueue_.IsEmpty())
  547. {
  548. // Render extra / custom passes
  549. PROFILE(RenderExtraPass);
  550. RenderBatchQueue(extraQueue_);
  551. }
  552. if (!transparentQueue_.IsEmpty())
  553. {
  554. // Render transparent objects last (both base passes & additive lighting)
  555. PROFILE(RenderTransparent);
  556. RenderBatchQueue(transparentQueue_, true);
  557. }
  558. }
  559. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  560. {
  561. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  562. float halfViewSize = camera->GetHalfViewSize();
  563. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  564. Vector3 cameraPos = camera->GetWorldPosition();
  565. for (unsigned i = 0; i < occluders.Size(); ++i)
  566. {
  567. Drawable* occluder = occluders[i];
  568. occluder->UpdateDistance(frame_);
  569. bool erase = false;
  570. // Check occluder's draw distance (in main camera view)
  571. float maxDistance = occluder->GetDrawDistance();
  572. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  573. erase = true;
  574. // Check that occluder is big enough on the screen
  575. const BoundingBox& box = occluder->GetWorldBoundingBox();
  576. float diagonal = (box.max_ - box.min_).LengthFast();
  577. float compare;
  578. if (!camera->IsOrthographic())
  579. compare = diagonal * halfViewSize / occluder->GetDistance();
  580. else
  581. compare = diagonal * invOrthoSize;
  582. if (compare < occluderSizeThreshold_)
  583. erase = true;
  584. if (!erase)
  585. {
  586. unsigned totalTriangles = 0;
  587. unsigned batches = occluder->GetNumBatches();
  588. Batch tempBatch;
  589. for (unsigned j = 0; j < batches; ++j)
  590. {
  591. occluder->GetBatch(frame_, j, tempBatch);
  592. if (tempBatch.geometry_)
  593. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  594. }
  595. // Store amount of triangles divided by screen size as a sorting key
  596. // (best occluders are big and have few triangles)
  597. occluder->SetSortValue((float)totalTriangles / compare);
  598. }
  599. else
  600. {
  601. occluders.Erase(occluders.Begin() + i);
  602. --i;
  603. }
  604. }
  605. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  606. if (occluders.Size())
  607. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  608. }
  609. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  610. {
  611. for (unsigned i = 0; i < occluders.Size(); ++i)
  612. {
  613. Drawable* occluder = occluders[i];
  614. if (i > 0)
  615. {
  616. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  617. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  618. continue;
  619. }
  620. occluder->UpdateGeometry(frame_);
  621. // Check for running out of triangles
  622. if (!occluder->DrawOcclusion(buffer))
  623. return;
  624. }
  625. }
  626. unsigned View::ProcessLight(Light* light)
  627. {
  628. // Check if light should be shadowed
  629. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  630. unsigned shadowSplits = 0;
  631. // If shadow distance non-zero, check it
  632. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  633. isShadowed = false;
  634. LightType type = light->GetLightType();
  635. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  636. litGeometries_.Clear();
  637. switch (type)
  638. {
  639. case LIGHT_DIRECTIONAL:
  640. dirLightShadowCasters_.Clear();
  641. for (unsigned i = 0; i < geometries_.Size(); ++i)
  642. {
  643. if (geometries_[i]->GetLightMask() & light->GetLightMask())
  644. litGeometries_.Push(geometries_[i]);
  645. }
  646. break;
  647. case LIGHT_SPOT:
  648. {
  649. FrustumOctreeQuery query(tempDrawables_, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  650. octree_->GetDrawables(query);
  651. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  652. {
  653. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  654. litGeometries_.Push(tempDrawables_[i]);
  655. }
  656. }
  657. break;
  658. case LIGHT_POINT:
  659. {
  660. SphereOctreeQuery query(tempDrawables_, Sphere(light->GetWorldPosition(), light->GetRange()), DRAWABLE_GEOMETRY,
  661. camera_->GetViewMask());
  662. octree_->GetDrawables(query);
  663. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  664. {
  665. if (tempDrawables_[i]->IsInView(frame_) && (tempDrawables_[i]->GetLightMask() & light->GetLightMask()))
  666. litGeometries_.Push(tempDrawables_[i]);
  667. }
  668. }
  669. break;
  670. }
  671. // If no lit geometries or not shadowed, no need to process shadow cameras
  672. if (litGeometries_.Empty() || !isShadowed)
  673. return 0;
  674. // Determine number of shadow cameras and setup their initial positions
  675. shadowSplits = SetupShadowCameras(light);
  676. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  677. bool useOcclusion = false;
  678. OcclusionBuffer* buffer = 0;
  679. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  680. {
  681. // This shadow camera is never used for actually querying shadow casters, just occluders
  682. Camera* shadowCamera = renderer_->CreateShadowCamera();
  683. SetupDirLightShadowCamera(shadowCamera, light, 0.0f, Min(light->GetShadowCascade().GetShadowRange(), camera_->GetFarClip()),
  684. true);
  685. // Get occluders, which must be shadow-casting themselves
  686. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  687. true, true);
  688. octree_->GetDrawables(query);
  689. UpdateOccluders(shadowOccluders_, shadowCamera);
  690. if (shadowOccluders_.Size())
  691. {
  692. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  693. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  694. DrawOccluders(buffer, shadowOccluders_);
  695. buffer->BuildDepthHierarchy();
  696. useOcclusion = true;
  697. }
  698. }
  699. // Process each split for shadow casters
  700. bool hasShadowCasters = false;
  701. for (unsigned i = 0; i < shadowSplits; ++i)
  702. {
  703. shadowCasters_[i].Clear();
  704. shadowCasterBox_[i].defined_ = false;
  705. Camera* shadowCamera = shadowCameras_[i];
  706. if (!useOcclusion)
  707. {
  708. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  709. // lit geometries, whose result still exists in tempDrawables_
  710. if (type != LIGHT_SPOT)
  711. {
  712. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  713. // If a point light face, check that the face is visible: if not, there is no need to query and render
  714. // the shadow casters
  715. if (type == LIGHT_POINT)
  716. {
  717. BoundingBox shadowCameraBox(shadowCameraFrustum);
  718. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  719. continue;
  720. }
  721. FrustumOctreeQuery query(tempDrawables_, shadowCameraFrustum, DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  722. false, true);
  723. octree_->GetDrawables(query);
  724. }
  725. }
  726. else
  727. {
  728. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  729. DRAWABLE_GEOMETRY, camera_->GetViewMask(), false, true);
  730. octree_->GetDrawables(query);
  731. // Store the raw list of possible shadow casters for a later optimization step
  732. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  733. dirLightShadowCasters_.Insert(tempDrawables_[i]);
  734. }
  735. // Check which shadow casters actually contribute to the shadowing
  736. ProcessShadowCasters(light, i, tempDrawables_, shadowCasterBox_[i]);
  737. if (shadowCasters_[i].Size())
  738. hasShadowCasters = true;
  739. }
  740. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  741. // only cost has been the shadow camera setup & queries
  742. if (!hasShadowCasters)
  743. shadowSplits = 0;
  744. // For a directional light queried with occlusion, can perform an optimization post-step: if a visible shadow caster has been
  745. // rejected due to occlusion, the light does not need to be rendered on it either
  746. if (shadowSplits && useOcclusion)
  747. {
  748. for (unsigned i = 0; i < litGeometries_.Size(); ++i)
  749. {
  750. Drawable* drawable = litGeometries_[i];
  751. if (drawable->GetCastShadows() && !dirLightShadowCasters_.Contains(drawable))
  752. litGeometries_[i] = 0;
  753. }
  754. }
  755. return shadowSplits;
  756. }
  757. void View::ProcessShadowCasters(Light* light, unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& shadowCasterBox)
  758. {
  759. Matrix3x4 lightView;
  760. Matrix4 lightProj;
  761. Camera* shadowCamera = shadowCameras_[splitIndex];
  762. lightView = shadowCamera->GetInverseWorldTransform();
  763. lightProj = shadowCamera->GetProjection();
  764. bool dirLight = shadowCamera->IsOrthographic();
  765. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  766. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  767. // frustum, so that shadow casters do not get rendered into unnecessary splits
  768. Frustum lightViewFrustum;
  769. if (!dirLight)
  770. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  771. else
  772. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, shadowNearSplits_[splitIndex]),
  773. Min(sceneViewBox_.max_.z_, shadowFarSplits_[splitIndex])).Transformed(lightView);
  774. BoundingBox lightViewFrustumBox(lightViewFrustum);
  775. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  776. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  777. return;
  778. BoundingBox lightViewBox;
  779. BoundingBox lightProjBox;
  780. for (unsigned i = 0; i < result.Size(); ++i)
  781. {
  782. Drawable* drawable = static_cast<Drawable*>(result[i]);
  783. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  784. // Check for that first
  785. if (!drawable->GetCastShadows())
  786. continue;
  787. drawable->UpdateDistance(frame_);
  788. // Check shadow distance
  789. float maxShadowDistance = drawable->GetShadowDistance();
  790. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  791. continue;
  792. // Check light mask
  793. if (!(drawable->GetLightMask() & light->GetLightMask()))
  794. continue;
  795. // Project shadow caster bounding box to light view space for visibility check
  796. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  797. if (drawable->IsInView(frame_) || IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum,
  798. lightViewFrustumBox))
  799. {
  800. // Update geometry now if not updated yet
  801. if (!drawable->IsInView(frame_))
  802. {
  803. drawable->MarkInShadowView(frame_);
  804. drawable->UpdateGeometry(frame_);
  805. }
  806. // Merge to shadow caster bounding box and add to the list
  807. if (dirLight)
  808. shadowCasterBox.Merge(lightViewBox);
  809. else
  810. {
  811. lightProjBox = lightViewBox.Projected(lightProj);
  812. shadowCasterBox.Merge(lightProjBox);
  813. }
  814. shadowCasters_[splitIndex].Push(drawable);
  815. }
  816. }
  817. }
  818. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  819. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  820. {
  821. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  822. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  823. if (drawable->IsOccluder())
  824. return true;
  825. if (shadowCamera->IsOrthographic())
  826. {
  827. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  828. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  829. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  830. }
  831. else
  832. {
  833. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  834. if (drawable->IsInView(frame_))
  835. return true;
  836. // For perspective lights, extrusion direction depends on the position of the shadow caster
  837. Vector3 center = lightViewBox.Center();
  838. Ray extrusionRay(center, center.Normalized());
  839. float extrusionDistance = shadowCamera->GetFarClip();
  840. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  841. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  842. float sizeFactor = extrusionDistance / originalDistance;
  843. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  844. // than necessary, so the test will be conservative
  845. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  846. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  847. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  848. lightViewBox.Merge(extrudedBox);
  849. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  850. }
  851. }
  852. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  853. {
  854. unsigned width = shadowMap->GetWidth();
  855. unsigned height = shadowMap->GetHeight();
  856. int maxCascades = renderer_->GetMaxShadowCascades();
  857. switch (light->GetLightType())
  858. {
  859. case LIGHT_DIRECTIONAL:
  860. if (maxCascades == 1)
  861. return IntRect(0, 0, width, height);
  862. else if (maxCascades == 2)
  863. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  864. else
  865. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  866. (splitIndex / 2 + 1) * height / 2);
  867. case LIGHT_SPOT:
  868. return IntRect(0, 0, width, height);
  869. case LIGHT_POINT:
  870. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  871. (splitIndex / 2 + 1) * height / 3);
  872. }
  873. return IntRect();
  874. }
  875. void View::OptimizeLightByScissor(Light* light)
  876. {
  877. if (light)
  878. graphics_->SetScissorTest(true, GetLightScissor(light));
  879. else
  880. graphics_->SetScissorTest(false);
  881. }
  882. void View::OptimizeLightByStencil(Light* light)
  883. {
  884. if (light && renderer_->GetLightStencilMasking())
  885. {
  886. Geometry* geometry = renderer_->GetLightGeometry(light);
  887. if (!geometry)
  888. {
  889. graphics_->SetStencilTest(false);
  890. return;
  891. }
  892. LightType type = light->GetLightType();
  893. Matrix3x4 view(camera_->GetInverseWorldTransform());
  894. Matrix4 projection(camera_->GetProjection());
  895. float lightDist;
  896. if (type == LIGHT_POINT)
  897. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  898. else
  899. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  900. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  901. if (lightDist < M_EPSILON)
  902. {
  903. graphics_->SetStencilTest(false);
  904. return;
  905. }
  906. // If the stencil value has wrapped, clear the whole stencil first
  907. if (!lightStencilValue_)
  908. {
  909. graphics_->Clear(CLEAR_STENCIL);
  910. lightStencilValue_ = 1;
  911. }
  912. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  913. // to avoid clipping the front faces.
  914. if (lightDist < camera_->GetNearClip() * 2.0f)
  915. {
  916. graphics_->SetCullMode(CULL_CW);
  917. graphics_->SetDepthTest(CMP_GREATER);
  918. }
  919. else
  920. {
  921. graphics_->SetCullMode(CULL_CCW);
  922. graphics_->SetDepthTest(CMP_LESSEQUAL);
  923. }
  924. graphics_->SetColorWrite(false);
  925. graphics_->SetDepthWrite(false);
  926. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  927. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  928. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  929. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform());
  930. geometry->Draw(graphics_);
  931. graphics_->ClearTransformSources();
  932. graphics_->SetColorWrite(true);
  933. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  934. // Increase stencil value for next light
  935. ++lightStencilValue_;
  936. }
  937. else
  938. graphics_->SetStencilTest(false);
  939. }
  940. const Rect& View::GetLightScissor(Light* light)
  941. {
  942. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  943. if (i != lightScissorCache_.End())
  944. return i->second_;
  945. Matrix3x4 view(camera_->GetInverseWorldTransform());
  946. Matrix4 projection(camera_->GetProjection());
  947. switch (light->GetLightType())
  948. {
  949. case LIGHT_POINT:
  950. {
  951. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  952. return lightScissorCache_[light] = viewBox.Projected(projection);
  953. }
  954. case LIGHT_SPOT:
  955. {
  956. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  957. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  958. }
  959. default:
  960. return lightScissorCache_[light] = Rect::FULL;
  961. }
  962. }
  963. unsigned View::SetupShadowCameras(Light* light)
  964. {
  965. LightType type = light->GetLightType();
  966. if (type == LIGHT_DIRECTIONAL)
  967. {
  968. const CascadeParameters& cascade = light->GetShadowCascade();
  969. int splits = 0;
  970. float nearSplit = camera_->GetNearClip();
  971. float farSplit;
  972. while (splits < renderer_->GetMaxShadowCascades())
  973. {
  974. // If split is completely beyond camera far clip, we are done
  975. if (nearSplit > camera_->GetFarClip())
  976. break;
  977. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  978. if (farSplit <= nearSplit)
  979. break;
  980. // Setup the shadow camera for the split
  981. Camera* shadowCamera = renderer_->CreateShadowCamera();
  982. shadowCameras_[splits] = shadowCamera;
  983. shadowNearSplits_[splits] = nearSplit;
  984. shadowFarSplits_[splits] = farSplit;
  985. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit, false);
  986. nearSplit = farSplit;
  987. ++splits;
  988. }
  989. return splits;
  990. }
  991. if (type == LIGHT_SPOT)
  992. {
  993. Camera* shadowCamera = renderer_->CreateShadowCamera();
  994. shadowCameras_[0] = shadowCamera;
  995. Node* cameraNode = shadowCamera->GetNode();
  996. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  997. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  998. shadowCamera->SetFarClip(light->GetRange());
  999. shadowCamera->SetFov(light->GetFov());
  1000. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1001. return 1;
  1002. }
  1003. if (type == LIGHT_POINT)
  1004. {
  1005. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1006. {
  1007. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1008. shadowCameras_[i] = shadowCamera;
  1009. Node* cameraNode = shadowCamera->GetNode();
  1010. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1011. cameraNode->SetPosition(light->GetWorldPosition());
  1012. cameraNode->SetDirection(directions[i]);
  1013. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1014. shadowCamera->SetFarClip(light->GetRange());
  1015. shadowCamera->SetFov(90.0f);
  1016. shadowCamera->SetAspectRatio(1.0f);
  1017. }
  1018. return MAX_CUBEMAP_FACES;
  1019. }
  1020. return 0;
  1021. }
  1022. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit, bool shadowOcclusion)
  1023. {
  1024. Node* cameraNode = shadowCamera->GetNode();
  1025. float extrusionDistance = camera_->GetFarClip();
  1026. const FocusParameters& parameters = light->GetShadowFocus();
  1027. // Calculate initial position & rotation
  1028. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1029. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1030. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1031. // Calculate main camera shadowed frustum in light's view space
  1032. farSplit = Min(farSplit, camera_->GetFarClip());
  1033. // Use the scene Z bounds to limit frustum size if applicable
  1034. if (shadowOcclusion || parameters.focus_)
  1035. {
  1036. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1037. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1038. }
  1039. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1040. frustumVolume_.Define(splitFrustum);
  1041. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1042. if (!shadowOcclusion && parameters.focus_)
  1043. {
  1044. PROFILE(ClipFrustumVolume);
  1045. BoundingBox litGeometriesBox;
  1046. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1047. {
  1048. // Skip "infinite" objects like the skybox
  1049. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1050. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1051. {
  1052. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1053. (geometries_[i]->GetLightMask() & light->GetLightMask()))
  1054. litGeometriesBox.Merge(geomBox);
  1055. }
  1056. }
  1057. if (litGeometriesBox.defined_)
  1058. {
  1059. frustumVolume_.Clip(litGeometriesBox);
  1060. // If volume became empty, restore it to avoid zero size
  1061. if (frustumVolume_.Empty())
  1062. frustumVolume_.Define(splitFrustum);
  1063. }
  1064. }
  1065. // Transform frustum volume to light space
  1066. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1067. frustumVolume_.Transform(lightView);
  1068. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1069. BoundingBox shadowBox;
  1070. if (shadowOcclusion || !parameters.nonUniform_)
  1071. shadowBox.Define(Sphere(frustumVolume_));
  1072. else
  1073. shadowBox.Define(frustumVolume_);
  1074. shadowCamera->SetOrthographic(true);
  1075. shadowCamera->SetAspectRatio(1.0f);
  1076. shadowCamera->SetNearClip(0.0f);
  1077. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1078. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1079. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1080. }
  1081. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1082. const BoundingBox& shadowCasterBox)
  1083. {
  1084. const FocusParameters& parameters = light->GetShadowFocus();
  1085. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1086. LightType type = light->GetLightType();
  1087. if (type == LIGHT_DIRECTIONAL)
  1088. {
  1089. BoundingBox shadowBox;
  1090. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1091. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1092. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1093. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1094. // Requantize and snap to shadow map texels
  1095. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1096. }
  1097. if (type == LIGHT_SPOT)
  1098. {
  1099. if (parameters.focus_)
  1100. {
  1101. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1102. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1103. float viewSize = Max(viewSizeX, viewSizeY);
  1104. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1105. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1106. float quantize = parameters.quantize_ * invOrthoSize;
  1107. float minView = parameters.minView_ * invOrthoSize;
  1108. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1109. if (viewSize < 1.0f)
  1110. shadowCamera->SetZoom(1.0f / viewSize);
  1111. }
  1112. }
  1113. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1114. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1115. if (shadowCamera->GetZoom() >= 1.0f)
  1116. {
  1117. if (light->GetLightType() != LIGHT_POINT)
  1118. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1119. else
  1120. {
  1121. #ifdef USE_OPENGL
  1122. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1123. #else
  1124. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1125. #endif
  1126. }
  1127. }
  1128. }
  1129. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1130. const BoundingBox& viewBox)
  1131. {
  1132. Node* cameraNode = shadowCamera->GetNode();
  1133. const FocusParameters& parameters = light->GetShadowFocus();
  1134. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1135. float minX = viewBox.min_.x_;
  1136. float minY = viewBox.min_.y_;
  1137. float maxX = viewBox.max_.x_;
  1138. float maxY = viewBox.max_.y_;
  1139. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1140. Vector2 viewSize(maxX - minX, maxY - minY);
  1141. // Quantize size to reduce swimming
  1142. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1143. if (parameters.nonUniform_)
  1144. {
  1145. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1146. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1147. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1148. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1149. }
  1150. else if (parameters.focus_)
  1151. {
  1152. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1153. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1154. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1155. viewSize.y_ = viewSize.x_;
  1156. }
  1157. shadowCamera->SetOrthoSize(viewSize);
  1158. // Center shadow camera to the view space bounding box
  1159. Vector3 pos(shadowCamera->GetWorldPosition());
  1160. Quaternion rot(shadowCamera->GetWorldRotation());
  1161. Vector3 adjust(center.x_, center.y_, 0.0f);
  1162. cameraNode->Translate(rot * adjust);
  1163. // If the shadow map viewport is known, snap to whole texels
  1164. if (shadowMapWidth > 0.0f)
  1165. {
  1166. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1167. // Take into account that shadow map border will not be used
  1168. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1169. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1170. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1171. cameraNode->Translate(rot * snap);
  1172. }
  1173. }
  1174. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1175. {
  1176. if (!material)
  1177. material = renderer_->GetDefaultMaterial();
  1178. if (!material)
  1179. return 0;
  1180. float lodDistance = drawable->GetLodDistance();
  1181. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1182. if (techniques.Empty())
  1183. return 0;
  1184. // Check for suitable technique. Techniques should be ordered like this:
  1185. // Most distant & highest quality
  1186. // Most distant & lowest quality
  1187. // Second most distant & highest quality
  1188. // ...
  1189. for (unsigned i = 0; i < techniques.Size(); ++i)
  1190. {
  1191. const TechniqueEntry& entry = techniques[i];
  1192. Technique* technique = entry.technique_;
  1193. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1194. continue;
  1195. if (lodDistance >= entry.lodDistance_)
  1196. return technique;
  1197. }
  1198. // If no suitable technique found, fallback to the last
  1199. return techniques.Back().technique_;
  1200. }
  1201. void View::CheckMaterialForAuxView(Material* material)
  1202. {
  1203. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1204. for (unsigned i = 0; i < textures.Size(); ++i)
  1205. {
  1206. // Have to check cube & 2D textures separately
  1207. Texture* texture = textures[i];
  1208. if (texture)
  1209. {
  1210. if (texture->GetType() == Texture2D::GetTypeStatic())
  1211. {
  1212. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1213. RenderSurface* target = tex2D->GetRenderSurface();
  1214. if (target)
  1215. {
  1216. const Viewport& viewport = target->GetViewport();
  1217. if (viewport.scene_ && viewport.camera_)
  1218. renderer_->AddView(target, viewport);
  1219. }
  1220. }
  1221. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1222. {
  1223. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1224. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1225. {
  1226. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1227. if (target)
  1228. {
  1229. const Viewport& viewport = target->GetViewport();
  1230. if (viewport.scene_ && viewport.camera_)
  1231. renderer_->AddView(target, viewport);
  1232. }
  1233. }
  1234. }
  1235. }
  1236. }
  1237. // Set frame number so that we can early-out next time we come across this material on the same frame
  1238. material->MarkForAuxView(frame_.frameNumber_);
  1239. }
  1240. void View::SortBatches()
  1241. {
  1242. PROFILE(SortBatches);
  1243. baseQueue_.SortFrontToBack();
  1244. extraQueue_.SortFrontToBack();
  1245. transparentQueue_.SortBackToFront();
  1246. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1247. {
  1248. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1249. lightQueues_[i].shadowSplits_[j].shadowBatches_.SortFrontToBack();
  1250. lightQueues_[i].litBatches_.SortFrontToBack();
  1251. }
  1252. }
  1253. void View::PrepareInstancingBuffer()
  1254. {
  1255. PROFILE(PrepareInstancingBuffer);
  1256. unsigned totalInstances = 0;
  1257. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1258. totalInstances += extraQueue_.GetNumInstances(renderer_);
  1259. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1260. {
  1261. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1262. totalInstances += lightQueues_[i].shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1263. totalInstances += lightQueues_[i].litBatches_.GetNumInstances(renderer_);
  1264. }
  1265. // If fail to set buffer size, fall back to per-group locking
  1266. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1267. {
  1268. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1269. unsigned freeIndex = 0;
  1270. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1271. if (lockedData)
  1272. {
  1273. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1274. extraQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1275. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1276. {
  1277. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1278. lightQueues_[i].shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1279. lightQueues_[i].litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1280. }
  1281. instancingBuffer->Unlock();
  1282. }
  1283. }
  1284. }
  1285. void View::CalculateShaderParameters()
  1286. {
  1287. Time* time = GetSubsystem<Time>();
  1288. float farClip = camera_->GetFarClip();
  1289. float nearClip = camera_->GetNearClip();
  1290. float fogStart = Min(zone_->GetFogStart(), farClip);
  1291. float fogEnd = Min(zone_->GetFogEnd(), farClip);
  1292. if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
  1293. fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
  1294. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1295. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1296. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1297. Vector4 depthMode = Vector4::ZERO;
  1298. if (camera_->IsOrthographic())
  1299. {
  1300. depthMode.x_ = 1.0f;
  1301. #ifdef USE_OPENGL
  1302. depthMode.z_ = 0.5f;
  1303. depthMode.w_ = 0.5f;
  1304. #else
  1305. depthMode.z_ = 1.0f;
  1306. #endif
  1307. }
  1308. else
  1309. depthMode.w_ = 1.0f / camera_->GetFarClip();
  1310. shaderParameters_.Clear();
  1311. shaderParameters_[VSP_DEPTHMODE] = depthMode;
  1312. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1313. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1314. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1315. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1316. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1317. }
  1318. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1319. {
  1320. if (useScissor)
  1321. graphics_->SetScissorTest(false);
  1322. graphics_->SetStencilTest(false);
  1323. // Priority instanced
  1324. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1325. queue.sortedPriorityBatchGroups_.End(); ++i)
  1326. {
  1327. BatchGroup* group = *i;
  1328. group->Draw(graphics_, renderer_, shaderParameters_);
  1329. }
  1330. // Priority non-instanced
  1331. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1332. {
  1333. Batch* batch = *i;
  1334. batch->Draw(graphics_, renderer_, shaderParameters_);
  1335. }
  1336. // Non-priority instanced
  1337. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1338. {
  1339. BatchGroup* group = *i;
  1340. if (useScissor && group->lightQueue_)
  1341. OptimizeLightByScissor(group->lightQueue_->light_);
  1342. group->Draw(graphics_, renderer_, shaderParameters_);
  1343. }
  1344. // Non-priority non-instanced
  1345. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1346. {
  1347. Batch* batch = *i;
  1348. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1349. if (useScissor)
  1350. {
  1351. if (!batch->hasPriority_ && batch->lightQueue_)
  1352. OptimizeLightByScissor(batch->lightQueue_->light_);
  1353. else
  1354. graphics_->SetScissorTest(false);
  1355. }
  1356. batch->Draw(graphics_, renderer_, shaderParameters_);
  1357. }
  1358. }
  1359. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1360. {
  1361. graphics_->SetScissorTest(false);
  1362. graphics_->SetStencilTest(false);
  1363. // Priority instanced
  1364. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1365. queue.sortedPriorityBatchGroups_.End(); ++i)
  1366. {
  1367. BatchGroup* group = *i;
  1368. group->Draw(graphics_, renderer_, shaderParameters_);
  1369. }
  1370. // Priority non-instanced
  1371. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1372. {
  1373. Batch* batch = *i;
  1374. batch->Draw(graphics_, renderer_, shaderParameters_);
  1375. }
  1376. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1377. OptimizeLightByStencil(light);
  1378. OptimizeLightByScissor(light);
  1379. // Non-priority instanced
  1380. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1381. {
  1382. BatchGroup* group = *i;
  1383. group->Draw(graphics_, renderer_, shaderParameters_);
  1384. }
  1385. // Non-priority non-instanced
  1386. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1387. {
  1388. Batch* batch = *i;
  1389. batch->Draw(graphics_, renderer_, shaderParameters_);
  1390. }
  1391. }
  1392. void View::RenderShadowMap(const LightBatchQueue& queue)
  1393. {
  1394. PROFILE(RenderShadowMap);
  1395. Texture2D* shadowMap = queue.shadowMap_;
  1396. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1397. if (!graphics_->GetFallback())
  1398. {
  1399. graphics_->SetColorWrite(false);
  1400. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1401. graphics_->SetDepthStencil(shadowMap);
  1402. graphics_->Clear(CLEAR_DEPTH);
  1403. }
  1404. else
  1405. {
  1406. graphics_->SetColorWrite(true);
  1407. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1408. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1409. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1410. }
  1411. // Set shadow depth bias
  1412. BiasParameters parameters = queue.light_->GetShadowBias();
  1413. // Adjust the light's constant depth bias according to global shadow map resolution
  1414. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1415. if (shadowMapSize <= 512)
  1416. parameters.constantBias_ *= 2.0f;
  1417. else if (shadowMapSize >= 2048)
  1418. parameters.constantBias_ *= 0.5f;
  1419. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1420. // Render each of the splits
  1421. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1422. {
  1423. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1424. if (!shadowQueue.shadowBatches_.IsEmpty())
  1425. {
  1426. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1427. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1428. // However, do not do this for point lights, which need to render continuously across cube faces
  1429. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1430. if (queue.light_->GetLightType() != LIGHT_POINT)
  1431. {
  1432. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1433. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1434. graphics_->SetScissorTest(true, zoomRect, false);
  1435. }
  1436. else
  1437. graphics_->SetScissorTest(false);
  1438. // Draw instanced and non-instanced shadow casters
  1439. RenderBatchQueue(shadowQueue.shadowBatches_);
  1440. }
  1441. }
  1442. graphics_->SetColorWrite(true);
  1443. graphics_->SetDepthBias(0.0f, 0.0f);
  1444. graphics_->SetScissorTest(false);
  1445. }