View.cpp 70 KB

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