View.cpp 73 KB

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