View.cpp 86 KB

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