View.cpp 72 KB

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