2
0

View.cpp 70 KB

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