View.cpp 74 KB

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