View.cpp 69 KB

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