View.cpp 72 KB

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