View.cpp 94 KB

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