View.cpp 90 KB

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