View.cpp 73 KB

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