View.cpp 87 KB

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