2
0

View.cpp 68 KB

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