View.cpp 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279
  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. // In light pre-pass mode, check if this is an opaque object that has converted its lights to per-vertex
  626. // due to overflowing the pixel light count. These need to be skipped as the per-pixel accumulation
  627. // already renders the light
  628. /// \todo Sub-geometries might need different interpretation if opaque & alpha are mixed
  629. if (!j)
  630. drawable->LimitVertexLights(prepass && pass->GetBlendMode() == BLEND_REPLACE);
  631. // The vertex light vector possibly became empty, so re-check
  632. if (!vertexLights.Empty())
  633. {
  634. // Find a vertex light queue. If not found, create new
  635. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  636. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  637. if (i == vertexLightQueues_.End())
  638. {
  639. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  640. i->second_.light_ = 0;
  641. i->second_.shadowMap_ = 0;
  642. i->second_.vertexLights_ = vertexLights;
  643. }
  644. baseBatch.lightQueue_ = &(i->second_);
  645. }
  646. }
  647. if (pass->GetBlendMode() == BLEND_REPLACE)
  648. {
  649. FinalizeBatch(baseBatch, tech, pass);
  650. baseQueue_.AddBatch(baseBatch);
  651. }
  652. else
  653. {
  654. // Transparent batches can not be instanced
  655. FinalizeBatch(baseBatch, tech, pass, false);
  656. alphaQueue_.AddBatch(baseBatch);
  657. }
  658. continue;
  659. }
  660. // If no base pass, finally check for pre-alpha / post-alpha custom passes
  661. pass = tech->GetPass(PASS_PREALPHA);
  662. if (pass)
  663. {
  664. FinalizeBatch(baseBatch, tech, pass);
  665. preAlphaQueue_.AddBatch(baseBatch);
  666. continue;
  667. }
  668. pass = tech->GetPass(PASS_POSTALPHA);
  669. if (pass)
  670. {
  671. // Post-alpha pass is treated similarly as alpha, and is not instanced
  672. FinalizeBatch(baseBatch, tech, pass, false);
  673. postAlphaQueue_.AddBatch(baseBatch);
  674. continue;
  675. }
  676. }
  677. }
  678. }
  679. }
  680. void View::UpdateGeometries()
  681. {
  682. PROFILE(UpdateGeometries);
  683. WorkQueue* queue = GetSubsystem<WorkQueue>();
  684. // Sort batches
  685. {
  686. WorkItem item;
  687. item.workFunction_ = SortBatchQueueFrontToBackWork;
  688. item.start_ = &baseQueue_;
  689. queue->AddWorkItem(item);
  690. item.start_ = &preAlphaQueue_;
  691. queue->AddWorkItem(item);
  692. if (renderer_->GetLightPrepass())
  693. {
  694. item.start_ = &gbufferQueue_;
  695. queue->AddWorkItem(item);
  696. }
  697. item.workFunction_ = SortBatchQueueBackToFrontWork;
  698. item.start_ = &alphaQueue_;
  699. queue->AddWorkItem(item);
  700. item.start_ = &postAlphaQueue_;
  701. queue->AddWorkItem(item);
  702. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  703. {
  704. item.workFunction_ = SortLightQueueWork;
  705. item.start_ = &(*i);
  706. queue->AddWorkItem(item);
  707. }
  708. }
  709. // Update geometries. Split into threaded and non-threaded updates.
  710. {
  711. nonThreadedGeometries_.Clear();
  712. threadedGeometries_.Clear();
  713. for (PODVector<Drawable*>::Iterator i = allGeometries_.Begin(); i != allGeometries_.End(); ++i)
  714. {
  715. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  716. if (type == UPDATE_MAIN_THREAD)
  717. nonThreadedGeometries_.Push(*i);
  718. else if (type == UPDATE_WORKER_THREAD)
  719. threadedGeometries_.Push(*i);
  720. }
  721. if (threadedGeometries_.Size())
  722. {
  723. WorkItem item;
  724. item.workFunction_ = UpdateDrawableGeometriesWork;
  725. item.aux_ = const_cast<FrameInfo*>(&frame_);
  726. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  727. while (start != threadedGeometries_.End())
  728. {
  729. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  730. if (end - start > DRAWABLES_PER_WORK_ITEM)
  731. end = start + DRAWABLES_PER_WORK_ITEM;
  732. item.start_ = &(*start);
  733. item.end_ = &(*end);
  734. queue->AddWorkItem(item);
  735. start = end;
  736. }
  737. }
  738. // While the work queue is processed, update non-threaded geometries
  739. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  740. (*i)->UpdateGeometry(frame_);
  741. }
  742. // Finally ensure all threaded work has completed
  743. queue->Complete();
  744. }
  745. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  746. {
  747. Light* light = lightQueue.light_;
  748. Light* firstLight = drawable->GetFirstLight();
  749. Zone* zone = GetZone(drawable);
  750. // Shadows on transparencies can only be rendered if shadow maps are not reused
  751. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  752. bool hasVertexLights = drawable->GetVertexLights().Size() > 0;
  753. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  754. bool prepass = renderer_->GetLightPrepass();
  755. unsigned numBatches = drawable->GetNumBatches();
  756. for (unsigned i = 0; i < numBatches; ++i)
  757. {
  758. Batch litBatch;
  759. drawable->GetBatch(litBatch, frame_, i);
  760. Technique* tech = GetTechnique(drawable, litBatch.material_);
  761. if (!litBatch.geometry_ || !tech)
  762. continue;
  763. // Do not create pixel lit forward passes for materials that render into the G-buffer
  764. if (prepass && tech->HasPass(PASS_GBUFFER))
  765. continue;
  766. Pass* pass = 0;
  767. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  768. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  769. if (i < 32 && light == firstLight && !hasVertexLights && !hasAmbientGradient && !drawable->HasBasePass(i))
  770. {
  771. pass = tech->GetPass(PASS_LITBASE);
  772. if (pass)
  773. {
  774. litBatch.isBase_ = true;
  775. drawable->SetBasePass(i);
  776. }
  777. }
  778. // If no lit base pass, get ordinary light pass
  779. if (!pass)
  780. pass = tech->GetPass(PASS_LIGHT);
  781. // Skip if material does not receive light at all
  782. if (!pass)
  783. continue;
  784. // Fill the rest of the batch
  785. litBatch.camera_ = camera_;
  786. litBatch.lightQueue_ = &lightQueue;
  787. litBatch.zone_ = GetZone(drawable);
  788. // Check from the ambient pass whether the object is opaque or transparent
  789. Pass* ambientPass = tech->GetPass(PASS_BASE);
  790. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  791. {
  792. FinalizeBatch(litBatch, tech, pass);
  793. lightQueue.litBatches_.AddBatch(litBatch);
  794. }
  795. else
  796. {
  797. // Transparent batches can not be instanced
  798. FinalizeBatch(litBatch, tech, pass, false, allowTransparentShadows);
  799. alphaQueue_.AddBatch(litBatch);
  800. }
  801. }
  802. }
  803. void View::RenderBatchesForward()
  804. {
  805. // Reset the light optimization stencil reference value
  806. lightStencilValue_ = 1;
  807. // If not reusing shadowmaps, render all of them first
  808. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  809. {
  810. PROFILE(RenderShadowMaps);
  811. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  812. {
  813. if (i->shadowMap_)
  814. RenderShadowMap(*i);
  815. }
  816. }
  817. graphics_->SetRenderTarget(0, renderTarget_);
  818. graphics_->SetDepthStencil(depthStencil_);
  819. graphics_->SetViewport(screenRect_);
  820. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, farClipZone_->GetFogColor());
  821. if (!baseQueue_.IsEmpty())
  822. {
  823. // Render opaque object unlit base pass
  824. PROFILE(RenderBase);
  825. RenderBatchQueue(baseQueue_);
  826. }
  827. if (!lightQueues_.Empty())
  828. {
  829. // Render shadow maps + opaque objects' additive lighting
  830. PROFILE(RenderLights);
  831. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  832. {
  833. // If reusing shadowmaps, render each of them before the lit batches
  834. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  835. {
  836. RenderShadowMap(*i);
  837. graphics_->SetRenderTarget(0, renderTarget_);
  838. graphics_->SetDepthStencil(depthStencil_);
  839. graphics_->SetViewport(screenRect_);
  840. }
  841. RenderLightBatchQueue(i->litBatches_, i->light_);
  842. }
  843. }
  844. graphics_->SetScissorTest(false);
  845. graphics_->SetStencilTest(false);
  846. graphics_->SetRenderTarget(0, renderTarget_);
  847. graphics_->SetDepthStencil(depthStencil_);
  848. graphics_->SetViewport(screenRect_);
  849. if (!preAlphaQueue_.IsEmpty())
  850. {
  851. // Render pre-alpha custom pass
  852. PROFILE(RenderPreAlpha);
  853. RenderBatchQueue(preAlphaQueue_);
  854. }
  855. if (!alphaQueue_.IsEmpty())
  856. {
  857. // Render transparent objects (both base passes & additive lighting)
  858. PROFILE(RenderAlpha);
  859. RenderBatchQueue(alphaQueue_, true);
  860. }
  861. if (!postAlphaQueue_.IsEmpty())
  862. {
  863. // Render pre-alpha custom pass
  864. PROFILE(RenderPostAlpha);
  865. RenderBatchQueue(postAlphaQueue_);
  866. }
  867. }
  868. void View::RenderBatchesLightPrepass()
  869. {
  870. if (renderTarget_)
  871. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  872. // If not reusing shadowmaps, render all of them first
  873. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  874. {
  875. PROFILE(RenderShadowMaps);
  876. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  877. {
  878. if (i->shadowMap_)
  879. RenderShadowMap(*i);
  880. }
  881. }
  882. Texture2D* normalBuffer = renderer_->GetNormalBuffer();
  883. Texture2D* depthBuffer = renderer_->GetDepthBuffer();
  884. RenderSurface* depthStencil = 0;
  885. // Hardware depth support: render to RGBA normal buffer and read hardware depth
  886. if (graphics_->GetHardwareDepthSupport())
  887. {
  888. depthStencil = depthBuffer->GetRenderSurface();
  889. graphics_->SetRenderTarget(0, normalBuffer);
  890. }
  891. // No hardware depth support: render to RGBA normal buffer and R32F depth
  892. else
  893. {
  894. graphics_->SetRenderTarget(0, normalBuffer);
  895. graphics_->SetRenderTarget(1, depthBuffer);
  896. }
  897. graphics_->SetDepthStencil(depthStencil);
  898. graphics_->SetViewport(screenRect_);
  899. graphics_->Clear(CLEAR_DEPTH | CLEAR_STENCIL);
  900. if (!gbufferQueue_.IsEmpty())
  901. {
  902. // Render G-buffer batches
  903. PROFILE(RenderGBuffer);
  904. RenderBatchQueue(gbufferQueue_);
  905. }
  906. // Clear the light accumulation buffer
  907. Texture2D* lightBuffer = renderer_->GetLightBuffer();
  908. graphics_->ResetRenderTarget(1);
  909. graphics_->SetRenderTarget(0, lightBuffer);
  910. graphics_->SetDepthStencil(depthStencil);
  911. graphics_->SetViewport(screenRect_);
  912. graphics_->Clear(CLEAR_COLOR);
  913. if (!lightQueues_.Empty())
  914. {
  915. // Render shadow maps + light volumes
  916. PROFILE(RenderLights);
  917. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  918. {
  919. // If reusing shadowmaps, render each of them before the lit batches
  920. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  921. {
  922. RenderShadowMap(*i);
  923. graphics_->SetRenderTarget(0, lightBuffer);
  924. graphics_->SetDepthStencil(depthStencil);
  925. graphics_->SetViewport(screenRect_);
  926. }
  927. graphics_->SetTexture(TU_DEPTHBUFFER, depthBuffer);
  928. graphics_->SetTexture(TU_NORMALBUFFER, normalBuffer);
  929. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  930. {
  931. SetupLightVolumeBatch(i->volumeBatches_[j]);
  932. i->volumeBatches_[j].Draw(graphics_, renderer_);
  933. }
  934. }
  935. }
  936. graphics_->SetTexture(TU_DEPTHBUFFER, 0);
  937. graphics_->SetTexture(TU_NORMALBUFFER, 0);
  938. // Clear destination render target with fog color
  939. graphics_->SetScissorTest(false);
  940. graphics_->SetStencilTest(false);
  941. #ifndef USE_OPENGL
  942. graphics_->SetRenderTarget(0, renderTarget_);
  943. #else
  944. // On OpenGL render the final image to the normal buffer first, as FBO and backbuffer rendering can not be mixed,
  945. // and we need the depth written in the FBO for proper depth testing
  946. graphics_->SetRenderTarget(0, normalBuffer);
  947. #endif
  948. graphics_->SetDepthStencil(depthStencil);
  949. graphics_->SetViewport(screenRect_);
  950. graphics_->Clear(CLEAR_COLOR, farClipZone_->GetFogColor());
  951. if (!baseQueue_.IsEmpty())
  952. {
  953. // Render opaque objects with deferred lighting result
  954. PROFILE(RenderBase);
  955. graphics_->SetTexture(TU_LIGHTBUFFER, lightBuffer);
  956. RenderBatchQueue(baseQueue_);
  957. graphics_->SetTexture(TU_LIGHTBUFFER, 0);
  958. }
  959. if (!preAlphaQueue_.IsEmpty())
  960. {
  961. // Render pre-alpha custom pass
  962. PROFILE(RenderPreAlpha);
  963. RenderBatchQueue(preAlphaQueue_);
  964. }
  965. if (!alphaQueue_.IsEmpty())
  966. {
  967. // Render transparent objects (both base passes & additive lighting)
  968. PROFILE(RenderAlpha);
  969. RenderBatchQueue(alphaQueue_, true);
  970. }
  971. if (!postAlphaQueue_.IsEmpty())
  972. {
  973. // Render pre-alpha custom pass
  974. PROFILE(RenderPostAlpha);
  975. RenderBatchQueue(postAlphaQueue_);
  976. }
  977. // Blit the final image to destination render target on OpenGL
  978. /// \todo Depth is reset to far plane, so geometry drawn after the view (for example debug geometry) can not be depth tested
  979. #ifdef USE_OPENGL
  980. graphics_->SetAlphaTest(false);
  981. graphics_->SetBlendMode(BLEND_REPLACE);
  982. graphics_->SetDepthTest(CMP_ALWAYS);
  983. graphics_->SetDepthWrite(true);
  984. graphics_->SetScissorTest(false);
  985. graphics_->SetStencilTest(false);
  986. graphics_->SetRenderTarget(0, renderTarget_);
  987. graphics_->SetDepthStencil(depthStencil_);
  988. graphics_->SetViewport(screenRect_);
  989. graphics_->SetShaders(renderer_->GetVertexShader("CopyFramebuffer"), renderer_->GetPixelShader("CopyFramebuffer"));
  990. float gBufferWidth = (float)graphics_->GetWidth();
  991. float gBufferHeight = (float)graphics_->GetHeight();
  992. float widthRange = 0.5f * (screenRect_.right_ - screenRect_.left_) / gBufferWidth;
  993. float heightRange = 0.5f * (screenRect_.bottom_ - screenRect_.top_) / gBufferHeight;
  994. Vector4 bufferUVOffset(((float)screenRect_.left_) / gBufferWidth + widthRange,
  995. ((float)screenRect_.top_) / gBufferHeight + heightRange, widthRange, heightRange);
  996. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  997. graphics_->SetTexture(TU_DIFFUSE, normalBuffer);
  998. DrawFullscreenQuad(camera_, false);
  999. #endif
  1000. graphics_->SetViewTexture(0);
  1001. }
  1002. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1003. {
  1004. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1005. float halfViewSize = camera->GetHalfViewSize();
  1006. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1007. Vector3 cameraPos = camera->GetWorldPosition();
  1008. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1009. {
  1010. Drawable* occluder = *i;
  1011. bool erase = false;
  1012. if (!occluder->IsInView(frame_, false))
  1013. occluder->UpdateDistance(frame_);
  1014. // Check occluder's draw distance (in main camera view)
  1015. float maxDistance = occluder->GetDrawDistance();
  1016. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  1017. erase = true;
  1018. else
  1019. {
  1020. // Check that occluder is big enough on the screen
  1021. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1022. float diagonal = (box.max_ - box.min_).LengthFast();
  1023. float compare;
  1024. if (!camera->IsOrthographic())
  1025. compare = diagonal * halfViewSize / occluder->GetDistance();
  1026. else
  1027. compare = diagonal * invOrthoSize;
  1028. if (compare < occluderSizeThreshold_)
  1029. erase = true;
  1030. else
  1031. {
  1032. // Store amount of triangles divided by screen size as a sorting key
  1033. // (best occluders are big and have few triangles)
  1034. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1035. }
  1036. }
  1037. if (erase)
  1038. i = occluders.Erase(i);
  1039. else
  1040. ++i;
  1041. }
  1042. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1043. if (occluders.Size())
  1044. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1045. }
  1046. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1047. {
  1048. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1049. buffer->Clear();
  1050. for (unsigned i = 0; i < occluders.Size(); ++i)
  1051. {
  1052. Drawable* occluder = occluders[i];
  1053. if (i > 0)
  1054. {
  1055. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1056. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1057. continue;
  1058. }
  1059. // Check for running out of triangles
  1060. if (!occluder->DrawOcclusion(buffer))
  1061. break;
  1062. }
  1063. buffer->BuildDepthHierarchy();
  1064. }
  1065. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1066. {
  1067. Light* light = query.light_;
  1068. LightType type = light->GetLightType();
  1069. // Check if light should be shadowed
  1070. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1071. // If shadow distance non-zero, check it
  1072. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1073. isShadowed = false;
  1074. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1075. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1076. query.litGeometries_.Clear();
  1077. switch (type)
  1078. {
  1079. case LIGHT_DIRECTIONAL:
  1080. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1081. {
  1082. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1083. query.litGeometries_.Push(geometries_[i]);
  1084. }
  1085. break;
  1086. case LIGHT_SPOT:
  1087. {
  1088. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1089. octree_->GetDrawables(octreeQuery);
  1090. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1091. {
  1092. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1093. query.litGeometries_.Push(tempDrawables[i]);
  1094. }
  1095. }
  1096. break;
  1097. case LIGHT_POINT:
  1098. {
  1099. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetWorldPosition(), light->GetRange()),
  1100. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1101. octree_->GetDrawables(octreeQuery);
  1102. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1103. {
  1104. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1105. query.litGeometries_.Push(tempDrawables[i]);
  1106. }
  1107. }
  1108. break;
  1109. }
  1110. // If no lit geometries or not shadowed, no need to process shadow cameras
  1111. if (query.litGeometries_.Empty() || !isShadowed)
  1112. {
  1113. query.numSplits_ = 0;
  1114. return;
  1115. }
  1116. // Determine number of shadow cameras and setup their initial positions
  1117. SetupShadowCameras(query);
  1118. // Process each split for shadow casters
  1119. query.shadowCasters_.Clear();
  1120. for (unsigned i = 0; i < query.numSplits_; ++i)
  1121. {
  1122. Camera* shadowCamera = query.shadowCameras_[i];
  1123. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  1124. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1125. // For point light check that the face is visible: if not, can skip the split
  1126. if (type == LIGHT_POINT)
  1127. {
  1128. BoundingBox shadowCameraBox(shadowCameraFrustum);
  1129. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  1130. continue;
  1131. }
  1132. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1133. if (type == LIGHT_DIRECTIONAL)
  1134. {
  1135. if (sceneViewBox_.min_.z_ > query.shadowFarSplits_[i])
  1136. continue;
  1137. if (sceneViewBox_.max_.z_ < query.shadowNearSplits_[i])
  1138. continue;
  1139. }
  1140. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  1141. // lit geometries, whose result still exists in tempDrawables
  1142. if (type != LIGHT_SPOT)
  1143. {
  1144. FrustumOctreeQuery octreeQuery(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1145. camera_->GetViewMask(), true);
  1146. octree_->GetDrawables(octreeQuery);
  1147. }
  1148. // Check which shadow casters actually contribute to the shadowing
  1149. ProcessShadowCasters(query, tempDrawables, i);
  1150. }
  1151. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1152. // only cost has been the shadow camera setup & queries
  1153. if (query.shadowCasters_.Empty())
  1154. query.numSplits_ = 0;
  1155. }
  1156. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1157. {
  1158. Light* light = query.light_;
  1159. Matrix3x4 lightView;
  1160. Matrix4 lightProj;
  1161. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1162. lightView = shadowCamera->GetInverseWorldTransform();
  1163. lightProj = shadowCamera->GetProjection();
  1164. bool dirLight = shadowCamera->IsOrthographic();
  1165. query.shadowCasterBox_[splitIndex].defined_ = false;
  1166. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1167. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1168. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1169. Frustum lightViewFrustum;
  1170. if (!dirLight)
  1171. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  1172. else
  1173. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, query.shadowNearSplits_[splitIndex]),
  1174. Min(sceneViewBox_.max_.z_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1175. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1176. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1177. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1178. return;
  1179. BoundingBox lightViewBox;
  1180. BoundingBox lightProjBox;
  1181. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1182. {
  1183. Drawable* drawable = *i;
  1184. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  1185. // Check for that first
  1186. if (!drawable->GetCastShadows())
  1187. continue;
  1188. // Note: as lights are processed threaded, it is possible a drawable's UpdateDistance() function is called several
  1189. // times. However, this should not cause problems as no scene modification happens at this point.
  1190. if (!drawable->IsInView(frame_, false))
  1191. drawable->UpdateDistance(frame_);
  1192. // Check shadow distance
  1193. float maxShadowDistance = drawable->GetShadowDistance();
  1194. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  1195. continue;
  1196. // Check shadow mask
  1197. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1198. continue;
  1199. // Project shadow caster bounding box to light view space for visibility check
  1200. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1201. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1202. {
  1203. // Merge to shadow caster bounding box and add to the list
  1204. if (dirLight)
  1205. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1206. else
  1207. {
  1208. lightProjBox = lightViewBox.Projected(lightProj);
  1209. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1210. }
  1211. query.shadowCasters_.Push(drawable);
  1212. }
  1213. }
  1214. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1215. }
  1216. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1217. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1218. {
  1219. if (shadowCamera->IsOrthographic())
  1220. {
  1221. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1222. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1223. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1224. }
  1225. else
  1226. {
  1227. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1228. if (drawable->IsInView(frame_))
  1229. return true;
  1230. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1231. Vector3 center = lightViewBox.Center();
  1232. Ray extrusionRay(center, center.Normalized());
  1233. float extrusionDistance = shadowCamera->GetFarClip();
  1234. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  1235. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1236. float sizeFactor = extrusionDistance / originalDistance;
  1237. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1238. // than necessary, so the test will be conservative
  1239. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1240. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1241. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1242. lightViewBox.Merge(extrudedBox);
  1243. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1244. }
  1245. }
  1246. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1247. {
  1248. unsigned width = shadowMap->GetWidth();
  1249. unsigned height = shadowMap->GetHeight();
  1250. int maxCascades = renderer_->GetMaxShadowCascades();
  1251. // Due to instruction count limits, light prepass in SM2.0 can only support up to 3 cascades
  1252. #ifndef USE_OPENGL
  1253. if (renderer_->GetLightPrepass() && !graphics_->GetSM3Support())
  1254. maxCascades = Max(maxCascades, 3);
  1255. #endif
  1256. switch (light->GetLightType())
  1257. {
  1258. case LIGHT_DIRECTIONAL:
  1259. if (maxCascades == 1)
  1260. return IntRect(0, 0, width, height);
  1261. else if (maxCascades == 2)
  1262. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1263. else
  1264. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1265. (splitIndex / 2 + 1) * height / 2);
  1266. case LIGHT_SPOT:
  1267. return IntRect(0, 0, width, height);
  1268. case LIGHT_POINT:
  1269. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1270. (splitIndex / 2 + 1) * height / 3);
  1271. }
  1272. return IntRect();
  1273. }
  1274. void View::OptimizeLightByScissor(Light* light)
  1275. {
  1276. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1277. graphics_->SetScissorTest(true, GetLightScissor(light));
  1278. else
  1279. graphics_->SetScissorTest(false);
  1280. }
  1281. void View::OptimizeLightByStencil(Light* light)
  1282. {
  1283. if (light)
  1284. {
  1285. LightType type = light->GetLightType();
  1286. if (type == LIGHT_DIRECTIONAL)
  1287. {
  1288. graphics_->SetStencilTest(false);
  1289. return;
  1290. }
  1291. Geometry* geometry = renderer_->GetLightGeometry(light);
  1292. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1293. Matrix4 projection(camera_->GetProjection());
  1294. float lightDist;
  1295. if (type == LIGHT_POINT)
  1296. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  1297. else
  1298. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  1299. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1300. if (lightDist < M_EPSILON)
  1301. {
  1302. graphics_->SetStencilTest(false);
  1303. return;
  1304. }
  1305. // If the stencil value has wrapped, clear the whole stencil first
  1306. if (!lightStencilValue_)
  1307. {
  1308. graphics_->Clear(CLEAR_STENCIL);
  1309. lightStencilValue_ = 1;
  1310. }
  1311. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1312. // to avoid clipping the front faces.
  1313. if (lightDist < camera_->GetNearClip() * 2.0f)
  1314. {
  1315. graphics_->SetCullMode(CULL_CW);
  1316. graphics_->SetDepthTest(CMP_GREATER);
  1317. }
  1318. else
  1319. {
  1320. graphics_->SetCullMode(CULL_CCW);
  1321. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1322. }
  1323. graphics_->SetColorWrite(false);
  1324. graphics_->SetDepthWrite(false);
  1325. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1326. graphics_->SetShaders(renderer_->GetStencilVS(), renderer_->GetStencilPS());
  1327. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1328. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera_));
  1329. geometry->Draw(graphics_);
  1330. graphics_->ClearTransformSources();
  1331. graphics_->SetColorWrite(true);
  1332. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1333. // Increase stencil value for next light
  1334. ++lightStencilValue_;
  1335. }
  1336. else
  1337. graphics_->SetStencilTest(false);
  1338. }
  1339. const Rect& View::GetLightScissor(Light* light)
  1340. {
  1341. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  1342. if (i != lightScissorCache_.End())
  1343. return i->second_;
  1344. Matrix3x4 view(camera_->GetInverseWorldTransform());
  1345. Matrix4 projection(camera_->GetProjection());
  1346. switch (light->GetLightType())
  1347. {
  1348. case LIGHT_POINT:
  1349. {
  1350. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1351. return lightScissorCache_[light] = viewBox.Projected(projection);
  1352. }
  1353. case LIGHT_SPOT:
  1354. {
  1355. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1356. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  1357. }
  1358. default:
  1359. return lightScissorCache_[light] = Rect::FULL;
  1360. }
  1361. }
  1362. void View::SetupShadowCameras(LightQueryResult& query)
  1363. {
  1364. Light* light = query.light_;
  1365. LightType type = light->GetLightType();
  1366. int splits = 0;
  1367. if (type == LIGHT_DIRECTIONAL)
  1368. {
  1369. const CascadeParameters& cascade = light->GetShadowCascade();
  1370. float nearSplit = camera_->GetNearClip();
  1371. float farSplit;
  1372. while (splits < renderer_->GetMaxShadowCascades())
  1373. {
  1374. // If split is completely beyond camera far clip, we are done
  1375. if (nearSplit > camera_->GetFarClip())
  1376. break;
  1377. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1378. if (farSplit <= nearSplit)
  1379. break;
  1380. // Setup the shadow camera for the split
  1381. Camera* shadowCamera = renderer_->GetShadowCamera();
  1382. query.shadowCameras_[splits] = shadowCamera;
  1383. query.shadowNearSplits_[splits] = nearSplit;
  1384. query.shadowFarSplits_[splits] = farSplit;
  1385. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1386. nearSplit = farSplit;
  1387. ++splits;
  1388. }
  1389. }
  1390. if (type == LIGHT_SPOT)
  1391. {
  1392. Camera* shadowCamera = renderer_->GetShadowCamera();
  1393. query.shadowCameras_[0] = shadowCamera;
  1394. Node* cameraNode = shadowCamera->GetNode();
  1395. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1396. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1397. shadowCamera->SetFarClip(light->GetRange());
  1398. shadowCamera->SetFov(light->GetFov());
  1399. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1400. splits = 1;
  1401. }
  1402. if (type == LIGHT_POINT)
  1403. {
  1404. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1405. {
  1406. Camera* shadowCamera = renderer_->GetShadowCamera();
  1407. query.shadowCameras_[i] = shadowCamera;
  1408. Node* cameraNode = shadowCamera->GetNode();
  1409. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1410. cameraNode->SetPosition(light->GetWorldPosition());
  1411. cameraNode->SetDirection(directions[i]);
  1412. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1413. shadowCamera->SetFarClip(light->GetRange());
  1414. shadowCamera->SetFov(90.0f);
  1415. shadowCamera->SetAspectRatio(1.0f);
  1416. }
  1417. splits = MAX_CUBEMAP_FACES;
  1418. }
  1419. query.numSplits_ = splits;
  1420. }
  1421. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1422. {
  1423. Node* cameraNode = shadowCamera->GetNode();
  1424. float extrusionDistance = camera_->GetFarClip();
  1425. const FocusParameters& parameters = light->GetShadowFocus();
  1426. // Calculate initial position & rotation
  1427. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1428. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1429. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1430. // Calculate main camera shadowed frustum in light's view space
  1431. farSplit = Min(farSplit, camera_->GetFarClip());
  1432. // Use the scene Z bounds to limit frustum size if applicable
  1433. if (parameters.focus_)
  1434. {
  1435. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1436. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1437. }
  1438. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1439. frustumVolume_.Define(splitFrustum);
  1440. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1441. if (parameters.focus_)
  1442. {
  1443. BoundingBox litGeometriesBox;
  1444. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1445. {
  1446. // Skip "infinite" objects like the skybox
  1447. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1448. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1449. {
  1450. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1451. (GetLightMask(geometries_[i]) & light->GetLightMask()))
  1452. litGeometriesBox.Merge(geomBox);
  1453. }
  1454. }
  1455. if (litGeometriesBox.defined_)
  1456. {
  1457. frustumVolume_.Clip(litGeometriesBox);
  1458. // If volume became empty, restore it to avoid zero size
  1459. if (frustumVolume_.Empty())
  1460. frustumVolume_.Define(splitFrustum);
  1461. }
  1462. }
  1463. // Transform frustum volume to light space
  1464. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1465. frustumVolume_.Transform(lightView);
  1466. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1467. BoundingBox shadowBox;
  1468. if (!parameters.nonUniform_)
  1469. shadowBox.Define(Sphere(frustumVolume_));
  1470. else
  1471. shadowBox.Define(frustumVolume_);
  1472. shadowCamera->SetOrthographic(true);
  1473. shadowCamera->SetAspectRatio(1.0f);
  1474. shadowCamera->SetNearClip(0.0f);
  1475. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1476. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1477. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1478. }
  1479. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1480. const BoundingBox& shadowCasterBox)
  1481. {
  1482. const FocusParameters& parameters = light->GetShadowFocus();
  1483. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1484. LightType type = light->GetLightType();
  1485. if (type == LIGHT_DIRECTIONAL)
  1486. {
  1487. BoundingBox shadowBox;
  1488. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1489. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1490. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1491. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1492. // Requantize and snap to shadow map texels
  1493. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1494. }
  1495. if (type == LIGHT_SPOT)
  1496. {
  1497. if (parameters.focus_)
  1498. {
  1499. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1500. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1501. float viewSize = Max(viewSizeX, viewSizeY);
  1502. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1503. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1504. float quantize = parameters.quantize_ * invOrthoSize;
  1505. float minView = parameters.minView_ * invOrthoSize;
  1506. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1507. if (viewSize < 1.0f)
  1508. shadowCamera->SetZoom(1.0f / viewSize);
  1509. }
  1510. }
  1511. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1512. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1513. if (shadowCamera->GetZoom() >= 1.0f)
  1514. {
  1515. if (light->GetLightType() != LIGHT_POINT)
  1516. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1517. else
  1518. {
  1519. #ifdef USE_OPENGL
  1520. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1521. #else
  1522. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1523. #endif
  1524. }
  1525. }
  1526. }
  1527. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1528. const BoundingBox& viewBox)
  1529. {
  1530. Node* cameraNode = shadowCamera->GetNode();
  1531. const FocusParameters& parameters = light->GetShadowFocus();
  1532. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1533. float minX = viewBox.min_.x_;
  1534. float minY = viewBox.min_.y_;
  1535. float maxX = viewBox.max_.x_;
  1536. float maxY = viewBox.max_.y_;
  1537. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1538. Vector2 viewSize(maxX - minX, maxY - minY);
  1539. // Quantize size to reduce swimming
  1540. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1541. if (parameters.nonUniform_)
  1542. {
  1543. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1544. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1545. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1546. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1547. }
  1548. else if (parameters.focus_)
  1549. {
  1550. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1551. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1552. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1553. viewSize.y_ = viewSize.x_;
  1554. }
  1555. shadowCamera->SetOrthoSize(viewSize);
  1556. // Center shadow camera to the view space bounding box
  1557. Vector3 pos(shadowCamera->GetWorldPosition());
  1558. Quaternion rot(shadowCamera->GetWorldRotation());
  1559. Vector3 adjust(center.x_, center.y_, 0.0f);
  1560. cameraNode->Translate(rot * adjust);
  1561. // If the shadow map viewport is known, snap to whole texels
  1562. if (shadowMapWidth > 0.0f)
  1563. {
  1564. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1565. // Take into account that shadow map border will not be used
  1566. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1567. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1568. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1569. cameraNode->Translate(rot * snap);
  1570. }
  1571. }
  1572. void View::FindZone(Drawable* drawable, unsigned threadIndex)
  1573. {
  1574. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1575. int bestPriority = M_MIN_INT;
  1576. Zone* newZone = 0;
  1577. // If bounding box center is in view, can use the visible zones. Else must query via the octree
  1578. if (frustum_.IsInside(center))
  1579. {
  1580. // First check if the last zone remains a conclusive result
  1581. Zone* lastZone = drawable->GetLastZone();
  1582. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) &&
  1583. lastZone->GetPriority() >= highestZonePriority_)
  1584. newZone = lastZone;
  1585. else
  1586. {
  1587. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1588. {
  1589. int priority = (*i)->GetPriority();
  1590. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1591. {
  1592. newZone = *i;
  1593. bestPriority = priority;
  1594. }
  1595. }
  1596. }
  1597. }
  1598. else
  1599. {
  1600. PODVector<Zone*>& tempZones = tempZones_[threadIndex];
  1601. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(tempZones), center, DRAWABLE_ZONE);
  1602. octree_->GetDrawables(query);
  1603. bestPriority = M_MIN_INT;
  1604. for (PODVector<Zone*>::Iterator i = tempZones.Begin(); i != tempZones.End(); ++i)
  1605. {
  1606. int priority = (*i)->GetPriority();
  1607. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1608. {
  1609. newZone = *i;
  1610. bestPriority = priority;
  1611. }
  1612. }
  1613. }
  1614. drawable->SetZone(newZone);
  1615. }
  1616. Zone* View::GetZone(Drawable* drawable)
  1617. {
  1618. if (cameraZoneOverride_)
  1619. return cameraZone_;
  1620. Zone* drawableZone = drawable->GetZone();
  1621. return drawableZone ? drawableZone : cameraZone_;
  1622. }
  1623. unsigned View::GetLightMask(Drawable* drawable)
  1624. {
  1625. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1626. }
  1627. unsigned View::GetShadowMask(Drawable* drawable)
  1628. {
  1629. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  1630. }
  1631. unsigned long long View::GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  1632. {
  1633. unsigned long long hash = 0;
  1634. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  1635. hash += (unsigned long long)(*i);
  1636. return hash;
  1637. }
  1638. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1639. {
  1640. if (!material)
  1641. material = renderer_->GetDefaultMaterial();
  1642. if (!material)
  1643. return 0;
  1644. float lodDistance = drawable->GetLodDistance();
  1645. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1646. if (techniques.Empty())
  1647. return 0;
  1648. // Check for suitable technique. Techniques should be ordered like this:
  1649. // Most distant & highest quality
  1650. // Most distant & lowest quality
  1651. // Second most distant & highest quality
  1652. // ...
  1653. for (unsigned i = 0; i < techniques.Size(); ++i)
  1654. {
  1655. const TechniqueEntry& entry = techniques[i];
  1656. Technique* technique = entry.technique_;
  1657. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1658. continue;
  1659. if (lodDistance >= entry.lodDistance_)
  1660. return technique;
  1661. }
  1662. // If no suitable technique found, fallback to the last
  1663. return techniques.Back().technique_;
  1664. }
  1665. void View::CheckMaterialForAuxView(Material* material)
  1666. {
  1667. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1668. for (unsigned i = 0; i < textures.Size(); ++i)
  1669. {
  1670. // Have to check cube & 2D textures separately
  1671. Texture* texture = textures[i];
  1672. if (texture)
  1673. {
  1674. if (texture->GetType() == Texture2D::GetTypeStatic())
  1675. {
  1676. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1677. RenderSurface* target = tex2D->GetRenderSurface();
  1678. if (target)
  1679. {
  1680. const Viewport& viewport = target->GetViewport();
  1681. if (viewport.scene_ && viewport.camera_)
  1682. renderer_->AddView(target, viewport);
  1683. }
  1684. }
  1685. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1686. {
  1687. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1688. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1689. {
  1690. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1691. if (target)
  1692. {
  1693. const Viewport& viewport = target->GetViewport();
  1694. if (viewport.scene_ && viewport.camera_)
  1695. renderer_->AddView(target, viewport);
  1696. }
  1697. }
  1698. }
  1699. }
  1700. }
  1701. // Set frame number so that we can early-out next time we come across this material on the same frame
  1702. material->MarkForAuxView(frame_.frameNumber_);
  1703. }
  1704. void View::FinalizeBatch(Batch& batch, Technique* tech, Pass* pass, bool allowInstancing, bool allowShadows)
  1705. {
  1706. // Convert to instanced if possible
  1707. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && !batch.shaderData_ && !batch.overrideView_)
  1708. batch.geometryType_ = GEOM_INSTANCED;
  1709. batch.pass_ = pass;
  1710. renderer_->SetBatchShaders(batch, tech, pass, allowShadows);
  1711. batch.CalculateSortKey();
  1712. }
  1713. void View::PrepareInstancingBuffer()
  1714. {
  1715. PROFILE(PrepareInstancingBuffer);
  1716. unsigned totalInstances = 0;
  1717. bool prepass = renderer_->GetLightPrepass();
  1718. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1719. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  1720. if (prepass)
  1721. totalInstances += gbufferQueue_.GetNumInstances(renderer_);
  1722. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1723. {
  1724. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  1725. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1726. totalInstances += i->litBatches_.GetNumInstances(renderer_);
  1727. }
  1728. // If fail to set buffer size, fall back to per-group locking
  1729. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1730. {
  1731. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1732. unsigned freeIndex = 0;
  1733. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1734. if (lockedData)
  1735. {
  1736. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1737. preAlphaQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1738. if (prepass)
  1739. gbufferQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1740. for (List<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1741. {
  1742. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  1743. i->shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1744. i->litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1745. }
  1746. instancingBuffer->Unlock();
  1747. }
  1748. }
  1749. }
  1750. void View::SetupLightVolumeBatch(Batch& batch)
  1751. {
  1752. Light* light = batch.lightQueue_->light_;
  1753. LightType type = light->GetLightType();
  1754. float lightDist;
  1755. graphics_->SetAlphaTest(false);
  1756. graphics_->SetBlendMode(BLEND_ADD);
  1757. graphics_->SetDepthWrite(false);
  1758. if (type != LIGHT_DIRECTIONAL)
  1759. {
  1760. if (type == LIGHT_POINT)
  1761. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  1762. else
  1763. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  1764. // Draw front faces if not inside light volume
  1765. if (lightDist < camera_->GetNearClip() * 2.0f)
  1766. {
  1767. graphics_->SetCullMode(CULL_CW);
  1768. graphics_->SetDepthTest(CMP_GREATER);
  1769. }
  1770. else
  1771. {
  1772. graphics_->SetCullMode(CULL_CCW);
  1773. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1774. }
  1775. }
  1776. else
  1777. {
  1778. graphics_->SetCullMode(CULL_NONE);
  1779. graphics_->SetDepthTest(CMP_ALWAYS);
  1780. }
  1781. graphics_->SetScissorTest(false);
  1782. graphics_->SetStencilTest(true, CMP_LESS, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  1783. }
  1784. void View::DrawFullscreenQuad(Camera* camera, bool nearQuad)
  1785. {
  1786. Light quadDirLight(context_);
  1787. quadDirLight.SetLightType(LIGHT_DIRECTIONAL);
  1788. Matrix3x4 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  1789. graphics_->SetCullMode(CULL_NONE);
  1790. graphics_->SetShaderParameter(VSP_MODEL, model);
  1791. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera->GetProjection());
  1792. graphics_->ClearTransformSources();
  1793. renderer_->GetLightGeometry(&quadDirLight)->Draw(graphics_);
  1794. }
  1795. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1796. {
  1797. graphics_->SetScissorTest(false);
  1798. // During G-buffer rendering, mark opaque pixels to stencil buffer
  1799. bool isGBuffer = &queue == &gbufferQueue_;
  1800. if (!isGBuffer)
  1801. graphics_->SetStencilTest(false);
  1802. // Base instanced
  1803. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBaseBatchGroups_.Begin(); i !=
  1804. queue.sortedBaseBatchGroups_.End(); ++i)
  1805. {
  1806. BatchGroup* group = *i;
  1807. if (isGBuffer)
  1808. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  1809. group->Draw(graphics_, renderer_);
  1810. }
  1811. // Base non-instanced
  1812. for (PODVector<Batch*>::ConstIterator i = queue.sortedBaseBatches_.Begin(); i != queue.sortedBaseBatches_.End(); ++i)
  1813. {
  1814. Batch* batch = *i;
  1815. if (isGBuffer)
  1816. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  1817. batch->Draw(graphics_, renderer_);
  1818. }
  1819. // Non-base instanced
  1820. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1821. {
  1822. BatchGroup* group = *i;
  1823. if (useScissor && group->lightQueue_)
  1824. OptimizeLightByScissor(group->lightQueue_->light_);
  1825. if (isGBuffer)
  1826. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
  1827. group->Draw(graphics_, renderer_);
  1828. }
  1829. // Non-base non-instanced
  1830. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1831. {
  1832. Batch* batch = *i;
  1833. if (useScissor)
  1834. {
  1835. if (!batch->isBase_ && batch->lightQueue_)
  1836. OptimizeLightByScissor(batch->lightQueue_->light_);
  1837. else
  1838. graphics_->SetScissorTest(false);
  1839. }
  1840. if (isGBuffer)
  1841. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, batch->lightMask_);
  1842. batch->Draw(graphics_, renderer_);
  1843. }
  1844. }
  1845. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1846. {
  1847. graphics_->SetScissorTest(false);
  1848. graphics_->SetStencilTest(false);
  1849. // Base instanced
  1850. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBaseBatchGroups_.Begin(); i !=
  1851. queue.sortedBaseBatchGroups_.End(); ++i)
  1852. {
  1853. BatchGroup* group = *i;
  1854. group->Draw(graphics_, renderer_);
  1855. }
  1856. // Base non-instanced
  1857. for (PODVector<Batch*>::ConstIterator i = queue.sortedBaseBatches_.Begin(); i != queue.sortedBaseBatches_.End(); ++i)
  1858. {
  1859. Batch* batch = *i;
  1860. batch->Draw(graphics_, renderer_);
  1861. }
  1862. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1863. OptimizeLightByStencil(light);
  1864. OptimizeLightByScissor(light);
  1865. // Non-base instanced
  1866. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1867. {
  1868. BatchGroup* group = *i;
  1869. group->Draw(graphics_, renderer_);
  1870. }
  1871. // Non-base non-instanced
  1872. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1873. {
  1874. Batch* batch = *i;
  1875. batch->Draw(graphics_, renderer_);
  1876. }
  1877. }
  1878. void View::RenderShadowMap(const LightBatchQueue& queue)
  1879. {
  1880. PROFILE(RenderShadowMap);
  1881. Texture2D* shadowMap = queue.shadowMap_;
  1882. graphics_->SetStencilTest(false);
  1883. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1884. if (!graphics_->GetFallback())
  1885. {
  1886. graphics_->SetColorWrite(false);
  1887. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1888. graphics_->SetDepthStencil(shadowMap);
  1889. graphics_->Clear(CLEAR_DEPTH);
  1890. }
  1891. else
  1892. {
  1893. graphics_->SetColorWrite(true);
  1894. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1895. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1896. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1897. }
  1898. // Set shadow depth bias
  1899. BiasParameters parameters = queue.light_->GetShadowBias();
  1900. // Adjust the light's constant depth bias according to global shadow map resolution
  1901. /// \todo Should remove this adjustment and find a more flexible solution
  1902. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1903. if (shadowMapSize <= 512)
  1904. parameters.constantBias_ *= 2.0f;
  1905. else if (shadowMapSize >= 2048)
  1906. parameters.constantBias_ *= 0.5f;
  1907. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1908. // Render each of the splits
  1909. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1910. {
  1911. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1912. if (!shadowQueue.shadowBatches_.IsEmpty())
  1913. {
  1914. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1915. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1916. // However, do not do this for point lights, which need to render continuously across cube faces
  1917. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1918. if (queue.light_->GetLightType() != LIGHT_POINT)
  1919. {
  1920. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1921. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1922. graphics_->SetScissorTest(true, zoomRect, false);
  1923. }
  1924. else
  1925. graphics_->SetScissorTest(false);
  1926. // Draw instanced and non-instanced shadow casters
  1927. RenderBatchQueue(shadowQueue.shadowBatches_);
  1928. }
  1929. }
  1930. graphics_->SetColorWrite(true);
  1931. graphics_->SetDepthBias(0.0f, 0.0f);
  1932. }