2
0

View.cpp 74 KB

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