View.cpp 67 KB

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