View.cpp 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254
  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 "Technique.h"
  39. #include "Texture2D.h"
  40. #include "TextureCube.h"
  41. #include "Time.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const String aaVariation[] = {
  47. "",
  48. "Ortho"
  49. };
  50. static const Vector3 directions[] =
  51. {
  52. Vector3::RIGHT,
  53. Vector3::LEFT,
  54. Vector3::UP,
  55. Vector3::DOWN,
  56. Vector3::FORWARD,
  57. Vector3::BACK,
  58. };
  59. OBJECTTYPESTATIC(View);
  60. View::View(Context* context) :
  61. Object(context),
  62. graphics_(GetSubsystem<Graphics>()),
  63. renderer_(GetSubsystem<Renderer>()),
  64. octree_(0),
  65. camera_(0),
  66. zone_(0),
  67. renderTarget_(0),
  68. depthStencil_(0),
  69. jitterCounter_(0)
  70. {
  71. frame_.camera_ = 0;
  72. }
  73. View::~View()
  74. {
  75. }
  76. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  77. {
  78. if ((!viewport.scene_) || (!viewport.camera_))
  79. return false;
  80. // If scene is loading asynchronously, it is incomplete and should not be rendered
  81. if (viewport.scene_->IsAsyncLoading())
  82. return false;
  83. Octree* octree = viewport.scene_->GetComponent<Octree>();
  84. if (!octree)
  85. return false;
  86. mode_ = graphics_->GetRenderMode();
  87. // In deferred mode, check for the render texture being too large
  88. if ((mode_ != RENDER_FORWARD) && (renderTarget))
  89. {
  90. if ((renderTarget->GetWidth() > graphics_->GetWidth()) || (renderTarget->GetHeight() > graphics_->GetHeight()))
  91. {
  92. // Display message only once per rendertarget, do not spam each frame
  93. if (gBufferErrorDisplayed_.Find(renderTarget) == gBufferErrorDisplayed_.End())
  94. {
  95. gBufferErrorDisplayed_.Insert(renderTarget);
  96. LOGERROR("Render texture is larger than the G-buffer, can not render");
  97. }
  98. return false;
  99. }
  100. }
  101. octree_ = octree;
  102. camera_ = viewport.camera_;
  103. renderTarget_ = renderTarget;
  104. // If not rendering to the back buffer, get the depth buffer linked to the color render target
  105. if (renderTarget)
  106. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  107. else
  108. depthStencil_ = 0;
  109. zone_ = renderer_->GetDefaultZone();
  110. // Validate the rect and calculate size. If zero rect, use whole render target size
  111. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  112. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  113. if (viewport.rect_ != IntRect::ZERO)
  114. {
  115. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  116. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  117. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  118. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  119. }
  120. else
  121. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  122. width_ = screenRect_.right_ - screenRect_.left_;
  123. height_ = screenRect_.bottom_ - screenRect_.top_;
  124. // Set possible quality overrides from the camera
  125. drawShadows_ = renderer_->GetDrawShadows();
  126. materialQuality_ = renderer_->GetMaterialQuality();
  127. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  128. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  129. if (viewOverrideFlags & VOF_LOW_MATERIAL_QUALITY)
  130. materialQuality_ = QUALITY_LOW;
  131. if (viewOverrideFlags & VOF_DISABLE_SHADOWS)
  132. drawShadows_ = false;
  133. if (viewOverrideFlags & VOF_DISABLE_OCCLUSION)
  134. maxOccluderTriangles_ = 0;
  135. return true;
  136. }
  137. void View::Update(const FrameInfo& frame)
  138. {
  139. if ((!camera_) || (!octree_))
  140. return;
  141. frame_.camera_ = camera_;
  142. frame_.timeStep_ = frame.timeStep_;
  143. frame_.frameNumber_ = frame.frameNumber_;
  144. frame_.viewSize_ = IntVector2(width_, height_);
  145. // Clear old light scissor cache, geometry, light, occluder & batch lists
  146. lightScissorCache_.Clear();
  147. geometries_.Clear();
  148. geometryDepthBounds_.Clear();
  149. lights_.Clear();
  150. occluders_.Clear();
  151. shadowOccluders_.Clear();
  152. gBufferQueue_.Clear();
  153. baseQueue_.Clear();
  154. extraQueue_.Clear();
  155. transparentQueue_.Clear();
  156. noShadowLightQueue_.Clear();
  157. lightQueues_.Clear();
  158. // Set automatic aspect ratio if required
  159. if (camera_->GetAutoAspectRatio())
  160. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  161. // Reset projection jitter if was used last frame
  162. camera_->SetProjectionOffset(Vector2::ZERO);
  163. // Reset shadow map use count; they can be reused between views as each is rendered completely at a time
  164. renderer_->ResetShadowMapUseCount();
  165. GetDrawables();
  166. GetBatches();
  167. }
  168. void View::Render()
  169. {
  170. if ((!octree_) || (!camera_))
  171. return;
  172. // If stream offset is supported, write all instance transforms to a single large buffer
  173. // Else we must lock the instance buffer for each batch group
  174. if ((renderer_->GetDynamicInstancing()) && (graphics_->GetStreamOffsetSupport()))
  175. PrepareInstancingBuffer();
  176. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  177. // again to ensure correct projection will be used
  178. if (camera_->GetAutoAspectRatio())
  179. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  180. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during rendering
  181. if (renderTarget_)
  182. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  183. else
  184. graphics_->SetViewTexture(0);
  185. graphics_->SetFillMode(FILL_SOLID);
  186. // Calculate view-global shader parameters
  187. CalculateShaderParameters();
  188. // If not reusing shadowmaps, render all of them first
  189. if (!renderer_->reuseShadowMaps_)
  190. {
  191. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  192. {
  193. LightBatchQueue& queue = lightQueues_[i];
  194. if (queue.light_->GetShadowMap())
  195. RenderShadowMap(queue);
  196. }
  197. }
  198. if (mode_ == RENDER_FORWARD)
  199. RenderBatchesForward();
  200. else
  201. RenderBatchesDeferred();
  202. graphics_->SetViewTexture(0);
  203. // If this is a main view, draw the associated debug geometry now
  204. if (!renderTarget_)
  205. {
  206. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  207. if (scene)
  208. {
  209. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  210. if (debug)
  211. {
  212. debug->SetView(camera_);
  213. debug->Render();
  214. }
  215. }
  216. }
  217. // "Forget" the camera, octree and zone after rendering
  218. camera_ = 0;
  219. octree_ = 0;
  220. zone_ = 0;
  221. frame_.camera_ = 0;
  222. }
  223. void View::GetDrawables()
  224. {
  225. PROFILE(GetDrawables);
  226. Vector3 cameraPos = camera_->GetWorldPosition();
  227. // Get zones & find the zone camera is in
  228. PODVector<Zone*> zones;
  229. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>& >(zones), cameraPos, DRAWABLE_ZONE);
  230. octree_->GetDrawables(query);
  231. int highestZonePriority = M_MIN_INT;
  232. for (unsigned i = 0; i < zones.Size(); ++i)
  233. {
  234. Zone* zone = zones[i];
  235. if ((zone->IsInside(cameraPos)) && (zone->GetPriority() > highestZonePriority))
  236. {
  237. zone_ = zone;
  238. highestZonePriority = zone->GetPriority();
  239. }
  240. }
  241. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  242. bool useOcclusion = false;
  243. OcclusionBuffer* buffer = 0;
  244. if (maxOccluderTriangles_ > 0)
  245. {
  246. FrustumOctreeQuery query(occluders_, camera_->GetFrustum(), DRAWABLE_GEOMETRY, true, false);
  247. octree_->GetDrawables(query);
  248. UpdateOccluders(occluders_, camera_);
  249. if (occluders_.Size())
  250. {
  251. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  252. DrawOccluders(buffer, occluders_);
  253. buffer->BuildDepthHierarchy();
  254. useOcclusion = true;
  255. }
  256. }
  257. if (!useOcclusion)
  258. {
  259. // Get geometries & lights without occlusion
  260. FrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  261. octree_->GetDrawables(query);
  262. }
  263. else
  264. {
  265. // Get geometries & lights using occlusion
  266. OccludedFrustumOctreeQuery query(tempDrawables_, camera_->GetFrustum(), buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  267. octree_->GetDrawables(query);
  268. }
  269. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  270. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  271. sceneBox_.defined_ = false;
  272. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  273. sceneViewBox_.defined_ = false;
  274. Matrix3x4 view(camera_->GetInverseWorldTransform());
  275. unsigned cameraViewMask = camera_->GetViewMask();
  276. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  277. {
  278. Drawable* drawable = tempDrawables_[i];
  279. // Check view mask
  280. if (!(cameraViewMask & drawable->GetViewMask()))
  281. continue;
  282. drawable->UpdateDistance(frame_);
  283. // If draw distance non-zero, check it
  284. float maxDistance = drawable->GetDrawDistance();
  285. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  286. continue;
  287. unsigned flags = drawable->GetDrawableFlags();
  288. if (flags & DRAWABLE_GEOMETRY)
  289. {
  290. drawable->ClearBasePass();
  291. drawable->MarkInView(frame_);
  292. drawable->UpdateGeometry(frame_);
  293. // Expand the scene bounding boxes
  294. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  295. BoundingBox geoview_Box = geomBox.Transformed(view);
  296. sceneBox_.Merge(geomBox);
  297. sceneViewBox_.Merge(geoview_Box);
  298. // Store depth info to speed up split directional light queries
  299. GeometryDepthBounds bounds;
  300. bounds.min_ = geoview_Box.min_.z_;
  301. bounds.max_ = geoview_Box.max_.z_;
  302. geometryDepthBounds_.Push(bounds);
  303. geometries_.Push(drawable);
  304. }
  305. else if (flags & DRAWABLE_LIGHT)
  306. {
  307. Light* light = static_cast<Light*>(drawable);
  308. // Skip if light is culled by the zone
  309. if (!(light->GetViewMask() & zone_->GetViewMask()))
  310. continue;
  311. light->MarkInView(frame_);
  312. lights_.Push(light);
  313. }
  314. }
  315. // Sort the lights to brightest/closest first
  316. for (unsigned i = 0; i < lights_.Size(); ++i)
  317. lights_[i]->SetIntensitySortValue(cameraPos);
  318. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  319. }
  320. void View::GetBatches()
  321. {
  322. HashSet<LitTransparencyCheck> litTransparencies;
  323. HashSet<Drawable*> maxLightsDrawables;
  324. Map<Light*, unsigned> lightQueueIndex;
  325. PassType gBufferPass = PASS_DEFERRED;
  326. PassType additionalPass = PASS_EXTRA;
  327. if (mode_ == RENDER_PREPASS)
  328. {
  329. gBufferPass = PASS_PREPASS;
  330. additionalPass = PASS_MATERIAL;
  331. }
  332. // Go through lights
  333. {
  334. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  335. unsigned lightQueueCount = 0;
  336. for (unsigned i = 0; i < lights_.Size(); ++i)
  337. {
  338. Light* light = lights_[i];
  339. unsigned splits = ProcessLight(light);
  340. if (!splits)
  341. continue;
  342. // Prepare lit object + shadow caster queues for each split
  343. if (lightQueues_.Size() < lightQueueCount + splits)
  344. lightQueues_.Resize(lightQueueCount + splits);
  345. unsigned prevLightQueueCount = lightQueueCount;
  346. for (unsigned j = 0; j < splits; ++j)
  347. {
  348. Light* SplitLight = splitLights_[j];
  349. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  350. lightQueue.light_ = SplitLight;
  351. lightQueue.shadowBatches_.Clear();
  352. lightQueue.litBatches_.Clear();
  353. lightQueue.volumeBatches_.Clear();
  354. lightQueue.lastSplit_ = false;
  355. // Loop through shadow casters
  356. Camera* shadowCamera = SplitLight->GetShadowCamera();
  357. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  358. {
  359. Drawable* drawable = shadowCasters_[j][k];
  360. unsigned numBatches = drawable->GetNumBatches();
  361. for (unsigned l = 0; l < numBatches; ++l)
  362. {
  363. Batch shadowBatch;
  364. drawable->GetBatch(frame_, l, shadowBatch);
  365. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  366. if ((!shadowBatch.geometry_) || (!tech))
  367. continue;
  368. Pass* pass = tech->GetPass(PASS_SHADOW);
  369. // Skip if material has no shadow pass
  370. if (!pass)
  371. continue;
  372. // Fill the rest of the batch
  373. shadowBatch.camera_ = shadowCamera;
  374. shadowBatch.distance_ = shadowCamera->GetDistance(drawable->GetWorldPosition());
  375. shadowBatch.light_ = SplitLight;
  376. shadowBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  377. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  378. lightQueue.shadowBatches_.AddBatch(shadowBatch);
  379. }
  380. }
  381. // Loop through lit geometries
  382. if (litGeometries_[j].Size())
  383. {
  384. bool storeLightQueue = true;
  385. for (unsigned k = 0; k < litGeometries_[j].Size(); ++k)
  386. {
  387. Drawable* drawable = litGeometries_[j][k];
  388. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  389. if (!drawable->GetMaxLights())
  390. GetLitBatches(drawable, light, SplitLight, &lightQueue, litTransparencies, gBufferPass);
  391. else
  392. {
  393. drawable->AddLight(SplitLight);
  394. maxLightsDrawables.Insert(drawable);
  395. }
  396. }
  397. // Store the light queue, and light volume batch in deferred mode
  398. if (mode_ != RENDER_FORWARD)
  399. {
  400. Batch volumeBatch;
  401. volumeBatch.geometry_ = renderer_->GetLightGeometry(SplitLight);
  402. volumeBatch.worldTransform_ = &SplitLight->GetVolumeTransform(*camera_);
  403. volumeBatch.overrideView_ = SplitLight->GetLightType() == LIGHT_DIRECTIONAL;
  404. volumeBatch.camera_ = camera_;
  405. volumeBatch.light_ = SplitLight;
  406. volumeBatch.distance_ = SplitLight->GetDistance();
  407. renderer_->SetLightVolumeShaders(volumeBatch);
  408. // If light is a split point light, it must be treated as shadowed in any case for correct stencil clearing
  409. if ((SplitLight->GetShadowMap()) || (SplitLight->GetLightType() == LIGHT_SPLITPOINT))
  410. lightQueue.volumeBatches_.Push(volumeBatch);
  411. else
  412. {
  413. storeLightQueue = false;
  414. noShadowLightQueue_.AddBatch(volumeBatch, true);
  415. }
  416. }
  417. if (storeLightQueue)
  418. {
  419. lightQueueIndex[SplitLight] = lightQueueCount;
  420. ++lightQueueCount;
  421. }
  422. }
  423. }
  424. // Mark the last split
  425. if (lightQueueCount != prevLightQueueCount)
  426. lightQueues_[lightQueueCount - 1].lastSplit_ = true;
  427. }
  428. // Resize the light queue vector now that final size is known
  429. lightQueues_.Resize(lightQueueCount);
  430. }
  431. // Process drawables with limited light count
  432. if (maxLightsDrawables.Size())
  433. {
  434. PROFILE(GetMaxLightsBatches);
  435. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables.Begin(); i != maxLightsDrawables.End(); ++i)
  436. {
  437. Drawable* drawable = *i;
  438. drawable->LimitLights();
  439. const PODVector<Light*>& lights = drawable->GetLights();
  440. for (unsigned i = 0; i < lights.Size(); ++i)
  441. {
  442. Light* SplitLight = lights[i];
  443. Light* light = SplitLight->GetOriginalLight();
  444. if (!light)
  445. light = SplitLight;
  446. // Find the correct light queue again
  447. LightBatchQueue* queue = 0;
  448. Map<Light*, unsigned>::Iterator j = lightQueueIndex.Find(SplitLight);
  449. if (j != lightQueueIndex.End())
  450. queue = &lightQueues_[j->second_];
  451. GetLitBatches(drawable, light, SplitLight, queue, litTransparencies, gBufferPass);
  452. }
  453. }
  454. }
  455. // Go through geometries for base pass batches
  456. {
  457. PROFILE(GetBaseBatches);
  458. for (unsigned i = 0; i < geometries_.Size(); ++i)
  459. {
  460. Drawable* drawable = geometries_[i];
  461. unsigned numBatches = drawable->GetNumBatches();
  462. for (unsigned j = 0; j < numBatches; ++j)
  463. {
  464. Batch baseBatch;
  465. drawable->GetBatch(frame_, j, baseBatch);
  466. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  467. if ((!baseBatch.geometry_) || (!tech))
  468. continue;
  469. // Check here if the material technique refers to a render target texture with camera(s) attached
  470. // Only check this for the main view (null rendertarget)
  471. if ((!renderTarget_) && (baseBatch.material_) && (baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_))
  472. CheckMaterialForAuxView(baseBatch.material_);
  473. // If object already has a lit base pass, can skip the unlit base pass
  474. if (drawable->HasBasePass(j))
  475. continue;
  476. // Fill the rest of the batch
  477. baseBatch.camera_ = camera_;
  478. baseBatch.distance_ = drawable->GetDistance();
  479. Pass* pass = 0;
  480. // In deferred mode, check for a G-buffer batch first
  481. if (mode_ != RENDER_FORWARD)
  482. {
  483. pass = tech->GetPass(gBufferPass);
  484. if (pass)
  485. {
  486. renderer_->SetBatchShaders(baseBatch, tech, pass);
  487. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  488. gBufferQueue_.AddBatch(baseBatch);
  489. // Check also for an additional pass. In light prepass mode this actually renders the visible geometry
  490. pass = tech->GetPass(additionalPass);
  491. if (pass)
  492. {
  493. renderer_->SetBatchShaders(baseBatch, tech, pass);
  494. baseQueue_.AddBatch(baseBatch);
  495. }
  496. continue;
  497. }
  498. }
  499. // Then check for forward rendering base pass
  500. pass = tech->GetPass(PASS_BASE);
  501. if (pass)
  502. {
  503. renderer_->SetBatchShaders(baseBatch, tech, pass);
  504. if (pass->GetBlendMode() == BLEND_REPLACE)
  505. {
  506. baseBatch.hasPriority_ = (!pass->GetAlphaTest()) && (!pass->GetAlphaMask());
  507. baseQueue_.AddBatch(baseBatch);
  508. }
  509. else
  510. {
  511. baseBatch.hasPriority_ = true;
  512. transparentQueue_.AddBatch(baseBatch, true);
  513. }
  514. continue;
  515. }
  516. else
  517. {
  518. // If no base pass, finally check for extra / custom pass
  519. pass = tech->GetPass(PASS_EXTRA);
  520. if (pass)
  521. {
  522. baseBatch.hasPriority_ = false;
  523. renderer_->SetBatchShaders(baseBatch, tech, pass);
  524. extraQueue_.AddBatch(baseBatch);
  525. }
  526. }
  527. }
  528. }
  529. }
  530. // All batches have been collected. Sort them now
  531. SortBatches();
  532. }
  533. void View::GetLitBatches(Drawable* drawable, Light* light, Light* SplitLight, LightBatchQueue* lightQueue,
  534. HashSet<LitTransparencyCheck>& litTransparencies, PassType gBufferPass)
  535. {
  536. bool splitPointLight = SplitLight->GetLightType() == LIGHT_SPLITPOINT;
  537. // Whether to allow shadows for transparencies, or for forward lit objects in deferred mode
  538. bool allowShadows = (!renderer_->reuseShadowMaps_) && (!splitPointLight);
  539. unsigned numBatches = drawable->GetNumBatches();
  540. for (unsigned i = 0; i < numBatches; ++i)
  541. {
  542. Batch litBatch;
  543. drawable->GetBatch(frame_, i, litBatch);
  544. Technique* tech = GetTechnique(drawable, litBatch.material_);
  545. if ((!litBatch.geometry_) || (!tech))
  546. continue;
  547. // If material uses opaque G-buffer rendering, skip
  548. if ((mode_ != RENDER_FORWARD) && (tech->HasPass(gBufferPass)))
  549. continue;
  550. Pass* pass = 0;
  551. bool priority = false;
  552. // For directional light, check for lit base pass
  553. if (SplitLight->GetLightType() == LIGHT_DIRECTIONAL)
  554. {
  555. if (!drawable->HasBasePass(i))
  556. {
  557. pass = tech->GetPass(PASS_LITBASE);
  558. if (pass)
  559. {
  560. priority = true;
  561. drawable->SetBasePass(i);
  562. }
  563. }
  564. }
  565. // If no first light pass, get ordinary light pass
  566. if (!pass)
  567. pass = tech->GetPass(PASS_LIGHT);
  568. // Skip if material does not receive light at all
  569. if (!pass)
  570. continue;
  571. // Fill the rest of the batch
  572. litBatch.camera_ = camera_;
  573. litBatch.distance_ = drawable->GetDistance();
  574. litBatch.light_ = SplitLight;
  575. litBatch.hasPriority_ = priority;
  576. // Check from the ambient pass whether the object is opaque
  577. Pass* ambientPass = tech->GetPass(PASS_BASE);
  578. if ((!ambientPass) || (ambientPass->GetBlendMode() == BLEND_REPLACE))
  579. {
  580. if (mode_ == RENDER_FORWARD)
  581. {
  582. if (lightQueue)
  583. {
  584. renderer_->SetBatchShaders(litBatch, tech, pass);
  585. lightQueue->litBatches_.AddBatch(litBatch);
  586. }
  587. }
  588. else
  589. {
  590. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  591. baseQueue_.AddBatch(litBatch);
  592. }
  593. }
  594. else
  595. {
  596. if (splitPointLight)
  597. {
  598. // Check if already lit
  599. LitTransparencyCheck check(light, drawable, i);
  600. if (litTransparencies.Find(check) != litTransparencies.End())
  601. continue;
  602. // Use the original light instead of the split one, to choose correct scissor
  603. litBatch.light_ = light;
  604. litTransparencies.Insert(check);
  605. }
  606. renderer_->SetBatchShaders(litBatch, tech, pass, allowShadows);
  607. transparentQueue_.AddBatch(litBatch, true);
  608. }
  609. }
  610. }
  611. void View::RenderBatchesForward()
  612. {
  613. {
  614. // Render opaque objects' base passes
  615. PROFILE(RenderBasePass);
  616. graphics_->ClearLastParameterSources();
  617. graphics_->SetColorWrite(true);
  618. graphics_->SetStencilTest(false);
  619. graphics_->SetRenderTarget(0, renderTarget_);
  620. graphics_->SetDepthStencil(depthStencil_);
  621. graphics_->SetViewport(screenRect_);
  622. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, zone_->GetFogColor());
  623. RenderBatchQueue(baseQueue_);
  624. }
  625. {
  626. // Render shadow maps + opaque objects' shadowed additive lighting
  627. PROFILE(RenderLights);
  628. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  629. {
  630. LightBatchQueue& queue = lightQueues_[i];
  631. // If reusing shadowmaps, render each of them before the lit batches
  632. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  633. RenderShadowMap(queue);
  634. graphics_->ClearLastParameterSources();
  635. graphics_->SetRenderTarget(0, renderTarget_);
  636. graphics_->SetDepthStencil(depthStencil_);
  637. graphics_->SetViewport(screenRect_);
  638. RenderForwardLightBatchQueue(queue.litBatches_, queue.light_);
  639. // Clear the stencil buffer after the last split
  640. if (queue.lastSplit_)
  641. {
  642. LightType type = queue.light_->GetLightType();
  643. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  644. DrawSplitLightToStencil(*camera_, queue.light_, true);
  645. }
  646. }
  647. }
  648. {
  649. // Render extra / custom passes
  650. PROFILE(RenderExtraPass);
  651. graphics_->ClearLastParameterSources();
  652. graphics_->SetRenderTarget(0, renderTarget_);
  653. graphics_->SetDepthStencil(depthStencil_);
  654. graphics_->SetViewport(screenRect_);
  655. RenderBatchQueue(extraQueue_);
  656. }
  657. {
  658. // Render transparent objects last (both base passes & additive lighting)
  659. PROFILE(RenderTransparent);
  660. RenderBatchQueue(transparentQueue_, true);
  661. }
  662. }
  663. void View::RenderBatchesDeferred()
  664. {
  665. bool deferred = mode_ != RENDER_PREPASS;
  666. Texture2D* diffBuffer = graphics_->GetDiffBuffer();
  667. Texture2D* normalBuffer = graphics_->GetNormalBuffer();
  668. Texture2D* depthBuffer = graphics_->GetDepthBuffer();
  669. // Check for temporal antialiasing in deferred mode. Only use it on the main view (null rendertarget)
  670. bool temporalAA = (!renderTarget_) && (graphics_->GetMultiSample() > 0);
  671. if (temporalAA)
  672. {
  673. ++jitterCounter_;
  674. if (jitterCounter_ > 3)
  675. jitterCounter_ = 2;
  676. Vector2 jitter(-0.25f, -0.25f);
  677. if (jitterCounter_ & 1)
  678. jitter = -jitter;
  679. jitter.x_ /= width_;
  680. jitter.y_ /= height_;
  681. camera_->SetProjectionOffset(jitter);
  682. }
  683. RenderSurface* renderBuffer = temporalAA ? graphics_->GetScreenBuffer(jitterCounter_ & 1)->GetRenderSurface() : renderTarget_;
  684. // Set shader parameters needed only in deferred rendering
  685. Vector3 nearVector, farVector;
  686. camera_->GetFrustumSize(nearVector, farVector);
  687. Vector4 viewportParams(farVector.x_, farVector.y_, farVector.z_, 0.0f);
  688. float gBufferWidth = (float)diffBuffer->GetWidth();
  689. float gBufferHeight = (float)diffBuffer->GetHeight();
  690. float widthRange = 0.5f * width_ / gBufferWidth;
  691. float heightRange = 0.5f * height_ / gBufferHeight;
  692. Vector4 bufferUVOffset((0.5f + (float)screenRect_.left_) / gBufferWidth + widthRange,
  693. (0.5f + (float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  694. Vector4 viewportSize((float)screenRect_.left_ / gBufferWidth, (float)screenRect_.top_ / gBufferHeight,
  695. (float)screenRect_.right_ / gBufferWidth, (float)screenRect_.bottom_ / gBufferHeight);
  696. shaderParameters_[VSP_FRUSTUMSIZE] = viewportParams;
  697. shaderParameters_[VSP_GBUFFEROFFSETS] = bufferUVOffset;
  698. shaderParameters_[PSP_GBUFFEROFFSETS] = bufferUVOffset;
  699. shaderParameters_[PSP_GBUFFERVIEWPORT] = viewportSize;
  700. {
  701. // Render G-buffer
  702. PROFILE(RenderGBuffer);
  703. graphics_->ClearLastParameterSources();
  704. // Use always the default depth stencil, so that it matches the G-buffer size, and is in the expected format
  705. graphics_->SetColorWrite(true);
  706. graphics_->SetScissorTest(false);
  707. graphics_->SetStencilTest(false);
  708. graphics_->ResetDepthStencil();
  709. if (deferred)
  710. {
  711. graphics_->SetRenderTarget(0, diffBuffer);
  712. graphics_->SetRenderTarget(1, normalBuffer);
  713. graphics_->SetRenderTarget(2, depthBuffer);
  714. }
  715. else
  716. {
  717. graphics_->SetRenderTarget(0, normalBuffer);
  718. graphics_->SetRenderTarget(1, depthBuffer);
  719. }
  720. graphics_->SetViewport(screenRect_);
  721. // Clear only depth and stencil at first, render the G-buffer batches
  722. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  723. RenderBatchQueue(gBufferQueue_);
  724. // Then fill the untouched parts of the G-buffer with defaults: black diffuse + specular (deferred only), far depth
  725. graphics_->SetAlphaTest(false);
  726. graphics_->SetBlendMode(BLEND_REPLACE);
  727. graphics_->SetDepthTest(CMP_LESSEQUAL);
  728. graphics_->SetDepthWrite(false);
  729. if (deferred)
  730. {
  731. graphics_->ResetRenderTarget(2);
  732. graphics_->SetRenderTarget(1, depthBuffer);
  733. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/GBufferFill"),
  734. renderer_->GetPixelShader("Deferred/GBufferFill"), false, shaderParameters_);
  735. }
  736. else
  737. {
  738. graphics_->ResetRenderTarget(1);
  739. graphics_->SetRenderTarget(0, depthBuffer);
  740. graphics_->SetViewport(screenRect_);
  741. // The stencil shader writes color 1.0, which equals far depth
  742. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Stencil"),
  743. renderer_->GetPixelShader("Stencil"), false, shaderParameters_);
  744. }
  745. }
  746. if (deferred)
  747. {
  748. // Render ambient color & fog
  749. graphics_->ClearLastParameterSources();
  750. graphics_->SetDepthTest(CMP_ALWAYS);
  751. graphics_->SetRenderTarget(0, renderBuffer);
  752. graphics_->ResetRenderTarget(1);
  753. graphics_->ResetRenderTarget(2);
  754. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  755. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  756. graphics_->SetViewport(screenRect_);
  757. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader("Deferred/Ambient"),
  758. renderer_->GetPixelShader("Deferred/Ambient"), false, shaderParameters_);
  759. }
  760. else
  761. {
  762. // Light prepass: reset the light accumulation buffer with black color
  763. graphics_->SetRenderTarget(0, diffBuffer);
  764. graphics_->ResetRenderTarget(1);
  765. graphics_->SetViewport(screenRect_);
  766. graphics_->Clear(CLEAR_COLOR);
  767. }
  768. {
  769. // Render lights
  770. PROFILE(RenderLights);
  771. // Shadowed lights
  772. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  773. {
  774. LightBatchQueue& queue = lightQueues_[i];
  775. // If reusing shadowmaps, render each of them before the lit batches
  776. if ((renderer_->reuseShadowMaps_) && (queue.light_->GetShadowMap()))
  777. RenderShadowMap(queue);
  778. // Light volume batches are not sorted as there should be only one of them
  779. if (queue.volumeBatches_.Size())
  780. {
  781. graphics_->ClearLastParameterSources();
  782. if (deferred)
  783. {
  784. graphics_->SetRenderTarget(0, renderBuffer);
  785. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  786. }
  787. else
  788. graphics_->SetRenderTarget(0, diffBuffer);
  789. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  790. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  791. graphics_->ResetDepthStencil();
  792. graphics_->SetViewport(screenRect_);
  793. for (unsigned j = 0; j < queue.volumeBatches_.Size(); ++j)
  794. {
  795. renderer_->SetupLightBatch(queue.volumeBatches_[j]);
  796. queue.volumeBatches_[j].Draw(graphics_, shaderParameters_);
  797. }
  798. // If was the last split of a split point light, clear the stencil by rendering the point light again
  799. if ((queue.lastSplit_) && (queue.light_->GetLightType() == LIGHT_SPLITPOINT))
  800. DrawSplitLightToStencil(*camera_, queue.light_, true);
  801. }
  802. }
  803. // Non-shadowed lights
  804. if (noShadowLightQueue_.sortedBatches_.Size())
  805. {
  806. graphics_->ClearLastParameterSources();
  807. if (deferred)
  808. {
  809. graphics_->SetRenderTarget(0, renderBuffer);
  810. graphics_->SetTexture(TU_DIFFBUFFER, diffBuffer);
  811. }
  812. else
  813. graphics_->SetRenderTarget(0, diffBuffer);
  814. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  815. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  816. graphics_->ResetDepthStencil();
  817. graphics_->SetViewport(screenRect_);
  818. for (unsigned i = 0; i < noShadowLightQueue_.sortedBatches_.Size(); ++i)
  819. {
  820. renderer_->SetupLightBatch(*noShadowLightQueue_.sortedBatches_[i]);
  821. noShadowLightQueue_.sortedBatches_[i]->Draw(graphics_, shaderParameters_);
  822. }
  823. }
  824. }
  825. {
  826. // Render base passes
  827. PROFILE(RenderBasePass);
  828. graphics_->ClearLastParameterSources();
  829. graphics_->SetStencilTest(false);
  830. graphics_->SetRenderTarget(0, renderBuffer);
  831. graphics_->SetTexture(TU_DIFFBUFFER, 0);
  832. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  833. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  834. graphics_->SetViewport(screenRect_);
  835. if (!deferred)
  836. graphics_->Clear(CLEAR_COLOR, zone_->GetFogColor());
  837. // Remember to bind the light buffer in prepass mode
  838. RenderBatchQueue(baseQueue_, true, !deferred);
  839. }
  840. {
  841. // Render extra / custom passes
  842. PROFILE(RenderExtraPass);
  843. RenderBatchQueue(extraQueue_);
  844. }
  845. {
  846. // Render transparent objects last (both ambient & additive lighting)
  847. PROFILE(RenderTransparent);
  848. RenderBatchQueue(transparentQueue_, true);
  849. }
  850. // Render temporal antialiasing now if enabled
  851. if (temporalAA)
  852. {
  853. PROFILE(RenderTemporalAA);
  854. // Disable averaging if it is the first frame rendered in this view
  855. float thisFrameWeight = jitterCounter_ < 2 ? 1.0f : 0.5f;
  856. Vector4 depthMode = Vector4::ZERO;
  857. if (camera_->IsOrthographic())
  858. depthMode.z_ = 1.0f;
  859. else
  860. depthMode.w_ = 1.0f / camera_->GetFarClip();
  861. graphics_->SetAlphaTest(false);
  862. graphics_->SetBlendMode(BLEND_REPLACE);
  863. graphics_->SetDepthTest(CMP_ALWAYS);
  864. graphics_->SetDepthWrite(false);
  865. graphics_->SetScissorTest(false);
  866. graphics_->SetStencilTest(false);
  867. graphics_->SetRenderTarget(0, renderTarget_);
  868. graphics_->SetViewport(screenRect_);
  869. graphics_->SetTexture(TU_DIFFBUFFER, graphics_->GetScreenBuffer(jitterCounter_ & 1));
  870. graphics_->SetTexture(TU_NORMALBUFFER, graphics_->GetScreenBuffer((jitterCounter_ + 1) & 1));
  871. graphics_->SetTexture(TU_DEPTHBUFFER, graphics_->GetDepthBuffer());
  872. graphics_->SetShaderParameter(VSP_CAMERAROT, camera_->GetWorldTransform().RotationMatrix());
  873. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  874. graphics_->SetShaderParameter(PSP_CAMERAPOS, camera_->GetWorldPosition());
  875. graphics_->SetShaderParameter(PSP_ANTIALIASWEIGHTS, Vector4(thisFrameWeight, 1.0f - thisFrameWeight, 0.0f, 0.0f));
  876. graphics_->SetShaderParameter(PSP_SAMPLEOFFSETS, Vector4(1.0f / gBufferWidth, 1.0f / gBufferHeight, 0.0f, 0.0f));
  877. graphics_->SetShaderParameter(PSP_VIEWPROJ, camera_->GetProjection(false) * lastCameraView_);
  878. unsigned index = camera_->IsOrthographic() ? 1 : 0;
  879. String shaderName = "TemporalAA_" + aaVariation[index];
  880. renderer_->DrawFullScreenQuad(*camera_, renderer_->GetVertexShader(shaderName),
  881. renderer_->GetPixelShader(shaderName), false, shaderParameters_);
  882. // Store view transform for next frame
  883. lastCameraView_ = camera_->GetInverseWorldTransform();
  884. }
  885. }
  886. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  887. {
  888. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  889. float halfViewSize = camera->GetHalfViewSize();
  890. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  891. Vector3 cameraPos = camera->GetWorldPosition();
  892. unsigned cameraViewMask = camera->GetViewMask();
  893. for (unsigned i = 0; i < occluders.Size(); ++i)
  894. {
  895. Drawable* occluder = occluders[i];
  896. occluder->UpdateDistance(frame_);
  897. bool erase = false;
  898. // Check view mask
  899. if (!(cameraViewMask & occluder->GetViewMask()))
  900. erase = true;
  901. // Check occluder's draw distance (in main camera view)
  902. float maxDistance = occluder->GetDrawDistance();
  903. if ((maxDistance > 0.0f) && (occluder->GetDistance() > maxDistance))
  904. erase = true;
  905. // Check that occluder is big enough on the screen
  906. const BoundingBox& box = occluder->GetWorldBoundingBox();
  907. float diagonal = (box.max_ - box.min_).LengthFast();
  908. float compare;
  909. if (!camera->IsOrthographic())
  910. compare = diagonal * halfViewSize / occluder->GetDistance();
  911. else
  912. compare = diagonal * invOrthoSize;
  913. if (compare < occluderSizeThreshold_)
  914. erase = true;
  915. if (!erase)
  916. {
  917. unsigned totalTriangles = 0;
  918. unsigned batches = occluder->GetNumBatches();
  919. Batch tempBatch;
  920. for (unsigned j = 0; j < batches; ++j)
  921. {
  922. occluder->GetBatch(frame_, j, tempBatch);
  923. if (tempBatch.geometry_)
  924. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  925. }
  926. // Store amount of triangles divided by screen size as a sorting key
  927. // (best occluders are big and have few triangles)
  928. occluder->SetSortValue((float)totalTriangles / compare);
  929. }
  930. else
  931. {
  932. occluders.Erase(occluders.Begin() + i);
  933. --i;
  934. }
  935. }
  936. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  937. if (occluders.Size())
  938. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  939. }
  940. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  941. {
  942. for (unsigned i = 0; i < occluders.Size(); ++i)
  943. {
  944. Drawable* occluder = occluders[i];
  945. if (i > 0)
  946. {
  947. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  948. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  949. continue;
  950. }
  951. occluder->UpdateGeometry(frame_);
  952. // Check for running out of triangles
  953. if (!occluder->DrawOcclusion(buffer))
  954. return;
  955. }
  956. }
  957. unsigned View::ProcessLight(Light* light)
  958. {
  959. unsigned numLitGeometries = 0;
  960. unsigned numShadowCasters = 0;
  961. unsigned numSplits;
  962. // Check if light should be shadowed
  963. bool isShadowed = (drawShadows_) && (light->GetCastShadows());
  964. // If shadow distance non-zero, check it
  965. if ((isShadowed) && (light->GetShadowDistance() > 0.0f) && (light->GetDistance() > light->GetShadowDistance()))
  966. isShadowed = false;
  967. // If light has no ramp textures defined, set defaults
  968. if ((light->GetLightType() != LIGHT_DIRECTIONAL) && (!light->GetRampTexture()))
  969. light->SetRampTexture(renderer_->GetDefaultLightRamp());
  970. if ((light->GetLightType() == LIGHT_SPOT) && (!light->GetShapeTexture()))
  971. light->SetShapeTexture(renderer_->GetDefaultLightSpot());
  972. // Split the light if necessary
  973. if (isShadowed)
  974. numSplits = SplitLight(light);
  975. else
  976. {
  977. // No splitting, use the original light
  978. splitLights_[0] = light;
  979. numSplits = 1;
  980. }
  981. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  982. bool useOcclusion = false;
  983. OcclusionBuffer* buffer = 0;
  984. if ((maxOccluderTriangles_ > 0) && (isShadowed) && (light->GetLightType() == LIGHT_DIRECTIONAL))
  985. {
  986. // This shadow camera is never used for actually querying shadow casters, just occluders
  987. Camera* shadowCamera = renderer_->CreateShadowCamera();
  988. light->SetShadowCamera(shadowCamera);
  989. SetupShadowCamera(light, true);
  990. // Get occluders, which must be shadow-casting themselves
  991. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, true, true);
  992. octree_->GetDrawables(query);
  993. UpdateOccluders(shadowOccluders_, shadowCamera);
  994. if (shadowOccluders_.Size())
  995. {
  996. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  997. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  998. DrawOccluders(buffer, shadowOccluders_);
  999. buffer->BuildDepthHierarchy();
  1000. useOcclusion = true;
  1001. }
  1002. }
  1003. // Process each split for shadow camera update, lit geometries, and shadow casters
  1004. for (unsigned i = 0; i < numSplits; ++i)
  1005. {
  1006. litGeometries_[i].Clear();
  1007. shadowCasters_[i].Clear();
  1008. }
  1009. for (unsigned i = 0; i < numSplits; ++i)
  1010. {
  1011. Light* split = splitLights_[i];
  1012. LightType type = split->GetLightType();
  1013. bool isSplitShadowed = (isShadowed) && (split->GetCastShadows());
  1014. Camera* shadowCamera = 0;
  1015. // If shadow casting, choose the shadow map & update shadow camera
  1016. if (isSplitShadowed)
  1017. {
  1018. shadowCamera = renderer_->CreateShadowCamera();
  1019. split->SetShadowMap(renderer_->GetShadowMap(splitLights_[i]->GetShadowResolution()));
  1020. // Check if managed to get a shadow map. Otherwise must convert to non-shadowed
  1021. if (split->GetShadowMap())
  1022. {
  1023. split->SetShadowCamera(shadowCamera);
  1024. SetupShadowCamera(split);
  1025. }
  1026. else
  1027. {
  1028. isSplitShadowed = false;
  1029. split->SetShadowCamera(0);
  1030. }
  1031. }
  1032. else
  1033. {
  1034. split->SetShadowCamera(0);
  1035. split->SetShadowMap(0);
  1036. }
  1037. BoundingBox geometryBox;
  1038. BoundingBox shadowCasterBox;
  1039. switch (type)
  1040. {
  1041. case LIGHT_DIRECTIONAL:
  1042. // Loop through visible geometries and check if they belong to this split
  1043. {
  1044. float nearSplit = split->GetNearSplit() - split->GetNearFadeRange();
  1045. float farSplit = split->GetFarSplit();
  1046. // If split extends to the whole visible frustum, no depth check necessary
  1047. bool optimize = (nearSplit <= camera_->GetNearClip()) && (farSplit >= camera_->GetFarClip());
  1048. // If whole visible scene is outside the split, can reject trivially
  1049. if ((sceneViewBox_.min_.z_ > farSplit) || (sceneViewBox_.max_.z_ < nearSplit))
  1050. {
  1051. split->SetShadowMap(0);
  1052. continue;
  1053. }
  1054. bool generateBoxes = (isSplitShadowed) && (split->GetShadowFocus().focus_);
  1055. Matrix3x4 lightView;
  1056. if (shadowCamera)
  1057. lightView = shadowCamera->GetInverseWorldTransform();
  1058. if (!optimize)
  1059. {
  1060. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1061. {
  1062. Drawable* drawable = geometries_[j];
  1063. const GeometryDepthBounds& bounds = geometryDepthBounds_[j];
  1064. // Check bounds and light mask
  1065. if ((bounds.min_ <= farSplit) && (bounds.max_ >= nearSplit) && (drawable->GetLightMask() &
  1066. split->GetLightMask()))
  1067. {
  1068. litGeometries_[i].Push(drawable);
  1069. if (generateBoxes)
  1070. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1071. }
  1072. }
  1073. }
  1074. else
  1075. {
  1076. for (unsigned j = 0; j < geometries_.Size(); ++j)
  1077. {
  1078. Drawable* drawable = geometries_[j];
  1079. // Need to check light mask only
  1080. if (drawable->GetLightMask() & split->GetLightMask())
  1081. {
  1082. litGeometries_[i].Push(drawable);
  1083. if (generateBoxes)
  1084. geometryBox.Merge(drawable->GetWorldBoundingBox().Transformed(lightView));
  1085. }
  1086. }
  1087. }
  1088. }
  1089. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  1090. if ((isSplitShadowed) && (litGeometries_[i].Size()))
  1091. {
  1092. Camera* shadowCamera = split->GetShadowCamera();
  1093. if (!useOcclusion)
  1094. {
  1095. // Get potential shadow casters without occlusion
  1096. FrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY);
  1097. octree_->GetDrawables(query);
  1098. }
  1099. else
  1100. {
  1101. // Get potential shadow casters with occlusion
  1102. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  1103. DRAWABLE_GEOMETRY);
  1104. octree_->GetDrawables(query);
  1105. }
  1106. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, false, isSplitShadowed);
  1107. }
  1108. break;
  1109. case LIGHT_POINT:
  1110. {
  1111. SphereOctreeQuery query(tempDrawables_, Sphere(split->GetWorldPosition(), split->GetRange()), DRAWABLE_GEOMETRY);
  1112. octree_->GetDrawables(query);
  1113. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, false);
  1114. }
  1115. break;
  1116. case LIGHT_SPOT:
  1117. case LIGHT_SPLITPOINT:
  1118. {
  1119. FrustumOctreeQuery query(tempDrawables_, splitLights_[i]->GetFrustum(), DRAWABLE_GEOMETRY);
  1120. octree_->GetDrawables(query);
  1121. ProcessLightQuery(i, tempDrawables_, geometryBox, shadowCasterBox, true, isSplitShadowed);
  1122. }
  1123. break;
  1124. }
  1125. // Optimization: if a particular split has no shadow casters, render as unshadowed
  1126. if (!shadowCasters_[i].Size())
  1127. split->SetShadowMap(0);
  1128. // Focus shadow camera as applicable
  1129. if (split->GetShadowMap())
  1130. {
  1131. if (split->GetShadowFocus().focus_)
  1132. FocusShadowCamera(split, geometryBox, shadowCasterBox);
  1133. // Set a zoom factor to ensure that we do not render to the shadow map border
  1134. // (clamp addressing is necessary because border mode /w hardware shadow maps is not supported by all GPUs)
  1135. Camera* shadowCamera = split->GetShadowCamera();
  1136. Texture2D* shadowMap = split->GetShadowMap();
  1137. if (shadowCamera->GetZoom() >= 1.0f)
  1138. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth()));
  1139. }
  1140. // Update count of total lit geometries & shadow casters
  1141. numLitGeometries += litGeometries_[i].Size();
  1142. numShadowCasters += shadowCasters_[i].Size();
  1143. }
  1144. // If no lit geometries at all, no need to process further
  1145. if (!numLitGeometries)
  1146. numSplits = 0;
  1147. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  1148. else if (!numShadowCasters)
  1149. {
  1150. if (numSplits > 1)
  1151. {
  1152. // Make sure there are no duplicates
  1153. HashSet<Drawable*> allLitGeometries;
  1154. for (unsigned i = 0; i < numSplits; ++i)
  1155. {
  1156. for (Vector<Drawable*>::Iterator j = litGeometries_[i].Begin(); j != litGeometries_[i].End(); ++j)
  1157. allLitGeometries.Insert(*j);
  1158. }
  1159. litGeometries_[0].Resize(allLitGeometries.Size());
  1160. unsigned index = 0;
  1161. for (HashSet<Drawable*>::Iterator i = allLitGeometries.Begin(); i != allLitGeometries.End(); ++i)
  1162. litGeometries_[0][index++] = *i;
  1163. }
  1164. splitLights_[0] = light;
  1165. splitLights_[0]->SetShadowMap(0);
  1166. numSplits = 1;
  1167. }
  1168. return numSplits;
  1169. }
  1170. void View::ProcessLightQuery(unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& geometryBox,
  1171. BoundingBox& shadowCasterBox, bool getLitGeometries, bool GetShadowCasters)
  1172. {
  1173. Light* light = splitLights_[splitIndex];
  1174. Matrix3x4 lightView;
  1175. Matrix4 lightProj;
  1176. Frustum lightViewFrustum;
  1177. BoundingBox lightViewFrustumBox;
  1178. bool mergeBoxes = (light->GetLightType() != LIGHT_SPLITPOINT) && (light->GetShadowMap()) && (light->GetShadowFocus().focus_);
  1179. bool projectBoxes = false;
  1180. Camera* shadowCamera = light->GetShadowCamera();
  1181. if (shadowCamera)
  1182. {
  1183. bool projectBoxes = !shadowCamera->IsOrthographic();
  1184. lightView = shadowCamera->GetInverseWorldTransform();
  1185. lightProj = shadowCamera->GetProjection();
  1186. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  1187. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  1188. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  1189. // rendered into unnecessary splits
  1190. if (light->GetLightType() != LIGHT_DIRECTIONAL)
  1191. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1192. else
  1193. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, light->GetNearSplit() - light->GetNearFadeRange()),
  1194. Min(sceneViewBox_.max_.z_, light->GetFarSplit())).Transformed(lightView);
  1195. lightViewFrustumBox.Define(lightViewFrustum);
  1196. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1197. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1198. GetShadowCasters = false;
  1199. }
  1200. else
  1201. GetShadowCasters = false;
  1202. BoundingBox lightViewBox;
  1203. BoundingBox lightProjBox;
  1204. for (unsigned i = 0; i < result.Size(); ++i)
  1205. {
  1206. Drawable* drawable = static_cast<Drawable*>(result[i]);
  1207. drawable->UpdateDistance(frame_);
  1208. bool boxGenerated = false;
  1209. // If draw distance non-zero, check it
  1210. float maxDistance = drawable->GetDrawDistance();
  1211. if ((maxDistance > 0.0f) && (drawable->GetDistance() > maxDistance))
  1212. continue;
  1213. // Check light mask
  1214. if (!(drawable->GetLightMask() & light->GetLightMask()))
  1215. continue;
  1216. // Get lit geometry only if inside main camera frustum this frame
  1217. if ((getLitGeometries) && (drawable->IsInView(frame_)))
  1218. {
  1219. if (mergeBoxes)
  1220. {
  1221. // Transform bounding box into light view space, and to projection space if needed
  1222. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1223. if (!projectBoxes)
  1224. geometryBox.Merge(lightViewBox);
  1225. else
  1226. {
  1227. lightProjBox = lightViewBox.Projected(lightProj);
  1228. geometryBox.Merge(lightProjBox);
  1229. }
  1230. boxGenerated = true;
  1231. }
  1232. litGeometries_[splitIndex].Push(drawable);
  1233. }
  1234. // Shadow caster need not be inside main camera frustum: in that case try to detect whether
  1235. // the shadow projection intersects the view
  1236. if ((GetShadowCasters) && (drawable->GetCastShadows()))
  1237. {
  1238. // If shadow distance non-zero, check it
  1239. float maxShadowDistance = drawable->GetShadowDistance();
  1240. if ((maxShadowDistance > 0.0f) && (drawable->GetDistance() > maxShadowDistance))
  1241. continue;
  1242. if (!boxGenerated)
  1243. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1244. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1245. {
  1246. if (mergeBoxes)
  1247. {
  1248. if (!projectBoxes)
  1249. shadowCasterBox.Merge(lightViewBox);
  1250. else
  1251. {
  1252. if (!boxGenerated)
  1253. lightProjBox = lightViewBox.Projected(lightProj);
  1254. shadowCasterBox.Merge(lightProjBox);
  1255. }
  1256. }
  1257. // Update geometry now if not updated yet
  1258. if (!drawable->IsInView(frame_))
  1259. {
  1260. drawable->MarkInShadowView(frame_);
  1261. drawable->UpdateGeometry(frame_);
  1262. }
  1263. shadowCasters_[splitIndex].Push(drawable);
  1264. }
  1265. }
  1266. }
  1267. }
  1268. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1269. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1270. {
  1271. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  1272. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  1273. if (drawable->IsOccluder())
  1274. return true;
  1275. if (shadowCamera->IsOrthographic())
  1276. {
  1277. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1278. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1279. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1280. }
  1281. else
  1282. {
  1283. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1284. if (drawable->IsInView(frame_))
  1285. return true;
  1286. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1287. Vector3 center = lightViewBox.Center();
  1288. Ray extrusionRay(center, center.Normalized());
  1289. float extrusionDistance = shadowCamera->GetFarClip();
  1290. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1291. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1292. float sizeFactor = extrusionDistance / originalDistance;
  1293. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1294. // than necessary, so the test will be conservative
  1295. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1296. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1297. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1298. lightViewBox.Merge(extrudedBox);
  1299. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1300. }
  1301. }
  1302. void View::SetupShadowCamera(Light* light, bool shadowOcclusion)
  1303. {
  1304. Camera* shadowCamera = light->GetShadowCamera();
  1305. Node* cameraNode = shadowCamera->GetNode();
  1306. const FocusParameters& parameters = light->GetShadowFocus();
  1307. // Reset zoom
  1308. shadowCamera->SetZoom(1.0f);
  1309. switch(light->GetLightType())
  1310. {
  1311. case LIGHT_DIRECTIONAL:
  1312. {
  1313. float extrusionDistance = camera_->GetFarClip();
  1314. // Calculate initial position & rotation
  1315. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1316. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1317. Quaternion rot(Vector3::FORWARD, lightWorldDirection);
  1318. cameraNode->SetTransform(pos, rot);
  1319. // Calculate main camera shadowed frustum in light's view space
  1320. float sceneMaxZ = camera_->GetFarClip();
  1321. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  1322. if ((shadowOcclusion) || (parameters.focus_))
  1323. sceneMaxZ = Min(sceneViewBox_.max_.z_, sceneMaxZ);
  1324. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1325. Frustum lightViewSplitFrustum = camera_->GetSplitFrustum(light->GetNearSplit() - light->GetNearFadeRange(),
  1326. Min(light->GetFarSplit(), sceneMaxZ)).Transformed(lightView);
  1327. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  1328. BoundingBox shadowBox;
  1329. if ((!shadowOcclusion) && (parameters.nonUniform_))
  1330. shadowBox.Define(lightViewSplitFrustum);
  1331. else
  1332. {
  1333. Sphere shadowSphere;
  1334. shadowSphere.Define(lightViewSplitFrustum);
  1335. shadowBox.Define(shadowSphere);
  1336. }
  1337. shadowCamera->SetOrthographic(true);
  1338. shadowCamera->SetNearClip(0.0f);
  1339. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1340. // Center shadow camera on the bounding box, snap to whole texels
  1341. QuantizeDirShadowCamera(light, shadowBox);
  1342. }
  1343. break;
  1344. case LIGHT_SPOT:
  1345. case LIGHT_SPLITPOINT:
  1346. {
  1347. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1348. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1349. shadowCamera->SetFarClip(light->GetRange());
  1350. shadowCamera->SetOrthographic(false);
  1351. shadowCamera->SetFov(light->GetFov());
  1352. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1353. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  1354. if ((light->GetLightType() == LIGHT_SPOT) && (parameters.zoomOut_))
  1355. {
  1356. // Make sure the out-zooming does not start while we are inside the spot
  1357. float distance = Max((camera_->GetInverseWorldTransform() * light->GetWorldPosition()).z_ - light->GetRange(), 1.0f);
  1358. float lightPixels = (((float)height_ * light->GetRange() * camera_->GetZoom() * 0.5f) / distance);
  1359. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  1360. if (lightPixels < SHADOW_MIN_PIXELS)
  1361. lightPixels = SHADOW_MIN_PIXELS;
  1362. float zoolevel_ = Min(lightPixels / (float)light->GetShadowMap()->GetHeight(), 1.0f);
  1363. shadowCamera->SetZoom(zoolevel_);
  1364. }
  1365. }
  1366. break;
  1367. }
  1368. }
  1369. void View::FocusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  1370. {
  1371. // If either no geometries or no shadow casters, do nothing
  1372. if ((!geometryBox.defined_) || (!shadowCasterBox.defined_))
  1373. return;
  1374. Camera* shadowCamera = light->GetShadowCamera();
  1375. const FocusParameters& parameters = light->GetShadowFocus();
  1376. switch (light->GetLightType())
  1377. {
  1378. case LIGHT_DIRECTIONAL:
  1379. {
  1380. BoundingBox combinedBox;
  1381. combinedBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1382. combinedBox.max_.x_ = shadowCamera->GetAspectRatio() * combinedBox.max_.y_;
  1383. combinedBox.min_.y_ = -combinedBox.max_.y_;
  1384. combinedBox.min_.x_ = -combinedBox.max_.x_;
  1385. combinedBox.Intersect(geometryBox);
  1386. combinedBox.Intersect(shadowCasterBox);
  1387. QuantizeDirShadowCamera(light, combinedBox);
  1388. }
  1389. break;
  1390. case LIGHT_SPOT:
  1391. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  1392. if (shadowCamera->GetZoom() >= 1.0f)
  1393. {
  1394. BoundingBox combinedBox(-1.0f, 1.0f);
  1395. combinedBox.Intersect(geometryBox);
  1396. combinedBox.Intersect(shadowCasterBox);
  1397. float viewSizeX = Max(fabsf(combinedBox.min_.x_), fabsf(combinedBox.max_.x_));
  1398. float viewSizeY = Max(fabsf(combinedBox.min_.y_), fabsf(combinedBox.max_.y_));
  1399. float viewSize = Max(viewSizeX, viewSizeY);
  1400. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1401. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1402. float quantize = parameters.quantize_ * invOrthoSize;
  1403. float minView = parameters.minView_ * invOrthoSize;
  1404. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1405. if (viewSize < 1.0f)
  1406. shadowCamera->SetZoom(1.0f / viewSize);
  1407. }
  1408. break;
  1409. }
  1410. }
  1411. void View::QuantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  1412. {
  1413. Camera* shadowCamera = light->GetShadowCamera();
  1414. Node* cameraNode = shadowCamera->GetNode();
  1415. const FocusParameters& parameters = light->GetShadowFocus();
  1416. float minX = viewBox.min_.x_;
  1417. float minY = viewBox.min_.y_;
  1418. float maxX = viewBox.max_.x_;
  1419. float maxY = viewBox.max_.y_;
  1420. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1421. Vector2 viewSize(maxX - minX, maxY - minY);
  1422. // Quantize size to reduce swimming
  1423. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1424. if (parameters.nonUniform_)
  1425. {
  1426. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1427. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1428. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1429. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1430. }
  1431. else if (parameters.focus_)
  1432. {
  1433. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1434. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1435. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1436. viewSize.y_ = viewSize.x_;
  1437. }
  1438. shadowCamera->SetOrthoSize(viewSize);
  1439. // Center shadow camera to the view space bounding box
  1440. Vector3 pos = shadowCamera->GetWorldPosition();
  1441. Quaternion rot = shadowCamera->GetWorldRotation();
  1442. Vector3 adjust(center.x_, center.y_, 0.0f);
  1443. cameraNode->Translate(rot * adjust);
  1444. // If there is a shadow map, snap to its whole texels
  1445. Texture2D* shadowMap = light->GetShadowMap();
  1446. if (shadowMap)
  1447. {
  1448. Vector3 viewPos(rot.Inverse() * shadowCamera->GetWorldPosition());
  1449. // Take into account that shadow map border will not be used
  1450. float invActualSize = 1.0f / (float)(shadowMap->GetWidth() - 2);
  1451. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1452. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1453. cameraNode->Translate(rot * snap);
  1454. }
  1455. }
  1456. void View::OptimizeLightByScissor(Light* light)
  1457. {
  1458. if (light)
  1459. graphics_->SetScissorTest(true, GetLightScissor(light));
  1460. else
  1461. graphics_->SetScissorTest(false);
  1462. }
  1463. const Rect& View::GetLightScissor(Light* light)
  1464. {
  1465. Map<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1466. if (i != lightScissorCache_.End())
  1467. return i->second_;
  1468. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1469. Matrix4 projection(camera_->GetProjection());
  1470. switch (light->GetLightType())
  1471. {
  1472. case LIGHT_POINT:
  1473. {
  1474. BoundingBox viewBox = light->GetWorldBoundingBox().Transformed(view);
  1475. return lightScissorCache_[light] = viewBox.Projected(projection);
  1476. }
  1477. case LIGHT_SPOT:
  1478. case LIGHT_SPLITPOINT:
  1479. {
  1480. Frustum viewFrustum = light->GetFrustum().Transformed(view);
  1481. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1482. }
  1483. default:
  1484. return lightScissorCache_[light] = Rect::FULL;
  1485. }
  1486. }
  1487. unsigned View::SplitLight(Light* light)
  1488. {
  1489. LightType type = light->GetLightType();
  1490. if (type == LIGHT_DIRECTIONAL)
  1491. {
  1492. const CascadeParameters& cascade = light->GetShadowCascade();
  1493. unsigned splits = cascade.splits_;
  1494. if (splits > MAX_LIGHT_SPLITS - 1)
  1495. splits = MAX_LIGHT_SPLITS;
  1496. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  1497. float farClip = Min(cascade.shadowRange_, camera_->GetFarClip()); // Shadow range end
  1498. float nearClip = Max(camera_->GetNearClip(), M_MIN_NEARCLIP); // Shadow range start
  1499. bool CreateExtraSplit = farClip < camera_->GetFarClip();
  1500. // Practical split scheme (Zhang et al.)
  1501. unsigned i;
  1502. for (i = 0; i < splits; ++i)
  1503. {
  1504. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  1505. float splitFadeRange = Max(cascade.splitFadeRange_, 0.001f);
  1506. float iPerM = (float)i / (float)splits;
  1507. float log = nearClip * powf(farClip / nearClip, iPerM);
  1508. float uniform = nearClip + (farClip - nearClip) * iPerM;
  1509. float nearSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1510. float nearFadeRange = nearSplit * splitFadeRange;
  1511. iPerM = (float)(i + 1) / (float)splits;
  1512. log = nearClip * powf(farClip / nearClip, iPerM);
  1513. uniform = nearClip + (farClip - nearClip) * iPerM;
  1514. float farSplit = log * cascade.lambda_ + uniform * (1.0f - cascade.lambda_);
  1515. float farFadeRange = farSplit * splitFadeRange;
  1516. // If split is completely beyond camera far clip, we are done
  1517. if ((nearSplit - nearFadeRange) > camera_->GetFarClip())
  1518. break;
  1519. Light* SplitLight = renderer_->CreateSplitLight(light);
  1520. splitLights_[i] = SplitLight;
  1521. // Though the near clip was previously clamped, use the real near clip value for the first split,
  1522. // so that there are no unlit portions
  1523. if (i)
  1524. SplitLight->SetNearSplit(nearSplit);
  1525. else
  1526. SplitLight->SetNearSplit(camera_->GetNearClip());
  1527. SplitLight->SetNearFadeRange(nearFadeRange);
  1528. SplitLight->SetFarSplit(farSplit);
  1529. // The final split will not fade
  1530. if ((CreateExtraSplit) || (i < splits - 1))
  1531. SplitLight->SetFarFadeRange(farFadeRange);
  1532. // Create an extra unshadowed split if necessary
  1533. if ((CreateExtraSplit) && (i == splits - 1))
  1534. {
  1535. Light* SplitLight = renderer_->CreateSplitLight(light);
  1536. splitLights_[i + 1] = SplitLight;
  1537. SplitLight->SetNearSplit(farSplit);
  1538. SplitLight->SetNearFadeRange(farFadeRange);
  1539. SplitLight->SetCastShadows(false);
  1540. }
  1541. }
  1542. if (CreateExtraSplit)
  1543. return i + 1;
  1544. else
  1545. return i;
  1546. }
  1547. if (type == LIGHT_POINT)
  1548. {
  1549. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1550. {
  1551. Light* SplitLight = renderer_->CreateSplitLight(light);
  1552. Node* lightNode = SplitLight->GetNode();
  1553. splitLights_[i] = SplitLight;
  1554. SplitLight->SetLightType(LIGHT_SPLITPOINT);
  1555. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1556. lightNode->SetDirection(directions[i]);
  1557. SplitLight->SetFov(90.0f);
  1558. SplitLight->SetAspectRatio(1.0f);
  1559. }
  1560. return MAX_CUBEMAP_FACES;
  1561. }
  1562. // A spot light does not actually need splitting. However, we may be rendering several views,
  1563. // and in some the light might be unshadowed, so better create an unique copy
  1564. Light* SplitLight = renderer_->CreateSplitLight(light);
  1565. splitLights_[0] = SplitLight;
  1566. return 1;
  1567. }
  1568. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1569. {
  1570. if (!material)
  1571. material = renderer_->GetDefaultMaterial();
  1572. if (!material)
  1573. return 0;
  1574. float lodDistance = drawable->GetLodDistance();
  1575. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1576. if (techniques.Empty())
  1577. return 0;
  1578. // Check for suitable technique. Techniques should be ordered like this:
  1579. // Most distant & highest quality
  1580. // Most distant & lowest quality
  1581. // Second most distant & highest quality
  1582. // ...
  1583. for (unsigned i = 0; i < techniques.Size(); ++i)
  1584. {
  1585. const TechniqueEntry& entry = techniques[i];
  1586. Technique* technique = entry.technique_;
  1587. if ((!technique) || ((technique->IsSM3()) && (!graphics_->GetSM3Support())) || (materialQuality_ < entry.qualityLevel_))
  1588. continue;
  1589. if (lodDistance >= entry.lodDistance_)
  1590. return technique;
  1591. }
  1592. // If no suitable technique found, fallback to the last
  1593. return techniques.Back().technique_;
  1594. }
  1595. void View::CheckMaterialForAuxView(Material* material)
  1596. {
  1597. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1598. for (unsigned i = 0; i < textures.Size(); ++i)
  1599. {
  1600. // Have to check cube & 2D textures separately
  1601. Texture* texture = textures[i];
  1602. if (texture)
  1603. {
  1604. if (texture->GetType() == Texture2D::GetTypeStatic())
  1605. {
  1606. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1607. RenderSurface* target = tex2D->GetRenderSurface();
  1608. if (target)
  1609. {
  1610. const Viewport& viewport = target->GetViewport();
  1611. if ((viewport.scene_) && (viewport.camera_))
  1612. renderer_->AddView(target, viewport);
  1613. }
  1614. }
  1615. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1616. {
  1617. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1618. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1619. {
  1620. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1621. if (target)
  1622. {
  1623. const Viewport& viewport = target->GetViewport();
  1624. if ((viewport.scene_) && (viewport.camera_))
  1625. renderer_->AddView(target, viewport);
  1626. }
  1627. }
  1628. }
  1629. }
  1630. }
  1631. // Set frame number so that we can early-out next time we come across this material on the same frame
  1632. material->MarkForAuxView(frame_.frameNumber_);
  1633. }
  1634. void View::SortBatches()
  1635. {
  1636. PROFILE(SortBatches);
  1637. if (mode_ != RENDER_FORWARD)
  1638. {
  1639. gBufferQueue_.SortFrontToBack();
  1640. noShadowLightQueue_.SortFrontToBack();
  1641. }
  1642. baseQueue_.SortFrontToBack();
  1643. extraQueue_.SortFrontToBack();
  1644. transparentQueue_.SortBackToFront();
  1645. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1646. {
  1647. lightQueues_[i].shadowBatches_.SortFrontToBack();
  1648. lightQueues_[i].litBatches_.SortFrontToBack();
  1649. }
  1650. }
  1651. void View::PrepareInstancingBuffer()
  1652. {
  1653. PROFILE(PrepareInstancingBuffer);
  1654. unsigned totalInstances = 0;
  1655. if (mode_ != RENDER_FORWARD)
  1656. totalInstances += gBufferQueue_.GetNumInstances();
  1657. totalInstances += baseQueue_.GetNumInstances();
  1658. totalInstances += extraQueue_.GetNumInstances();
  1659. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1660. {
  1661. totalInstances += lightQueues_[i].shadowBatches_.GetNumInstances();
  1662. totalInstances += lightQueues_[i].litBatches_.GetNumInstances();
  1663. }
  1664. // If fail to set buffer size, fall back to per-group locking
  1665. if ((totalInstances) && (renderer_->ResizeInstancingBuffer(totalInstances)))
  1666. {
  1667. unsigned freeIndex = 0;
  1668. void* lockedData = renderer_->instancingBuffer_->Lock(0, totalInstances, LOCK_DISCARD);
  1669. if (lockedData)
  1670. {
  1671. if (mode_ != RENDER_FORWARD)
  1672. gBufferQueue_.SetTransforms(lockedData, freeIndex);
  1673. baseQueue_.SetTransforms(lockedData, freeIndex);
  1674. extraQueue_.SetTransforms(lockedData, freeIndex);
  1675. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1676. {
  1677. lightQueues_[i].shadowBatches_.SetTransforms(lockedData, freeIndex);
  1678. lightQueues_[i].litBatches_.SetTransforms(lockedData, freeIndex);
  1679. }
  1680. renderer_->instancingBuffer_->Unlock();
  1681. }
  1682. }
  1683. }
  1684. void View::CalculateShaderParameters()
  1685. {
  1686. Time* time = GetSubsystem<Time>();
  1687. float fogStart = zone_->GetFogStart();
  1688. float fogEnd = zone_->GetFogEnd();
  1689. float fogRange = Max(fogEnd - fogStart, M_EPSILON);
  1690. float farClip = camera_->GetFarClip();
  1691. float nearClip = camera_->GetNearClip();
  1692. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  1693. Vector4 elapsedTime((time->GetTotalMSec() & 0x3fffff) / 1000.0f, 0.0f, 0.0f, 0.0f);
  1694. shaderParameters_.Clear();
  1695. shaderParameters_[VSP_ELAPSEDTIME] = elapsedTime;
  1696. shaderParameters_[PSP_AMBIENTCOLOR] = zone_->GetAmbientColor().ToVector4();
  1697. shaderParameters_[PSP_ELAPSEDTIME] = elapsedTime;
  1698. shaderParameters_[PSP_FOGCOLOR] = zone_->GetFogColor().ToVector4(),
  1699. shaderParameters_[PSP_FOGPARAMS] = fogParams;
  1700. }
  1701. void View::DrawSplitLightToStencil(Camera& camera, Light* light, bool clear)
  1702. {
  1703. graphics_->ClearTransformSources();
  1704. Matrix3x4 view(camera.GetInverseWorldTransform());
  1705. switch (light->GetLightType())
  1706. {
  1707. case LIGHT_SPLITPOINT:
  1708. if (!clear)
  1709. {
  1710. Matrix4 projection(camera.GetProjection());
  1711. const Matrix3x4& model = light->GetVolumeTransform(camera);
  1712. float lightExtent = light->GetVolumeExtent();
  1713. float lightViewDist = (light->GetWorldPosition() - camera.GetWorldPosition()).LengthFast();
  1714. bool drawBackFaces = lightViewDist < (lightExtent + camera.GetNearClip());
  1715. graphics_->SetAlphaTest(false);
  1716. graphics_->SetColorWrite(false);
  1717. graphics_->SetDepthWrite(false);
  1718. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1719. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1720. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1721. graphics_->SetShaderParameter(VSP_MODEL, model);
  1722. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1723. // Draw the faces to stencil which we should draw (where no light has not been rendered yet)
  1724. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1725. renderer_->spotLightGeometry_->Draw(graphics_);
  1726. // Draw the other faces to stencil to mark where we should not draw ("frees up" the pixels for other faces)
  1727. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1728. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_KEEP, OP_KEEP, 1);
  1729. renderer_->spotLightGeometry_->Draw(graphics_);
  1730. // Now set stencil test for rendering the lit geometries (also marks the pixels so that they will not be used again)
  1731. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1732. graphics_->SetColorWrite(true);
  1733. }
  1734. else
  1735. {
  1736. // Clear stencil with a scissored clear operation
  1737. OptimizeLightByScissor(light->GetOriginalLight());
  1738. graphics_->Clear(CLEAR_STENCIL);
  1739. graphics_->SetScissorTest(false);
  1740. graphics_->SetStencilTest(false);
  1741. }
  1742. break;
  1743. case LIGHT_DIRECTIONAL:
  1744. // If light encompasses whole frustum, no drawing to frustum necessary
  1745. if ((light->GetNearSplit() <= camera.GetNearClip()) && (light->GetFarSplit() >= camera.GetFarClip()))
  1746. return;
  1747. else
  1748. {
  1749. if (!clear)
  1750. {
  1751. // Get projection without jitter offset to ensure the whole screen is filled
  1752. Matrix4 projection(camera.GetProjection(false));
  1753. Matrix3x4 nearTransform(light->GetDirLightTransform(camera, true));
  1754. Matrix3x4 farTransform(light->GetDirLightTransform(camera, false));
  1755. graphics_->SetAlphaTest(false);
  1756. graphics_->SetColorWrite(false);
  1757. graphics_->SetDepthWrite(false);
  1758. graphics_->SetCullMode(CULL_NONE);
  1759. // If the split begins at the near plane (first split), draw at split far plane
  1760. if (light->GetNearSplit() <= camera.GetNearClip())
  1761. {
  1762. graphics_->SetDepthTest(CMP_GREATEREQUAL);
  1763. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1764. graphics_->SetShaderParameter(VSP_MODEL, farTransform);
  1765. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1766. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1767. }
  1768. // Otherwise draw at split near plane
  1769. else
  1770. {
  1771. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1772. graphics_->SetShaders(renderer_->stencilVS_, renderer_->stencilPS_);
  1773. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1774. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1775. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_ZERO, OP_ZERO, 1);
  1776. }
  1777. renderer_->dirLightGeometry_->Draw(graphics_);
  1778. graphics_->SetColorWrite(true);
  1779. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 1);
  1780. }
  1781. else
  1782. {
  1783. // Clear the whole stencil
  1784. graphics_->SetScissorTest(false);
  1785. graphics_->Clear(CLEAR_STENCIL);
  1786. graphics_->SetStencilTest(false);
  1787. }
  1788. }
  1789. break;
  1790. }
  1791. }
  1792. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor, bool useLightBuffer, bool disableScissor)
  1793. {
  1794. Texture2D* diffBuffer = 0;
  1795. VertexBuffer* instancingBuffer = 0;
  1796. if (useLightBuffer)
  1797. diffBuffer = graphics_->GetDiffBuffer();
  1798. if (renderer_->GetDynamicInstancing())
  1799. instancingBuffer = renderer_->instancingBuffer_;
  1800. if (disableScissor)
  1801. graphics_->SetScissorTest(false);
  1802. graphics_->SetStencilTest(false);
  1803. // Priority instanced
  1804. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1805. queue.priorityBatchGroups_.End(); ++i)
  1806. {
  1807. const BatchGroup& group = i->second_;
  1808. if ((useLightBuffer) && (!group.light_))
  1809. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1810. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1811. }
  1812. // Priority non-instanced
  1813. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1814. {
  1815. Batch* batch = *i;
  1816. if ((useLightBuffer) && (!batch->light_))
  1817. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1818. batch->Draw(graphics_, shaderParameters_);
  1819. }
  1820. // Non-priority instanced
  1821. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1822. queue.batchGroups_.End(); ++i)
  1823. {
  1824. const BatchGroup& group = i->second_;
  1825. if ((useScissor) && (group.light_))
  1826. OptimizeLightByScissor(group.light_);
  1827. else
  1828. graphics_->SetScissorTest(false);
  1829. if ((useLightBuffer) && (!group.light_))
  1830. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1831. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1832. }
  1833. // Non-priority non-instanced
  1834. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1835. {
  1836. Batch* batch = *i;
  1837. // For the transparent queue, both priority and non-priority batches are copied here, so check the flag
  1838. if ((useScissor) && (batch->light_) && (!batch->hasPriority_))
  1839. OptimizeLightByScissor(batch->light_);
  1840. else
  1841. graphics_->SetScissorTest(false);
  1842. if ((useLightBuffer) && (!batch->light_))
  1843. graphics_->SetTexture(TU_LIGHTBUFFER, diffBuffer);
  1844. batch->Draw(graphics_, shaderParameters_);
  1845. }
  1846. }
  1847. void View::RenderForwardLightBatchQueue(const BatchQueue& queue, Light* light)
  1848. {
  1849. VertexBuffer* instancingBuffer = 0;
  1850. if (renderer_->GetDynamicInstancing())
  1851. instancingBuffer = renderer_->instancingBuffer_;
  1852. graphics_->SetScissorTest(false);
  1853. graphics_->SetStencilTest(false);
  1854. // Priority instanced
  1855. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.priorityBatchGroups_.Begin(); i !=
  1856. queue.priorityBatchGroups_.End(); ++i)
  1857. {
  1858. const BatchGroup& group = i->second_;
  1859. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1860. }
  1861. // Priority non-instanced
  1862. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1863. {
  1864. Batch* batch = *i;
  1865. batch->Draw(graphics_, shaderParameters_);
  1866. }
  1867. // All base passes have been drawn. Optimize at this point by both scissor and stencil
  1868. if (light)
  1869. {
  1870. OptimizeLightByScissor(light);
  1871. LightType type = light->GetLightType();
  1872. if ((type == LIGHT_SPLITPOINT) || (type == LIGHT_DIRECTIONAL))
  1873. DrawSplitLightToStencil(*camera_, light);
  1874. }
  1875. // Non-priority instanced
  1876. for (Map<BatchGroupKey, BatchGroup>::ConstIterator i = queue.batchGroups_.Begin(); i !=
  1877. queue.batchGroups_.End(); ++i)
  1878. {
  1879. const BatchGroup& group = i->second_;
  1880. group.Draw(graphics_, instancingBuffer, shaderParameters_);
  1881. }
  1882. // Non-priority non-instanced
  1883. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1884. {
  1885. Batch* batch = *i;
  1886. batch->Draw(graphics_, shaderParameters_);
  1887. }
  1888. }
  1889. void View::RenderShadowMap(const LightBatchQueue& queue)
  1890. {
  1891. PROFILE(RenderShadowMap);
  1892. Texture2D* shadowMap = queue.light_->GetShadowMap();
  1893. graphics_->ClearLastParameterSources();
  1894. graphics_->SetColorWrite(false);
  1895. graphics_->SetStencilTest(false);
  1896. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1897. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1898. graphics_->SetDepthStencil(shadowMap);
  1899. graphics_->Clear(CLEAR_DEPTH);
  1900. // Set shadow depth bias
  1901. BiasParameters parameters = queue.light_->GetShadowBias();
  1902. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1903. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1904. // However, do not do this for point lights
  1905. if (queue.light_->GetLightType() != LIGHT_SPLITPOINT)
  1906. {
  1907. float zoom = Min(queue.light_->GetShadowCamera()->GetZoom(),
  1908. (float)(shadowMap->GetWidth() - 2) / (float)shadowMap->GetWidth());
  1909. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1910. graphics_->SetScissorTest(true, zoomRect, false);
  1911. }
  1912. else
  1913. graphics_->SetScissorTest(false);
  1914. // Draw instanced and non-instanced shadow casters
  1915. RenderBatchQueue(queue.shadowBatches_, false, false, false);
  1916. graphics_->SetColorWrite(true);
  1917. graphics_->SetDepthBias(0.0f, 0.0f);
  1918. }