View.cpp 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "DebugRenderer.h"
  25. #include "FileSystem.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "Renderer.h"
  34. #include "RenderPath.h"
  35. #include "ResourceCache.h"
  36. #include "Profiler.h"
  37. #include "Scene.h"
  38. #include "ShaderVariation.h"
  39. #include "Skybox.h"
  40. #include "Technique.h"
  41. #include "Texture2D.h"
  42. #include "Texture3D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "WorkQueue.h"
  47. #include "DebugNew.h"
  48. namespace Urho3D
  49. {
  50. static const Vector3* directions[] =
  51. {
  52. &Vector3::RIGHT,
  53. &Vector3::LEFT,
  54. &Vector3::UP,
  55. &Vector3::DOWN,
  56. &Vector3::FORWARD,
  57. &Vector3::BACK
  58. };
  59. static const float LIGHT_INTENSITY_THRESHOLD = 0.003f;
  60. /// %Frustum octree query for shadowcasters.
  61. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  62. {
  63. public:
  64. /// Construct with frustum and query parameters.
  65. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  66. unsigned viewMask = DEFAULT_VIEWMASK) :
  67. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  68. {
  69. }
  70. /// Intersection test for drawables.
  71. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  72. {
  73. while (start != end)
  74. {
  75. Drawable* drawable = *start++;
  76. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  77. (drawable->GetViewMask() & viewMask_))
  78. {
  79. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  80. result_.Push(drawable);
  81. }
  82. }
  83. }
  84. };
  85. /// %Frustum octree query for zones and occluders.
  86. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  87. {
  88. public:
  89. /// Construct with frustum and query parameters.
  90. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  91. unsigned viewMask = DEFAULT_VIEWMASK) :
  92. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  93. {
  94. }
  95. /// Intersection test for drawables.
  96. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  97. {
  98. while (start != end)
  99. {
  100. Drawable* drawable = *start++;
  101. unsigned char flags = drawable->GetDrawableFlags();
  102. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) && (drawable->GetViewMask() &
  103. viewMask_))
  104. {
  105. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  106. result_.Push(drawable);
  107. }
  108. }
  109. }
  110. };
  111. /// %Frustum octree query with occlusion.
  112. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  113. {
  114. public:
  115. /// Construct with frustum, occlusion buffer and query parameters.
  116. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  117. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  118. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  119. buffer_(buffer)
  120. {
  121. }
  122. /// Intersection test for an octant.
  123. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  124. {
  125. if (inside)
  126. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  127. else
  128. {
  129. Intersection result = frustum_.IsInside(box);
  130. if (result != OUTSIDE && !buffer_->IsVisible(box))
  131. result = OUTSIDE;
  132. return result;
  133. }
  134. }
  135. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  136. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  137. {
  138. while (start != end)
  139. {
  140. Drawable* drawable = *start++;
  141. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  142. {
  143. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  144. result_.Push(drawable);
  145. }
  146. }
  147. }
  148. /// Occlusion buffer.
  149. OcclusionBuffer* buffer_;
  150. };
  151. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  152. {
  153. View* view = reinterpret_cast<View*>(item->aux_);
  154. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  155. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  156. OcclusionBuffer* buffer = view->occlusionBuffer_;
  157. const Matrix3x4& viewMatrix = view->camera_->GetView();
  158. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  159. Vector3 absViewZ = viewZ.Abs();
  160. unsigned cameraViewMask = view->camera_->GetViewMask();
  161. bool cameraZoneOverride = view->cameraZoneOverride_;
  162. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  163. while (start != end)
  164. {
  165. Drawable* drawable = *start++;
  166. bool batchesUpdated = false;
  167. // If draw distance non-zero, update and check it
  168. float maxDistance = drawable->GetDrawDistance();
  169. if (maxDistance > 0.0f)
  170. {
  171. drawable->UpdateBatches(view->frame_);
  172. batchesUpdated = true;
  173. if (drawable->GetDistance() > maxDistance)
  174. continue;
  175. }
  176. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  177. {
  178. if (!batchesUpdated)
  179. drawable->UpdateBatches(view->frame_);
  180. drawable->MarkInView(view->frame_);
  181. // For geometries, find zone, clear lights and calculate view space Z range
  182. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  183. {
  184. Zone* drawableZone = drawable->GetZone();
  185. if ((!drawableZone || (drawableZone->GetViewMask() & cameraViewMask) == 0) && !cameraZoneOverride)
  186. view->FindZone(drawable);
  187. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  188. Vector3 center = geomBox.Center();
  189. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  190. Vector3 edge = geomBox.Size() * 0.5f;
  191. float viewEdgeZ = absViewZ.DotProduct(edge);
  192. float minZ = viewCenterZ - viewEdgeZ;
  193. float maxZ = viewCenterZ + viewEdgeZ;
  194. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  195. drawable->ClearLights();
  196. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  197. if (drawable->GetType() != Skybox::GetTypeStatic())
  198. {
  199. result.minZ_ = Min(result.minZ_, minZ);
  200. result.maxZ_ = Max(result.maxZ_, maxZ);
  201. }
  202. result.geometries_.Push(drawable);
  203. }
  204. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  205. {
  206. Light* light = static_cast<Light*>(drawable);
  207. // Skip lights which are so dim that they can not contribute to a rendertarget
  208. if (light->GetColor().SumRGB() > LIGHT_INTENSITY_THRESHOLD)
  209. result.lights_.Push(light);
  210. }
  211. }
  212. }
  213. }
  214. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  215. {
  216. View* view = reinterpret_cast<View*>(item->aux_);
  217. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  218. view->ProcessLight(*query, threadIndex);
  219. }
  220. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  221. {
  222. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  223. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  224. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  225. while (start != end)
  226. {
  227. Drawable* drawable = *start++;
  228. drawable->UpdateGeometry(frame);
  229. }
  230. }
  231. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  232. {
  233. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  234. queue->SortFrontToBack();
  235. }
  236. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  237. {
  238. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  239. queue->SortBackToFront();
  240. }
  241. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  242. {
  243. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  244. start->litBaseBatches_.SortFrontToBack();
  245. start->litBatches_.SortFrontToBack();
  246. }
  247. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  248. {
  249. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  250. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  251. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  252. }
  253. View::View(Context* context) :
  254. Object(context),
  255. graphics_(GetSubsystem<Graphics>()),
  256. renderer_(GetSubsystem<Renderer>()),
  257. scene_(0),
  258. octree_(0),
  259. camera_(0),
  260. cameraZone_(0),
  261. farClipZone_(0),
  262. renderTarget_(0),
  263. substituteRenderTarget_(0)
  264. {
  265. // Create octree query and scene results vector for each thread
  266. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  267. tempDrawables_.Resize(numThreads);
  268. sceneResults_.Resize(numThreads);
  269. frame_.camera_ = 0;
  270. }
  271. View::~View()
  272. {
  273. }
  274. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  275. {
  276. Scene* scene = viewport->GetScene();
  277. Camera* camera = viewport->GetCamera();
  278. if (!scene || !camera || !camera->IsEnabledEffective())
  279. return false;
  280. // If scene is loading asynchronously, it is incomplete and should not be rendered
  281. if (scene->IsAsyncLoading())
  282. return false;
  283. Octree* octree = scene->GetComponent<Octree>();
  284. if (!octree)
  285. return false;
  286. // Do not accept view if camera projection is illegal
  287. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  288. if (!camera->IsProjectionValid())
  289. return false;
  290. scene_ = scene;
  291. octree_ = octree;
  292. camera_ = camera;
  293. cameraNode_ = camera->GetNode();
  294. renderTarget_ = renderTarget;
  295. renderPath_ = viewport->GetRenderPath();
  296. gBufferPassName_ = StringHash();
  297. basePassName_ = PASS_BASE;
  298. alphaPassName_ = PASS_ALPHA;
  299. lightPassName_ = PASS_LIGHT;
  300. litBasePassName_ = PASS_LITBASE;
  301. litAlphaPassName_ = PASS_LITALPHA;
  302. // Make sure that all necessary batch queues exist
  303. scenePasses_.Clear();
  304. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  305. {
  306. const RenderPathCommand& command = renderPath_->commands_[i];
  307. if (!command.enabled_)
  308. continue;
  309. if (command.type_ == CMD_SCENEPASS)
  310. {
  311. ScenePassInfo info;
  312. info.pass_ = command.pass_;
  313. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  314. info.markToStencil_ = command.markToStencil_;
  315. info.vertexLights_ = command.vertexLights_;
  316. // Check scenepass metadata for defining custom passes which interact with lighting
  317. if (!command.metadata_.Empty())
  318. {
  319. if (command.metadata_ == "gbuffer")
  320. gBufferPassName_ = command.pass_;
  321. else if (command.metadata_ == "base" && command.pass_ != "base")
  322. {
  323. basePassName_ = command.pass_;
  324. litBasePassName_ = "lit" + command.pass_;
  325. }
  326. else if (command.metadata_ == "alpha" && command.pass_ != "alpha")
  327. {
  328. alphaPassName_ = command.pass_;
  329. litAlphaPassName_ = "lit" + command.pass_;
  330. }
  331. }
  332. HashMap<StringHash, BatchQueue>::Iterator j = batchQueues_.Find(command.pass_);
  333. if (j == batchQueues_.End())
  334. j = batchQueues_.Insert(Pair<StringHash, BatchQueue>(command.pass_, BatchQueue()));
  335. info.batchQueue_ = &j->second_;
  336. scenePasses_.Push(info);
  337. }
  338. // Allow a custom forward light pass
  339. else if (command.type_ == CMD_FORWARDLIGHTS && !command.pass_.Empty())
  340. lightPassName_ = command.pass_;
  341. }
  342. // Go through commands to check for deferred rendering and other flags
  343. deferred_ = false;
  344. deferredAmbient_ = false;
  345. useLitBase_ = false;
  346. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  347. {
  348. const RenderPathCommand& command = renderPath_->commands_[i];
  349. if (!command.enabled_)
  350. continue;
  351. // Check if ambient pass and G-buffer rendering happens at the same time
  352. if (command.type_ == CMD_SCENEPASS && command.outputNames_.Size() > 1)
  353. {
  354. if (CheckViewportWrite(command))
  355. deferredAmbient_ = true;
  356. }
  357. else if (command.type_ == CMD_LIGHTVOLUMES)
  358. {
  359. lightVolumeVSName_ = command.vertexShaderName_;
  360. lightVolumePSName_ = command.pixelShaderName_;
  361. deferred_ = true;
  362. }
  363. else if (command.type_ == CMD_FORWARDLIGHTS)
  364. useLitBase_ = command.useLitBase_;
  365. }
  366. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  367. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  368. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  369. const IntRect& rect = viewport->GetRect();
  370. if (rect != IntRect::ZERO)
  371. {
  372. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  373. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  374. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  375. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  376. }
  377. else
  378. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  379. viewSize_ = viewRect_.Size();
  380. rtSize_ = IntVector2(rtWidth, rtHeight);
  381. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  382. #ifdef USE_OPENGL
  383. if (renderTarget_)
  384. {
  385. viewRect_.bottom_ = rtSize_.y_ - viewRect_.top_;
  386. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  387. }
  388. #endif
  389. drawShadows_ = renderer_->GetDrawShadows();
  390. materialQuality_ = renderer_->GetMaterialQuality();
  391. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  392. minInstances_ = renderer_->GetMinInstances();
  393. // Set possible quality overrides from the camera
  394. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  395. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  396. materialQuality_ = QUALITY_LOW;
  397. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  398. drawShadows_ = false;
  399. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  400. maxOccluderTriangles_ = 0;
  401. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  402. if (viewSize_.y_ > viewSize_.x_ * 4)
  403. maxOccluderTriangles_ = 0;
  404. return true;
  405. }
  406. void View::Update(const FrameInfo& frame)
  407. {
  408. if (!camera_ || !octree_)
  409. return;
  410. frame_.camera_ = camera_;
  411. frame_.timeStep_ = frame.timeStep_;
  412. frame_.frameNumber_ = frame.frameNumber_;
  413. frame_.viewSize_ = viewSize_;
  414. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  415. // Clear buffers, geometry, light, occluder & batch list
  416. renderTargets_.Clear();
  417. geometries_.Clear();
  418. shadowGeometries_.Clear();
  419. lights_.Clear();
  420. zones_.Clear();
  421. occluders_.Clear();
  422. vertexLightQueues_.Clear();
  423. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  424. i->second_.Clear(maxSortedInstances);
  425. // Set automatic aspect ratio if required
  426. if (camera_->GetAutoAspectRatio())
  427. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  428. GetDrawables();
  429. GetBatches();
  430. }
  431. void View::Render()
  432. {
  433. if (!octree_ || !camera_)
  434. return;
  435. // Actually update geometry data now
  436. UpdateGeometries();
  437. // Allocate screen buffers as necessary
  438. AllocateScreenBuffers();
  439. // Forget parameter sources from the previous view
  440. graphics_->ClearParameterSources();
  441. // If stream offset is supported, write all instance transforms to a single large buffer
  442. // Else we must lock the instance buffer for each batch group
  443. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  444. PrepareInstancingBuffer();
  445. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  446. // again to ensure correct projection will be used
  447. if (camera_->GetAutoAspectRatio())
  448. camera_->SetAspectRatio((float)(viewSize_.x_) / (float)(viewSize_.y_));
  449. // Bind the face selection and indirection cube maps for point light shadows
  450. if (renderer_->GetDrawShadows())
  451. {
  452. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  453. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  454. }
  455. if (renderTarget_)
  456. {
  457. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  458. // as a render texture produced on Direct3D9
  459. #ifdef USE_OPENGL
  460. camera_->SetFlipVertical(true);
  461. #endif
  462. }
  463. // Render
  464. ExecuteRenderPathCommands();
  465. #ifdef USE_OPENGL
  466. camera_->SetFlipVertical(false);
  467. #endif
  468. graphics_->SetDepthBias(0.0f, 0.0f);
  469. graphics_->SetScissorTest(false);
  470. graphics_->SetStencilTest(false);
  471. graphics_->ResetStreamFrequencies();
  472. // Run framebuffer blitting if necessary
  473. if (currentRenderTarget_ != renderTarget_)
  474. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()), renderTarget_, true);
  475. // If this is a main view, draw the associated debug geometry now
  476. if (!renderTarget_)
  477. {
  478. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  479. if (debug)
  480. {
  481. debug->SetView(camera_);
  482. debug->Render();
  483. }
  484. }
  485. // "Forget" the scene, camera, octree and zone after rendering
  486. scene_ = 0;
  487. camera_ = 0;
  488. octree_ = 0;
  489. cameraZone_ = 0;
  490. farClipZone_ = 0;
  491. occlusionBuffer_ = 0;
  492. frame_.camera_ = 0;
  493. }
  494. Graphics* View::GetGraphics() const
  495. {
  496. return graphics_;
  497. }
  498. Renderer* View::GetRenderer() const
  499. {
  500. return renderer_;
  501. }
  502. void View::GetDrawables()
  503. {
  504. PROFILE(GetDrawables);
  505. WorkQueue* queue = GetSubsystem<WorkQueue>();
  506. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  507. // Get zones and occluders first
  508. {
  509. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, camera_->GetViewMask());
  510. octree_->GetDrawables(query);
  511. }
  512. highestZonePriority_ = M_MIN_INT;
  513. int bestPriority = M_MIN_INT;
  514. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  515. // Get default zone first in case we do not have zones defined
  516. Zone* defaultZone = renderer_->GetDefaultZone();
  517. cameraZone_ = farClipZone_ = defaultZone;
  518. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  519. {
  520. Drawable* drawable = *i;
  521. unsigned char flags = drawable->GetDrawableFlags();
  522. if (flags & DRAWABLE_ZONE)
  523. {
  524. Zone* zone = static_cast<Zone*>(drawable);
  525. zones_.Push(zone);
  526. int priority = zone->GetPriority();
  527. if (priority > highestZonePriority_)
  528. highestZonePriority_ = priority;
  529. if (priority > bestPriority && zone->IsInside(cameraPos))
  530. {
  531. cameraZone_ = zone;
  532. bestPriority = priority;
  533. }
  534. }
  535. else
  536. occluders_.Push(drawable);
  537. }
  538. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  539. cameraZoneOverride_ = cameraZone_->GetOverride();
  540. if (!cameraZoneOverride_)
  541. {
  542. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  543. bestPriority = M_MIN_INT;
  544. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  545. {
  546. int priority = (*i)->GetPriority();
  547. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  548. {
  549. farClipZone_ = *i;
  550. bestPriority = priority;
  551. }
  552. }
  553. }
  554. if (farClipZone_ == defaultZone)
  555. farClipZone_ = cameraZone_;
  556. // If occlusion in use, get & render the occluders
  557. occlusionBuffer_ = 0;
  558. if (maxOccluderTriangles_ > 0)
  559. {
  560. UpdateOccluders(occluders_, camera_);
  561. if (occluders_.Size())
  562. {
  563. PROFILE(DrawOcclusion);
  564. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  565. DrawOccluders(occlusionBuffer_, occluders_);
  566. }
  567. }
  568. // Get lights and geometries. Coarse occlusion for octants is used at this point
  569. if (occlusionBuffer_)
  570. {
  571. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  572. DRAWABLE_LIGHT, camera_->GetViewMask());
  573. octree_->GetDrawables(query);
  574. }
  575. else
  576. {
  577. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  578. camera_->GetViewMask());
  579. octree_->GetDrawables(query);
  580. }
  581. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  582. {
  583. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  584. {
  585. PerThreadSceneResult& result = sceneResults_[i];
  586. result.geometries_.Clear();
  587. result.lights_.Clear();
  588. result.minZ_ = M_INFINITY;
  589. result.maxZ_ = 0.0f;
  590. }
  591. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  592. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  593. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  594. // Create a work item for each thread
  595. for (int i = 0; i < numWorkItems; ++i)
  596. {
  597. SharedPtr<WorkItem> item = queue->GetFreeItem();
  598. item->priority_ = M_MAX_UNSIGNED;
  599. item->workFunction_ = CheckVisibilityWork;
  600. item->aux_ = this;
  601. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  602. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  603. end = start + drawablesPerItem;
  604. item->start_ = &(*start);
  605. item->end_ = &(*end);
  606. queue->AddWorkItem(item);
  607. start = end;
  608. }
  609. queue->Complete(M_MAX_UNSIGNED);
  610. }
  611. // Combine lights, geometries & scene Z range from the threads
  612. geometries_.Clear();
  613. lights_.Clear();
  614. minZ_ = M_INFINITY;
  615. maxZ_ = 0.0f;
  616. if (sceneResults_.Size() > 1)
  617. {
  618. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  619. {
  620. PerThreadSceneResult& result = sceneResults_[i];
  621. geometries_.Push(result.geometries_);
  622. lights_.Push(result.lights_);
  623. minZ_ = Min(minZ_, result.minZ_);
  624. maxZ_ = Max(maxZ_, result.maxZ_);
  625. }
  626. }
  627. else
  628. {
  629. // If just 1 thread, copy the results directly
  630. PerThreadSceneResult& result = sceneResults_[0];
  631. minZ_ = result.minZ_;
  632. maxZ_ = result.maxZ_;
  633. Swap(geometries_, result.geometries_);
  634. Swap(lights_, result.lights_);
  635. }
  636. if (minZ_ == M_INFINITY)
  637. minZ_ = 0.0f;
  638. // Sort the lights to brightest/closest first
  639. for (unsigned i = 0; i < lights_.Size(); ++i)
  640. {
  641. Light* light = lights_[i];
  642. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  643. light->SetLightQueue(0);
  644. }
  645. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  646. }
  647. void View::GetBatches()
  648. {
  649. WorkQueue* queue = GetSubsystem<WorkQueue>();
  650. PODVector<Light*> vertexLights;
  651. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassName_) ? &batchQueues_[alphaPassName_] : (BatchQueue*)0;
  652. // Process lit geometries and shadow casters for each light
  653. {
  654. PROFILE(ProcessLights);
  655. lightQueryResults_.Resize(lights_.Size());
  656. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  657. {
  658. SharedPtr<WorkItem> item = queue->GetFreeItem();
  659. item->priority_ = M_MAX_UNSIGNED;
  660. item->workFunction_ = ProcessLightWork;
  661. item->aux_ = this;
  662. LightQueryResult& query = lightQueryResults_[i];
  663. query.light_ = lights_[i];
  664. item->start_ = &query;
  665. queue->AddWorkItem(item);
  666. }
  667. // Ensure all lights have been processed before proceeding
  668. queue->Complete(M_MAX_UNSIGNED);
  669. }
  670. // Build light queues and lit batches
  671. {
  672. PROFILE(GetLightBatches);
  673. // Preallocate light queues: per-pixel lights which have lit geometries
  674. unsigned numLightQueues = 0;
  675. unsigned usedLightQueues = 0;
  676. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  677. {
  678. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  679. ++numLightQueues;
  680. }
  681. lightQueues_.Resize(numLightQueues);
  682. maxLightsDrawables_.Clear();
  683. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  684. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  685. {
  686. LightQueryResult& query = *i;
  687. // If light has no affected geometries, no need to process further
  688. if (query.litGeometries_.Empty())
  689. continue;
  690. Light* light = query.light_;
  691. // Per-pixel light
  692. if (!light->GetPerVertex())
  693. {
  694. unsigned shadowSplits = query.numSplits_;
  695. // Initialize light queue and store it to the light so that it can be found later
  696. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  697. light->SetLightQueue(&lightQueue);
  698. lightQueue.light_ = light;
  699. lightQueue.shadowMap_ = 0;
  700. lightQueue.litBaseBatches_.Clear(maxSortedInstances);
  701. lightQueue.litBatches_.Clear(maxSortedInstances);
  702. lightQueue.volumeBatches_.Clear();
  703. // Allocate shadow map now
  704. if (shadowSplits > 0)
  705. {
  706. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  707. // If did not manage to get a shadow map, convert the light to unshadowed
  708. if (!lightQueue.shadowMap_)
  709. shadowSplits = 0;
  710. }
  711. // Setup shadow batch queues
  712. lightQueue.shadowSplits_.Resize(shadowSplits);
  713. for (unsigned j = 0; j < shadowSplits; ++j)
  714. {
  715. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  716. Camera* shadowCamera = query.shadowCameras_[j];
  717. shadowQueue.shadowCamera_ = shadowCamera;
  718. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  719. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  720. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  721. // Setup the shadow split viewport and finalize shadow camera parameters
  722. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  723. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  724. // Loop through shadow casters
  725. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  726. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  727. {
  728. Drawable* drawable = *k;
  729. if (!drawable->IsInView(frame_, true))
  730. {
  731. // May be called from multiple threads, so don't manipulate the Drawable's viewCameras set,
  732. // just update the frame number
  733. drawable->MarkInView(frame_.frameNumber_, 0);
  734. shadowGeometries_.Push(drawable);
  735. }
  736. Zone* zone = GetZone(drawable);
  737. const Vector<SourceBatch>& batches = drawable->GetBatches();
  738. for (unsigned l = 0; l < batches.Size(); ++l)
  739. {
  740. const SourceBatch& srcBatch = batches[l];
  741. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  742. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  743. continue;
  744. Pass* pass = tech->GetPass(PASS_SHADOW);
  745. // Skip if material has no shadow pass
  746. if (!pass)
  747. continue;
  748. Batch destBatch(srcBatch);
  749. destBatch.pass_ = pass;
  750. destBatch.camera_ = shadowCamera;
  751. destBatch.zone_ = zone;
  752. destBatch.lightQueue_ = &lightQueue;
  753. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  754. }
  755. }
  756. }
  757. // Process lit geometries
  758. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  759. {
  760. Drawable* drawable = *j;
  761. drawable->AddLight(light);
  762. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  763. if (!drawable->GetMaxLights())
  764. GetLitBatches(drawable, lightQueue, alphaQueue);
  765. else
  766. maxLightsDrawables_.Insert(drawable);
  767. }
  768. // In deferred modes, store the light volume batch now
  769. if (deferred_)
  770. {
  771. Batch volumeBatch;
  772. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  773. volumeBatch.geometryType_ = GEOM_STATIC;
  774. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  775. volumeBatch.numWorldTransforms_ = 1;
  776. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  777. volumeBatch.camera_ = camera_;
  778. volumeBatch.lightQueue_ = &lightQueue;
  779. volumeBatch.distance_ = light->GetDistance();
  780. volumeBatch.material_ = 0;
  781. volumeBatch.pass_ = 0;
  782. volumeBatch.zone_ = 0;
  783. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVolumeVSName_, lightVolumePSName_);
  784. lightQueue.volumeBatches_.Push(volumeBatch);
  785. }
  786. }
  787. // Per-vertex light
  788. else
  789. {
  790. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  791. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  792. {
  793. Drawable* drawable = *j;
  794. drawable->AddVertexLight(light);
  795. }
  796. }
  797. }
  798. }
  799. // Process drawables with limited per-pixel light count
  800. if (maxLightsDrawables_.Size())
  801. {
  802. PROFILE(GetMaxLightsBatches);
  803. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  804. {
  805. Drawable* drawable = *i;
  806. drawable->LimitLights();
  807. const PODVector<Light*>& lights = drawable->GetLights();
  808. for (unsigned i = 0; i < lights.Size(); ++i)
  809. {
  810. Light* light = lights[i];
  811. // Find the correct light queue again
  812. LightBatchQueue* queue = light->GetLightQueue();
  813. if (queue)
  814. GetLitBatches(drawable, *queue, alphaQueue);
  815. }
  816. }
  817. }
  818. // Build base pass batches
  819. {
  820. PROFILE(GetBaseBatches);
  821. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  822. {
  823. Drawable* drawable = *i;
  824. Zone* zone = GetZone(drawable);
  825. const Vector<SourceBatch>& batches = drawable->GetBatches();
  826. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  827. if (!drawableVertexLights.Empty())
  828. drawable->LimitVertexLights();
  829. for (unsigned j = 0; j < batches.Size(); ++j)
  830. {
  831. const SourceBatch& srcBatch = batches[j];
  832. // Check here if the material refers to a rendertarget texture with camera(s) attached
  833. // Only check this for backbuffer views (null rendertarget)
  834. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  835. CheckMaterialForAuxView(srcBatch.material_);
  836. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  837. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  838. continue;
  839. Batch destBatch(srcBatch);
  840. destBatch.camera_ = camera_;
  841. destBatch.zone_ = zone;
  842. destBatch.isBase_ = true;
  843. destBatch.pass_ = 0;
  844. destBatch.lightMask_ = GetLightMask(drawable);
  845. // Check each of the scene passes
  846. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  847. {
  848. ScenePassInfo& info = scenePasses_[k];
  849. destBatch.pass_ = tech->GetPass(info.pass_);
  850. if (!destBatch.pass_)
  851. continue;
  852. // Skip forward base pass if the corresponding litbase pass already exists
  853. if (info.pass_ == basePassName_ && j < 32 && drawable->HasBasePass(j))
  854. continue;
  855. if (info.vertexLights_ && !drawableVertexLights.Empty())
  856. {
  857. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  858. // them to prevent double-lighting
  859. if (deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  860. {
  861. vertexLights.Clear();
  862. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  863. {
  864. if (drawableVertexLights[i]->GetPerVertex())
  865. vertexLights.Push(drawableVertexLights[i]);
  866. }
  867. }
  868. else
  869. vertexLights = drawableVertexLights;
  870. if (!vertexLights.Empty())
  871. {
  872. // Find a vertex light queue. If not found, create new
  873. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  874. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  875. if (i == vertexLightQueues_.End())
  876. {
  877. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  878. i->second_.light_ = 0;
  879. i->second_.shadowMap_ = 0;
  880. i->second_.vertexLights_ = vertexLights;
  881. }
  882. destBatch.lightQueue_ = &(i->second_);
  883. }
  884. }
  885. else
  886. destBatch.lightQueue_ = 0;
  887. bool allowInstancing = info.allowInstancing_;
  888. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (zone->GetLightMask() & 0xff))
  889. allowInstancing = false;
  890. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  891. }
  892. }
  893. }
  894. }
  895. }
  896. void View::UpdateGeometries()
  897. {
  898. PROFILE(SortAndUpdateGeometry);
  899. WorkQueue* queue = GetSubsystem<WorkQueue>();
  900. // Sort batches
  901. {
  902. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  903. {
  904. const RenderPathCommand& command = renderPath_->commands_[i];
  905. if (!IsNecessary(command))
  906. continue;
  907. if (command.type_ == CMD_SCENEPASS)
  908. {
  909. BatchQueue* passQueue = &batchQueues_[command.pass_];
  910. SharedPtr<WorkItem> item = queue->GetFreeItem();
  911. item->priority_ = M_MAX_UNSIGNED;
  912. item->workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork : SortBatchQueueBackToFrontWork;
  913. item->start_ = &batchQueues_[command.pass_];
  914. queue->AddWorkItem(item);
  915. }
  916. }
  917. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  918. {
  919. SharedPtr<WorkItem> lightItem = queue->GetFreeItem();
  920. lightItem->priority_ = M_MAX_UNSIGNED;
  921. lightItem->workFunction_ = SortLightQueueWork;
  922. lightItem->start_ = &(*i);
  923. queue->AddWorkItem(lightItem);
  924. if (i->shadowSplits_.Size())
  925. {
  926. SharedPtr<WorkItem> shadowItem = queue->GetFreeItem();
  927. shadowItem->priority_ = M_MAX_UNSIGNED;
  928. shadowItem->workFunction_ = SortShadowQueueWork;
  929. shadowItem->start_ = &(*i);
  930. queue->AddWorkItem(shadowItem);
  931. }
  932. }
  933. }
  934. // Update geometries. Split into threaded and non-threaded updates.
  935. {
  936. nonThreadedGeometries_.Clear();
  937. threadedGeometries_.Clear();
  938. for (PODVector<Drawable*>::Iterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  939. {
  940. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  941. if (type == UPDATE_MAIN_THREAD)
  942. nonThreadedGeometries_.Push(*i);
  943. else if (type == UPDATE_WORKER_THREAD)
  944. threadedGeometries_.Push(*i);
  945. }
  946. for (PODVector<Drawable*>::Iterator i = shadowGeometries_.Begin(); i != shadowGeometries_.End(); ++i)
  947. {
  948. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  949. if (type == UPDATE_MAIN_THREAD)
  950. nonThreadedGeometries_.Push(*i);
  951. else if (type == UPDATE_WORKER_THREAD)
  952. threadedGeometries_.Push(*i);
  953. }
  954. if (threadedGeometries_.Size())
  955. {
  956. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  957. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  958. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  959. for (int i = 0; i < numWorkItems; ++i)
  960. {
  961. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  962. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  963. end = start + drawablesPerItem;
  964. SharedPtr<WorkItem> item = queue->GetFreeItem();
  965. item->priority_ = M_MAX_UNSIGNED;
  966. item->workFunction_ = UpdateDrawableGeometriesWork;
  967. item->aux_ = const_cast<FrameInfo*>(&frame_);
  968. item->start_ = &(*start);
  969. item->end_ = &(*end);
  970. queue->AddWorkItem(item);
  971. start = end;
  972. }
  973. }
  974. // While the work queue is processed, update non-threaded geometries
  975. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  976. (*i)->UpdateGeometry(frame_);
  977. }
  978. // Finally ensure all threaded work has completed
  979. queue->Complete(M_MAX_UNSIGNED);
  980. }
  981. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue)
  982. {
  983. Light* light = lightQueue.light_;
  984. Zone* zone = GetZone(drawable);
  985. const Vector<SourceBatch>& batches = drawable->GetBatches();
  986. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  987. // Shadows on transparencies can only be rendered if shadow maps are not reused
  988. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  989. bool allowLitBase = useLitBase_ && light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  990. for (unsigned i = 0; i < batches.Size(); ++i)
  991. {
  992. const SourceBatch& srcBatch = batches[i];
  993. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  994. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  995. continue;
  996. // Do not create pixel lit forward passes for materials that render into the G-buffer
  997. if (gBufferPassName_.Value() && tech->HasPass(gBufferPassName_))
  998. continue;
  999. Batch destBatch(srcBatch);
  1000. bool isLitAlpha = false;
  1001. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1002. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1003. if (i < 32 && allowLitBase)
  1004. {
  1005. destBatch.pass_ = tech->GetPass(litBasePassName_);
  1006. if (destBatch.pass_)
  1007. {
  1008. destBatch.isBase_ = true;
  1009. drawable->SetBasePass(i);
  1010. }
  1011. else
  1012. destBatch.pass_ = tech->GetPass(lightPassName_);
  1013. }
  1014. else
  1015. destBatch.pass_ = tech->GetPass(lightPassName_);
  1016. // If no lit pass, check for lit alpha
  1017. if (!destBatch.pass_)
  1018. {
  1019. destBatch.pass_ = tech->GetPass(litAlphaPassName_);
  1020. isLitAlpha = true;
  1021. }
  1022. // Skip if material does not receive light at all
  1023. if (!destBatch.pass_)
  1024. continue;
  1025. destBatch.camera_ = camera_;
  1026. destBatch.lightQueue_ = &lightQueue;
  1027. destBatch.zone_ = zone;
  1028. if (!isLitAlpha)
  1029. {
  1030. if (destBatch.isBase_)
  1031. AddBatchToQueue(lightQueue.litBaseBatches_, destBatch, tech);
  1032. else
  1033. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1034. }
  1035. else if (alphaQueue)
  1036. {
  1037. // Transparent batches can not be instanced
  1038. AddBatchToQueue(*alphaQueue, destBatch, tech, false, allowTransparentShadows);
  1039. }
  1040. }
  1041. }
  1042. void View::ExecuteRenderPathCommands()
  1043. {
  1044. // If not reusing shadowmaps, render all of them first
  1045. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1046. {
  1047. PROFILE(RenderShadowMaps);
  1048. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1049. {
  1050. if (i->shadowMap_)
  1051. RenderShadowMap(*i);
  1052. }
  1053. }
  1054. {
  1055. PROFILE(ExecuteRenderPath);
  1056. // Set for safety in case of empty renderpath
  1057. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1058. currentViewportTexture_ = 0;
  1059. bool viewportModified = false;
  1060. bool isPingponging = false;
  1061. unsigned lastCommandIndex = 0;
  1062. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1063. {
  1064. RenderPathCommand& command = renderPath_->commands_[i];
  1065. if (IsNecessary(command))
  1066. lastCommandIndex = i;
  1067. }
  1068. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1069. {
  1070. RenderPathCommand& command = renderPath_->commands_[i];
  1071. if (!IsNecessary(command))
  1072. continue;
  1073. bool viewportRead = CheckViewportRead(command);
  1074. bool viewportWrite = CheckViewportWrite(command);
  1075. bool beginPingpong = CheckPingpong(i);
  1076. // Has the viewport been modified and will be read as a texture by the current command?
  1077. if (viewportRead && viewportModified)
  1078. {
  1079. // Start pingponging without a blit if already rendering to the substitute render target
  1080. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1081. isPingponging = true;
  1082. // If not using pingponging, simply resolve/copy to the first viewport texture
  1083. if (!isPingponging)
  1084. {
  1085. if (!currentRenderTarget_)
  1086. {
  1087. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1088. currentViewportTexture_ = viewportTextures_[0];
  1089. viewportModified = false;
  1090. }
  1091. else
  1092. {
  1093. if (viewportWrite)
  1094. {
  1095. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1096. viewportTextures_[0]->GetRenderSurface(), false);
  1097. currentViewportTexture_ = viewportTextures_[0];
  1098. viewportModified = false;
  1099. }
  1100. else
  1101. {
  1102. // If the current render target is already a texture, and we are not writing to it, can read that
  1103. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1104. // will do both read and write, and then we need to blit / resolve
  1105. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1106. }
  1107. }
  1108. }
  1109. else
  1110. {
  1111. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1112. viewportTextures_[1] = viewportTextures_[0];
  1113. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1114. currentViewportTexture_ = viewportTextures_[0];
  1115. viewportModified = false;
  1116. }
  1117. }
  1118. if (beginPingpong)
  1119. isPingponging = true;
  1120. // Determine viewport write target
  1121. if (viewportWrite)
  1122. {
  1123. if (isPingponging)
  1124. {
  1125. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1126. // If the render path ends into a quad, it can be redirected to the final render target
  1127. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1128. currentRenderTarget_ = renderTarget_;
  1129. }
  1130. else
  1131. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1132. }
  1133. switch (command.type_)
  1134. {
  1135. case CMD_CLEAR:
  1136. {
  1137. PROFILE(ClearRenderTarget);
  1138. Color clearColor = command.clearColor_;
  1139. if (command.useFogColor_)
  1140. clearColor = farClipZone_->GetFogColor();
  1141. SetRenderTargets(command);
  1142. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1143. }
  1144. break;
  1145. case CMD_SCENEPASS:
  1146. if (!batchQueues_[command.pass_].IsEmpty())
  1147. {
  1148. PROFILE(RenderScenePass);
  1149. SetRenderTargets(command);
  1150. SetTextures(command);
  1151. graphics_->SetFillMode(camera_->GetFillMode());
  1152. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1153. batchQueues_[command.pass_].Draw(this, command.markToStencil_, false);
  1154. }
  1155. break;
  1156. case CMD_QUAD:
  1157. {
  1158. PROFILE(RenderQuad);
  1159. SetRenderTargets(command);
  1160. SetTextures(command);
  1161. RenderQuad(command);
  1162. }
  1163. break;
  1164. case CMD_FORWARDLIGHTS:
  1165. // Render shadow maps + opaque objects' additive lighting
  1166. if (!lightQueues_.Empty())
  1167. {
  1168. PROFILE(RenderLights);
  1169. SetRenderTargets(command);
  1170. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1171. {
  1172. // If reusing shadowmaps, render each of them before the lit batches
  1173. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1174. {
  1175. RenderShadowMap(*i);
  1176. SetRenderTargets(command);
  1177. }
  1178. SetTextures(command);
  1179. graphics_->SetFillMode(camera_->GetFillMode());
  1180. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1181. // Draw base (replace blend) batches first
  1182. i->litBaseBatches_.Draw(this);
  1183. // Then, if there are additive passes, optimize the light and draw them
  1184. if (!i->litBatches_.IsEmpty())
  1185. {
  1186. renderer_->OptimizeLightByScissor(i->light_, camera_);
  1187. renderer_->OptimizeLightByStencil(i->light_, camera_);
  1188. i->litBatches_.Draw(this, false, true);
  1189. }
  1190. }
  1191. graphics_->SetScissorTest(false);
  1192. graphics_->SetStencilTest(false);
  1193. }
  1194. break;
  1195. case CMD_LIGHTVOLUMES:
  1196. // Render shadow maps + light volumes
  1197. if (!lightQueues_.Empty())
  1198. {
  1199. PROFILE(RenderLightVolumes);
  1200. SetRenderTargets(command);
  1201. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1202. {
  1203. // If reusing shadowmaps, render each of them before the lit batches
  1204. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1205. {
  1206. RenderShadowMap(*i);
  1207. SetRenderTargets(command);
  1208. }
  1209. SetTextures(command);
  1210. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1211. {
  1212. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1213. i->volumeBatches_[j].Draw(this);
  1214. }
  1215. }
  1216. graphics_->SetScissorTest(false);
  1217. graphics_->SetStencilTest(false);
  1218. }
  1219. break;
  1220. default:
  1221. break;
  1222. }
  1223. // If current command output to the viewport, mark it modified
  1224. if (viewportWrite)
  1225. viewportModified = true;
  1226. }
  1227. }
  1228. // After executing all commands, reset rendertarget for debug geometry rendering
  1229. graphics_->SetRenderTarget(0, renderTarget_);
  1230. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1231. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1232. graphics_->SetDepthStencil(GetDepthStencil(renderTarget_));
  1233. graphics_->SetViewport(viewRect_);
  1234. graphics_->SetFillMode(FILL_SOLID);
  1235. graphics_->SetClipPlane(false);
  1236. }
  1237. void View::SetRenderTargets(RenderPathCommand& command)
  1238. {
  1239. unsigned index = 0;
  1240. IntRect viewPort = viewRect_;
  1241. while (index < command.outputNames_.Size())
  1242. {
  1243. if (!command.outputNames_[index].Compare("viewport", false))
  1244. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1245. else
  1246. {
  1247. StringHash nameHash(command.outputNames_[index]);
  1248. if (renderTargets_.Contains(nameHash))
  1249. {
  1250. Texture2D* texture = renderTargets_[nameHash];
  1251. graphics_->SetRenderTarget(index, texture);
  1252. if (!index)
  1253. {
  1254. // Determine viewport size from rendertarget info
  1255. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1256. {
  1257. const RenderTargetInfo& info = renderPath_->renderTargets_[i];
  1258. if (!info.name_.Compare(command.outputNames_[index], false))
  1259. {
  1260. switch (info.sizeMode_)
  1261. {
  1262. // If absolute or a divided viewport size, use the full texture
  1263. case SIZE_ABSOLUTE:
  1264. case SIZE_VIEWPORTDIVISOR:
  1265. viewPort = IntRect(0, 0, texture->GetWidth(), texture->GetHeight());
  1266. break;
  1267. // If a divided rendertarget size, retain the same viewport, but scaled
  1268. case SIZE_RENDERTARGETDIVISOR:
  1269. if (info.size_.x_ && info.size_.y_)
  1270. {
  1271. viewPort = IntRect(viewRect_.left_ / info.size_.x_, viewRect_.top_ / info.size_.y_,
  1272. viewRect_.right_ / info.size_.x_, viewRect_.bottom_ / info.size_.y_);
  1273. }
  1274. break;
  1275. }
  1276. break;
  1277. }
  1278. }
  1279. }
  1280. }
  1281. else
  1282. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1283. }
  1284. ++index;
  1285. }
  1286. while (index < MAX_RENDERTARGETS)
  1287. {
  1288. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1289. ++index;
  1290. }
  1291. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1292. graphics_->SetViewport(viewPort);
  1293. graphics_->SetColorWrite(true);
  1294. }
  1295. void View::SetTextures(RenderPathCommand& command)
  1296. {
  1297. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1298. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1299. {
  1300. if (command.textureNames_[i].Empty())
  1301. continue;
  1302. // Bind the rendered output
  1303. if (!command.textureNames_[i].Compare("viewport", false))
  1304. {
  1305. graphics_->SetTexture(i, currentViewportTexture_);
  1306. continue;
  1307. }
  1308. // Bind a rendertarget
  1309. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1310. if (j != renderTargets_.End())
  1311. {
  1312. graphics_->SetTexture(i, j->second_);
  1313. continue;
  1314. }
  1315. // Bind a texture from the resource system
  1316. Texture* texture;
  1317. // Detect cube/3D textures by file extension: they are defined by an XML file
  1318. if (GetExtension(command.textureNames_[i]) == ".xml")
  1319. {
  1320. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1321. if (i == TU_VOLUMEMAP)
  1322. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1323. else
  1324. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1325. }
  1326. else
  1327. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1328. if (texture)
  1329. graphics_->SetTexture(i, texture);
  1330. else
  1331. {
  1332. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1333. command.textureNames_[i] = String::EMPTY;
  1334. }
  1335. }
  1336. }
  1337. void View::RenderQuad(RenderPathCommand& command)
  1338. {
  1339. if (command.vertexShaderName_.Empty() || command.pixelShaderName_.Empty())
  1340. return;
  1341. // If shader can not be found, clear it from the command to prevent redundant attempts
  1342. ShaderVariation* vs = graphics_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1343. if (!vs)
  1344. command.vertexShaderName_ = String::EMPTY;
  1345. ShaderVariation* ps = graphics_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1346. if (!ps)
  1347. command.pixelShaderName_ = String::EMPTY;
  1348. // Set shaders & shader parameters and textures
  1349. graphics_->SetShaders(vs, ps);
  1350. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1351. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1352. graphics_->SetShaderParameter(k->first_, k->second_);
  1353. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  1354. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  1355. float nearClip = camera_->GetNearClip();
  1356. float farClip = camera_->GetFarClip();
  1357. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  1358. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  1359. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  1360. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  1361. float rtWidth = (float)rtSize_.x_;
  1362. float rtHeight = (float)rtSize_.y_;
  1363. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1364. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1365. #ifdef USE_OPENGL
  1366. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1367. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1368. #else
  1369. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1370. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1371. #endif
  1372. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1373. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(1.0f / rtWidth, 1.0f / rtHeight, 0.0f, 0.0f));
  1374. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1375. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1376. {
  1377. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1378. if (!rtInfo.enabled_)
  1379. continue;
  1380. StringHash nameHash(rtInfo.name_);
  1381. if (!renderTargets_.Contains(nameHash))
  1382. continue;
  1383. String invSizeName = rtInfo.name_ + "InvSize";
  1384. String offsetsName = rtInfo.name_ + "Offsets";
  1385. float width = (float)renderTargets_[nameHash]->GetWidth();
  1386. float height = (float)renderTargets_[nameHash]->GetHeight();
  1387. graphics_->SetShaderParameter(invSizeName, Vector4(1.0f / width, 1.0f / height, 0.0f, 0.0f));
  1388. #ifdef USE_OPENGL
  1389. graphics_->SetShaderParameter(offsetsName, Vector4::ZERO);
  1390. #else
  1391. graphics_->SetShaderParameter(offsetsName, Vector4(0.5f / width, 0.5f / height, 0.0f, 0.0f));
  1392. #endif
  1393. }
  1394. graphics_->SetBlendMode(BLEND_REPLACE);
  1395. graphics_->SetDepthTest(CMP_ALWAYS);
  1396. graphics_->SetDepthWrite(false);
  1397. graphics_->SetFillMode(FILL_SOLID);
  1398. graphics_->SetClipPlane(false);
  1399. graphics_->SetScissorTest(false);
  1400. graphics_->SetStencilTest(false);
  1401. DrawFullscreenQuad(false);
  1402. }
  1403. bool View::IsNecessary(const RenderPathCommand& command)
  1404. {
  1405. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1406. !batchQueues_[command.pass_].IsEmpty());
  1407. }
  1408. bool View::CheckViewportRead(const RenderPathCommand& command)
  1409. {
  1410. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1411. {
  1412. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1413. return true;
  1414. }
  1415. return false;
  1416. }
  1417. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1418. {
  1419. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1420. {
  1421. if (!command.outputNames_[i].Compare("viewport", false))
  1422. return true;
  1423. }
  1424. return false;
  1425. }
  1426. bool View::CheckPingpong(unsigned index)
  1427. {
  1428. // Current command must be a viewport-reading & writing quad to begin the pingpong chain
  1429. RenderPathCommand& current = renderPath_->commands_[index];
  1430. if (current.type_ != CMD_QUAD || !CheckViewportRead(current) || !CheckViewportWrite(current))
  1431. return false;
  1432. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1433. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1434. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1435. {
  1436. RenderPathCommand& command = renderPath_->commands_[i];
  1437. if (!IsNecessary(command))
  1438. continue;
  1439. if (CheckViewportWrite(command))
  1440. {
  1441. if (command.type_ != CMD_QUAD)
  1442. return false;
  1443. }
  1444. }
  1445. return true;
  1446. }
  1447. void View::AllocateScreenBuffers()
  1448. {
  1449. bool needSubstitute = false;
  1450. unsigned numViewportTextures = 0;
  1451. #ifdef USE_OPENGL
  1452. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1453. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1454. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1455. Graphics::GetRGBAFormat()))
  1456. needSubstitute = true;
  1457. #endif
  1458. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1459. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1460. needSubstitute = true;
  1461. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1462. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1463. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1464. bool hdrRendering = renderer_->GetHDRRendering();
  1465. if (renderer_->GetHDRRendering())
  1466. {
  1467. format = Graphics::GetRGBAFloat16Format();
  1468. needSubstitute = true;
  1469. }
  1470. #ifdef USE_OPENGL
  1471. if (deferred_ && !hdrRendering)
  1472. format = Graphics::GetRGBAFormat();
  1473. #endif
  1474. // Check for commands which read the viewport, or pingpong between viewport textures
  1475. bool hasViewportRead = false;
  1476. bool hasPingpong = false;
  1477. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1478. {
  1479. const RenderPathCommand& command = renderPath_->commands_[i];
  1480. if (!IsNecessary(command))
  1481. continue;
  1482. if (CheckViewportRead(command))
  1483. hasViewportRead = true;
  1484. if (!hasPingpong && CheckPingpong(i))
  1485. hasPingpong = true;
  1486. }
  1487. if (hasViewportRead)
  1488. {
  1489. ++numViewportTextures;
  1490. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1491. // is specified, there is no choice
  1492. #ifdef GL_ES_VERSION_2_0
  1493. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1494. needSubstitute = true;
  1495. #endif
  1496. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1497. // does not support reading a cube map
  1498. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1499. needSubstitute = true;
  1500. if (hasPingpong && !needSubstitute)
  1501. ++numViewportTextures;
  1502. }
  1503. // Allocate screen buffers with filtering active in case the quad commands need that
  1504. // Follow the sRGB mode of the destination render target
  1505. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1506. substituteRenderTarget_ = needSubstitute ? renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true,
  1507. sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1508. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1509. {
  1510. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true, sRGB) :
  1511. (Texture2D*)0;
  1512. }
  1513. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1514. if (numViewportTextures == 1 && substituteRenderTarget_)
  1515. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1516. // Allocate extra render targets defined by the rendering path
  1517. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1518. {
  1519. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1520. if (!rtInfo.enabled_)
  1521. continue;
  1522. unsigned width = rtInfo.size_.x_;
  1523. unsigned height = rtInfo.size_.y_;
  1524. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1525. {
  1526. width = viewSize_.x_ / (width ? width : 1);
  1527. height = viewSize_.y_ / (height ? height : 1);
  1528. }
  1529. if (rtInfo.sizeMode_ == SIZE_RENDERTARGETDIVISOR)
  1530. {
  1531. width = rtSize_.x_ / (width ? width : 1);
  1532. height = rtSize_.y_ / (height ? height : 1);
  1533. }
  1534. // If the rendertarget is persistent, key it with a hash derived from the RT name and the view's pointer
  1535. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(width, height, rtInfo.format_, rtInfo.filtered_, rtInfo.sRGB_,
  1536. rtInfo.persistent_ ? StringHash(rtInfo.name_).Value() + (unsigned)(size_t)this : 0);
  1537. }
  1538. }
  1539. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1540. {
  1541. if (!source)
  1542. return;
  1543. PROFILE(BlitFramebuffer);
  1544. graphics_->SetBlendMode(BLEND_REPLACE);
  1545. graphics_->SetDepthTest(CMP_ALWAYS);
  1546. graphics_->SetDepthWrite(depthWrite);
  1547. graphics_->SetFillMode(FILL_SOLID);
  1548. graphics_->SetClipPlane(false);
  1549. graphics_->SetScissorTest(false);
  1550. graphics_->SetStencilTest(false);
  1551. graphics_->SetRenderTarget(0, destination);
  1552. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1553. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1554. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1555. graphics_->SetViewport(viewRect_);
  1556. String shaderName = "CopyFramebuffer";
  1557. graphics_->SetShaders(graphics_->GetShader(VS, shaderName), graphics_->GetShader(PS, shaderName));
  1558. float rtWidth = (float)rtSize_.x_;
  1559. float rtHeight = (float)rtSize_.y_;
  1560. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1561. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1562. #ifdef USE_OPENGL
  1563. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1564. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1565. #else
  1566. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1567. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1568. #endif
  1569. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1570. graphics_->SetTexture(TU_DIFFUSE, source);
  1571. DrawFullscreenQuad(false);
  1572. }
  1573. void View::DrawFullscreenQuad(bool nearQuad)
  1574. {
  1575. Light* quadDirLight = renderer_->GetQuadDirLight();
  1576. Geometry* geometry = renderer_->GetLightGeometry(quadDirLight);
  1577. Matrix3x4 model = Matrix3x4::IDENTITY;
  1578. Matrix4 projection = Matrix4::IDENTITY;
  1579. #ifdef USE_OPENGL
  1580. if (camera_->GetFlipVertical())
  1581. projection.m11_ = -1.0f;
  1582. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1583. #else
  1584. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1585. #endif
  1586. graphics_->SetCullMode(CULL_NONE);
  1587. graphics_->SetShaderParameter(VSP_MODEL, model);
  1588. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1589. graphics_->ClearTransformSources();
  1590. geometry->Draw(graphics_);
  1591. }
  1592. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1593. {
  1594. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1595. float halfViewSize = camera->GetHalfViewSize();
  1596. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1597. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1598. {
  1599. Drawable* occluder = *i;
  1600. bool erase = false;
  1601. if (!occluder->IsInView(frame_, true))
  1602. occluder->UpdateBatches(frame_);
  1603. // Check occluder's draw distance (in main camera view)
  1604. float maxDistance = occluder->GetDrawDistance();
  1605. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1606. {
  1607. // Check that occluder is big enough on the screen
  1608. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1609. float diagonal = box.Size().Length();
  1610. float compare;
  1611. if (!camera->IsOrthographic())
  1612. compare = diagonal * halfViewSize / occluder->GetDistance();
  1613. else
  1614. compare = diagonal * invOrthoSize;
  1615. if (compare < occluderSizeThreshold_)
  1616. erase = true;
  1617. else
  1618. {
  1619. // Store amount of triangles divided by screen size as a sorting key
  1620. // (best occluders are big and have few triangles)
  1621. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1622. }
  1623. }
  1624. else
  1625. erase = true;
  1626. if (erase)
  1627. i = occluders.Erase(i);
  1628. else
  1629. ++i;
  1630. }
  1631. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1632. if (occluders.Size())
  1633. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1634. }
  1635. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1636. {
  1637. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1638. buffer->Clear();
  1639. for (unsigned i = 0; i < occluders.Size(); ++i)
  1640. {
  1641. Drawable* occluder = occluders[i];
  1642. if (i > 0)
  1643. {
  1644. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1645. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1646. continue;
  1647. }
  1648. // Check for running out of triangles
  1649. if (!occluder->DrawOcclusion(buffer))
  1650. break;
  1651. }
  1652. buffer->BuildDepthHierarchy();
  1653. }
  1654. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1655. {
  1656. Light* light = query.light_;
  1657. LightType type = light->GetLightType();
  1658. const Frustum& frustum = camera_->GetFrustum();
  1659. // Check if light should be shadowed
  1660. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1661. // If shadow distance non-zero, check it
  1662. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1663. isShadowed = false;
  1664. // OpenGL ES can not support point light shadows
  1665. #ifdef GL_ES_VERSION_2_0
  1666. if (isShadowed && type == LIGHT_POINT)
  1667. isShadowed = false;
  1668. #endif
  1669. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1670. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1671. query.litGeometries_.Clear();
  1672. switch (type)
  1673. {
  1674. case LIGHT_DIRECTIONAL:
  1675. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1676. {
  1677. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1678. query.litGeometries_.Push(geometries_[i]);
  1679. }
  1680. break;
  1681. case LIGHT_SPOT:
  1682. {
  1683. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1684. octree_->GetDrawables(octreeQuery);
  1685. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1686. {
  1687. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1688. query.litGeometries_.Push(tempDrawables[i]);
  1689. }
  1690. }
  1691. break;
  1692. case LIGHT_POINT:
  1693. {
  1694. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1695. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1696. octree_->GetDrawables(octreeQuery);
  1697. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1698. {
  1699. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1700. query.litGeometries_.Push(tempDrawables[i]);
  1701. }
  1702. }
  1703. break;
  1704. }
  1705. // If no lit geometries or not shadowed, no need to process shadow cameras
  1706. if (query.litGeometries_.Empty() || !isShadowed)
  1707. {
  1708. query.numSplits_ = 0;
  1709. return;
  1710. }
  1711. // Determine number of shadow cameras and setup their initial positions
  1712. SetupShadowCameras(query);
  1713. // Process each split for shadow casters
  1714. query.shadowCasters_.Clear();
  1715. for (unsigned i = 0; i < query.numSplits_; ++i)
  1716. {
  1717. Camera* shadowCamera = query.shadowCameras_[i];
  1718. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1719. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1720. // For point light check that the face is visible: if not, can skip the split
  1721. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1722. continue;
  1723. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1724. if (type == LIGHT_DIRECTIONAL)
  1725. {
  1726. if (minZ_ > query.shadowFarSplits_[i])
  1727. continue;
  1728. if (maxZ_ < query.shadowNearSplits_[i])
  1729. continue;
  1730. // Reuse lit geometry query for all except directional lights
  1731. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1732. camera_->GetViewMask());
  1733. octree_->GetDrawables(query);
  1734. }
  1735. // Check which shadow casters actually contribute to the shadowing
  1736. ProcessShadowCasters(query, tempDrawables, i);
  1737. }
  1738. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1739. // only cost has been the shadow camera setup & queries
  1740. if (query.shadowCasters_.Empty())
  1741. query.numSplits_ = 0;
  1742. }
  1743. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1744. {
  1745. Light* light = query.light_;
  1746. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1747. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1748. const Matrix3x4& lightView = shadowCamera->GetView();
  1749. const Matrix4& lightProj = shadowCamera->GetProjection();
  1750. LightType type = light->GetLightType();
  1751. query.shadowCasterBox_[splitIndex].defined_ = false;
  1752. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1753. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1754. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1755. Frustum lightViewFrustum;
  1756. if (type != LIGHT_DIRECTIONAL)
  1757. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1758. else
  1759. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1760. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1761. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1762. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1763. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1764. return;
  1765. BoundingBox lightViewBox;
  1766. BoundingBox lightProjBox;
  1767. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1768. {
  1769. Drawable* drawable = *i;
  1770. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1771. // Check for that first
  1772. if (!drawable->GetCastShadows())
  1773. continue;
  1774. // Check shadow mask
  1775. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1776. continue;
  1777. // For point light, check that this drawable is inside the split shadow camera frustum
  1778. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1779. continue;
  1780. // Check shadow distance
  1781. float maxShadowDistance = drawable->GetShadowDistance();
  1782. float drawDistance = drawable->GetDrawDistance();
  1783. bool batchesUpdated = drawable->IsInView(frame_, true);
  1784. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1785. maxShadowDistance = drawDistance;
  1786. if (maxShadowDistance > 0.0f)
  1787. {
  1788. if (!batchesUpdated)
  1789. {
  1790. drawable->UpdateBatches(frame_);
  1791. batchesUpdated = true;
  1792. }
  1793. if (drawable->GetDistance() > maxShadowDistance)
  1794. continue;
  1795. }
  1796. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1797. // times. However, this should not cause problems as no scene modification happens at this point.
  1798. if (!batchesUpdated)
  1799. drawable->UpdateBatches(frame_);
  1800. // Project shadow caster bounding box to light view space for visibility check
  1801. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1802. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1803. {
  1804. // Merge to shadow caster bounding box and add to the list
  1805. if (type == LIGHT_DIRECTIONAL)
  1806. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1807. else
  1808. {
  1809. lightProjBox = lightViewBox.Projected(lightProj);
  1810. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1811. }
  1812. query.shadowCasters_.Push(drawable);
  1813. }
  1814. }
  1815. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1816. }
  1817. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1818. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1819. {
  1820. if (shadowCamera->IsOrthographic())
  1821. {
  1822. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1823. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1824. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1825. }
  1826. else
  1827. {
  1828. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1829. if (drawable->IsInView(frame_))
  1830. return true;
  1831. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1832. Vector3 center = lightViewBox.Center();
  1833. Ray extrusionRay(center, center);
  1834. float extrusionDistance = shadowCamera->GetFarClip();
  1835. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  1836. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1837. float sizeFactor = extrusionDistance / originalDistance;
  1838. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1839. // than necessary, so the test will be conservative
  1840. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1841. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1842. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1843. lightViewBox.Merge(extrudedBox);
  1844. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1845. }
  1846. }
  1847. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1848. {
  1849. unsigned width = shadowMap->GetWidth();
  1850. unsigned height = shadowMap->GetHeight();
  1851. int maxCascades = renderer_->GetMaxShadowCascades();
  1852. switch (light->GetLightType())
  1853. {
  1854. case LIGHT_DIRECTIONAL:
  1855. if (maxCascades == 1)
  1856. return IntRect(0, 0, width, height);
  1857. else if (maxCascades == 2)
  1858. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1859. else
  1860. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1861. (splitIndex / 2 + 1) * height / 2);
  1862. case LIGHT_SPOT:
  1863. return IntRect(0, 0, width, height);
  1864. case LIGHT_POINT:
  1865. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1866. (splitIndex / 2 + 1) * height / 3);
  1867. }
  1868. return IntRect();
  1869. }
  1870. void View::SetupShadowCameras(LightQueryResult& query)
  1871. {
  1872. Light* light = query.light_;
  1873. int splits = 0;
  1874. switch (light->GetLightType())
  1875. {
  1876. case LIGHT_DIRECTIONAL:
  1877. {
  1878. const CascadeParameters& cascade = light->GetShadowCascade();
  1879. float nearSplit = camera_->GetNearClip();
  1880. float farSplit;
  1881. while (splits < renderer_->GetMaxShadowCascades())
  1882. {
  1883. // If split is completely beyond camera far clip, we are done
  1884. if (nearSplit > camera_->GetFarClip())
  1885. break;
  1886. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1887. if (farSplit <= nearSplit)
  1888. break;
  1889. // Setup the shadow camera for the split
  1890. Camera* shadowCamera = renderer_->GetShadowCamera();
  1891. query.shadowCameras_[splits] = shadowCamera;
  1892. query.shadowNearSplits_[splits] = nearSplit;
  1893. query.shadowFarSplits_[splits] = farSplit;
  1894. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1895. nearSplit = farSplit;
  1896. ++splits;
  1897. }
  1898. }
  1899. break;
  1900. case LIGHT_SPOT:
  1901. {
  1902. Camera* shadowCamera = renderer_->GetShadowCamera();
  1903. query.shadowCameras_[0] = shadowCamera;
  1904. Node* cameraNode = shadowCamera->GetNode();
  1905. Node* lightNode = light->GetNode();
  1906. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  1907. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1908. shadowCamera->SetFarClip(light->GetRange());
  1909. shadowCamera->SetFov(light->GetFov());
  1910. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1911. splits = 1;
  1912. }
  1913. break;
  1914. case LIGHT_POINT:
  1915. {
  1916. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1917. {
  1918. Camera* shadowCamera = renderer_->GetShadowCamera();
  1919. query.shadowCameras_[i] = shadowCamera;
  1920. Node* cameraNode = shadowCamera->GetNode();
  1921. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1922. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  1923. cameraNode->SetDirection(*directions[i]);
  1924. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1925. shadowCamera->SetFarClip(light->GetRange());
  1926. shadowCamera->SetFov(90.0f);
  1927. shadowCamera->SetAspectRatio(1.0f);
  1928. }
  1929. splits = MAX_CUBEMAP_FACES;
  1930. }
  1931. break;
  1932. }
  1933. query.numSplits_ = splits;
  1934. }
  1935. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1936. {
  1937. Node* shadowCameraNode = shadowCamera->GetNode();
  1938. Node* lightNode = light->GetNode();
  1939. float extrusionDistance = camera_->GetFarClip();
  1940. const FocusParameters& parameters = light->GetShadowFocus();
  1941. // Calculate initial position & rotation
  1942. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  1943. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  1944. // Calculate main camera shadowed frustum in light's view space
  1945. farSplit = Min(farSplit, camera_->GetFarClip());
  1946. // Use the scene Z bounds to limit frustum size if applicable
  1947. if (parameters.focus_)
  1948. {
  1949. nearSplit = Max(minZ_, nearSplit);
  1950. farSplit = Min(maxZ_, farSplit);
  1951. }
  1952. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1953. Polyhedron frustumVolume;
  1954. frustumVolume.Define(splitFrustum);
  1955. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1956. if (parameters.focus_)
  1957. {
  1958. BoundingBox litGeometriesBox;
  1959. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1960. {
  1961. Drawable* drawable = geometries_[i];
  1962. // Skip skyboxes as they have undefinedly large bounding box size
  1963. if (drawable->GetType() == Skybox::GetTypeStatic())
  1964. continue;
  1965. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  1966. (GetLightMask(drawable) & light->GetLightMask()))
  1967. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  1968. }
  1969. if (litGeometriesBox.defined_)
  1970. {
  1971. frustumVolume.Clip(litGeometriesBox);
  1972. // If volume became empty, restore it to avoid zero size
  1973. if (frustumVolume.Empty())
  1974. frustumVolume.Define(splitFrustum);
  1975. }
  1976. }
  1977. // Transform frustum volume to light space
  1978. const Matrix3x4& lightView = shadowCamera->GetView();
  1979. frustumVolume.Transform(lightView);
  1980. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1981. BoundingBox shadowBox;
  1982. if (!parameters.nonUniform_)
  1983. shadowBox.Define(Sphere(frustumVolume));
  1984. else
  1985. shadowBox.Define(frustumVolume);
  1986. shadowCamera->SetOrthographic(true);
  1987. shadowCamera->SetAspectRatio(1.0f);
  1988. shadowCamera->SetNearClip(0.0f);
  1989. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1990. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1991. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1992. }
  1993. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1994. const BoundingBox& shadowCasterBox)
  1995. {
  1996. const FocusParameters& parameters = light->GetShadowFocus();
  1997. float shadowMapWidth = (float)(shadowViewport.Width());
  1998. LightType type = light->GetLightType();
  1999. if (type == LIGHT_DIRECTIONAL)
  2000. {
  2001. BoundingBox shadowBox;
  2002. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  2003. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  2004. shadowBox.min_.y_ = -shadowBox.max_.y_;
  2005. shadowBox.min_.x_ = -shadowBox.max_.x_;
  2006. // Requantize and snap to shadow map texels
  2007. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2008. }
  2009. if (type == LIGHT_SPOT)
  2010. {
  2011. if (parameters.focus_)
  2012. {
  2013. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2014. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2015. float viewSize = Max(viewSizeX, viewSizeY);
  2016. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2017. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2018. float quantize = parameters.quantize_ * invOrthoSize;
  2019. float minView = parameters.minView_ * invOrthoSize;
  2020. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2021. if (viewSize < 1.0f)
  2022. shadowCamera->SetZoom(1.0f / viewSize);
  2023. }
  2024. }
  2025. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2026. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2027. if (shadowCamera->GetZoom() >= 1.0f)
  2028. {
  2029. if (light->GetLightType() != LIGHT_POINT)
  2030. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2031. else
  2032. {
  2033. #ifdef USE_OPENGL
  2034. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2035. #else
  2036. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2037. #endif
  2038. }
  2039. }
  2040. }
  2041. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2042. const BoundingBox& viewBox)
  2043. {
  2044. Node* shadowCameraNode = shadowCamera->GetNode();
  2045. const FocusParameters& parameters = light->GetShadowFocus();
  2046. float shadowMapWidth = (float)(shadowViewport.Width());
  2047. float minX = viewBox.min_.x_;
  2048. float minY = viewBox.min_.y_;
  2049. float maxX = viewBox.max_.x_;
  2050. float maxY = viewBox.max_.y_;
  2051. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2052. Vector2 viewSize(maxX - minX, maxY - minY);
  2053. // Quantize size to reduce swimming
  2054. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2055. if (parameters.nonUniform_)
  2056. {
  2057. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2058. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2059. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2060. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2061. }
  2062. else if (parameters.focus_)
  2063. {
  2064. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2065. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2066. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2067. viewSize.y_ = viewSize.x_;
  2068. }
  2069. shadowCamera->SetOrthoSize(viewSize);
  2070. // Center shadow camera to the view space bounding box
  2071. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2072. Vector3 adjust(center.x_, center.y_, 0.0f);
  2073. shadowCameraNode->Translate(rot * adjust);
  2074. // If the shadow map viewport is known, snap to whole texels
  2075. if (shadowMapWidth > 0.0f)
  2076. {
  2077. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2078. // Take into account that shadow map border will not be used
  2079. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2080. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2081. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2082. shadowCameraNode->Translate(rot * snap);
  2083. }
  2084. }
  2085. void View::FindZone(Drawable* drawable)
  2086. {
  2087. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2088. int bestPriority = M_MIN_INT;
  2089. Zone* newZone = 0;
  2090. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2091. // (possibly incorrect) and must be re-evaluated on the next frame
  2092. bool temporary = !camera_->GetFrustum().IsInside(center);
  2093. // First check if the last zone remains a conclusive result
  2094. Zone* lastZone = drawable->GetLastZone();
  2095. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2096. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2097. newZone = lastZone;
  2098. else
  2099. {
  2100. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2101. {
  2102. Zone* zone = *i;
  2103. int priority = zone->GetPriority();
  2104. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2105. {
  2106. newZone = zone;
  2107. bestPriority = priority;
  2108. }
  2109. }
  2110. }
  2111. drawable->SetZone(newZone, temporary);
  2112. }
  2113. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2114. {
  2115. if (!material)
  2116. {
  2117. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  2118. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  2119. }
  2120. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2121. // If only one technique, no choice
  2122. if (techniques.Size() == 1)
  2123. return techniques[0].technique_;
  2124. else
  2125. {
  2126. float lodDistance = drawable->GetLodDistance();
  2127. // Check for suitable technique. Techniques should be ordered like this:
  2128. // Most distant & highest quality
  2129. // Most distant & lowest quality
  2130. // Second most distant & highest quality
  2131. // ...
  2132. for (unsigned i = 0; i < techniques.Size(); ++i)
  2133. {
  2134. const TechniqueEntry& entry = techniques[i];
  2135. Technique* tech = entry.technique_;
  2136. if (!tech || (tech->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  2137. continue;
  2138. if (lodDistance >= entry.lodDistance_)
  2139. return tech;
  2140. }
  2141. // If no suitable technique found, fallback to the last
  2142. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2143. }
  2144. }
  2145. void View::CheckMaterialForAuxView(Material* material)
  2146. {
  2147. const SharedPtr<Texture>* textures = material->GetTextures();
  2148. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  2149. {
  2150. Texture* texture = textures[i];
  2151. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2152. {
  2153. // Have to check cube & 2D textures separately
  2154. if (texture->GetType() == Texture2D::GetTypeStatic())
  2155. {
  2156. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2157. RenderSurface* target = tex2D->GetRenderSurface();
  2158. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2159. target->QueueUpdate();
  2160. }
  2161. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2162. {
  2163. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2164. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2165. {
  2166. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2167. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2168. target->QueueUpdate();
  2169. }
  2170. }
  2171. }
  2172. }
  2173. // Flag as processed so we can early-out next time we come across this material on the same frame
  2174. material->MarkForAuxView(frame_.frameNumber_);
  2175. }
  2176. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2177. {
  2178. if (!batch.material_)
  2179. batch.material_ = renderer_->GetDefaultMaterial();
  2180. // Convert to instanced if possible
  2181. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer() && !batch.overrideView_)
  2182. batch.geometryType_ = GEOM_INSTANCED;
  2183. if (batch.geometryType_ == GEOM_INSTANCED)
  2184. {
  2185. BatchGroupKey key(batch);
  2186. HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchQueue.batchGroups_.Find(key);
  2187. if (i == batchQueue.batchGroups_.End())
  2188. {
  2189. // Create a new group based on the batch
  2190. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2191. BatchGroup newGroup(batch);
  2192. newGroup.geometryType_ = GEOM_STATIC;
  2193. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2194. newGroup.CalculateSortKey();
  2195. i = batchQueue.batchGroups_.Insert(MakePair(key, newGroup));
  2196. }
  2197. int oldSize = i->second_.instances_.Size();
  2198. i->second_.AddTransforms(batch);
  2199. // Convert to using instancing shaders when the instancing limit is reached
  2200. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2201. {
  2202. i->second_.geometryType_ = GEOM_INSTANCED;
  2203. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2204. i->second_.CalculateSortKey();
  2205. }
  2206. }
  2207. else
  2208. {
  2209. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2210. batch.CalculateSortKey();
  2211. batchQueue.batches_.Push(batch);
  2212. }
  2213. }
  2214. void View::PrepareInstancingBuffer()
  2215. {
  2216. PROFILE(PrepareInstancingBuffer);
  2217. unsigned totalInstances = 0;
  2218. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2219. totalInstances += i->second_.GetNumInstances();
  2220. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2221. {
  2222. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2223. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2224. totalInstances += i->litBaseBatches_.GetNumInstances();
  2225. totalInstances += i->litBatches_.GetNumInstances();
  2226. }
  2227. // If fail to set buffer size, fall back to per-group locking
  2228. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2229. {
  2230. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2231. unsigned freeIndex = 0;
  2232. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2233. if (!dest)
  2234. return;
  2235. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2236. i->second_.SetTransforms(dest, freeIndex);
  2237. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2238. {
  2239. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2240. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2241. i->litBaseBatches_.SetTransforms(dest, freeIndex);
  2242. i->litBatches_.SetTransforms(dest, freeIndex);
  2243. }
  2244. instancingBuffer->Unlock();
  2245. }
  2246. }
  2247. void View::SetupLightVolumeBatch(Batch& batch)
  2248. {
  2249. Light* light = batch.lightQueue_->light_;
  2250. LightType type = light->GetLightType();
  2251. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2252. float lightDist;
  2253. graphics_->SetBlendMode(BLEND_ADD);
  2254. graphics_->SetDepthBias(0.0f, 0.0f);
  2255. graphics_->SetDepthWrite(false);
  2256. graphics_->SetFillMode(FILL_SOLID);
  2257. graphics_->SetClipPlane(false);
  2258. if (type != LIGHT_DIRECTIONAL)
  2259. {
  2260. if (type == LIGHT_POINT)
  2261. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2262. else
  2263. lightDist = light->GetFrustum().Distance(cameraPos);
  2264. // Draw front faces if not inside light volume
  2265. if (lightDist < camera_->GetNearClip() * 2.0f)
  2266. {
  2267. renderer_->SetCullMode(CULL_CW, camera_);
  2268. graphics_->SetDepthTest(CMP_GREATER);
  2269. }
  2270. else
  2271. {
  2272. renderer_->SetCullMode(CULL_CCW, camera_);
  2273. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2274. }
  2275. }
  2276. else
  2277. {
  2278. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2279. // refresh the directional light's model transform before rendering
  2280. light->GetVolumeTransform(camera_);
  2281. graphics_->SetCullMode(CULL_NONE);
  2282. graphics_->SetDepthTest(CMP_ALWAYS);
  2283. }
  2284. graphics_->SetScissorTest(false);
  2285. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2286. }
  2287. void View::RenderShadowMap(const LightBatchQueue& queue)
  2288. {
  2289. PROFILE(RenderShadowMap);
  2290. Texture2D* shadowMap = queue.shadowMap_;
  2291. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2292. graphics_->SetColorWrite(false);
  2293. graphics_->SetFillMode(FILL_SOLID);
  2294. graphics_->SetClipPlane(false);
  2295. graphics_->SetStencilTest(false);
  2296. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2297. graphics_->SetDepthStencil(shadowMap);
  2298. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2299. graphics_->Clear(CLEAR_DEPTH);
  2300. // Set shadow depth bias
  2301. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2302. // Render each of the splits
  2303. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2304. {
  2305. float multiplier = 1.0f;
  2306. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2307. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2308. {
  2309. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2310. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2311. }
  2312. graphics_->SetDepthBias(multiplier * parameters.constantBias_, multiplier * parameters.slopeScaledBias_);
  2313. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2314. if (!shadowQueue.shadowBatches_.IsEmpty())
  2315. {
  2316. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2317. shadowQueue.shadowBatches_.Draw(this);
  2318. }
  2319. }
  2320. graphics_->SetColorWrite(true);
  2321. graphics_->SetDepthBias(0.0f, 0.0f);
  2322. }
  2323. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2324. {
  2325. // If using the backbuffer, return the backbuffer depth-stencil
  2326. if (!renderTarget)
  2327. return 0;
  2328. // Then check for linked depth-stencil
  2329. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2330. // Finally get one from Renderer
  2331. if (!depthStencil)
  2332. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2333. return depthStencil;
  2334. }
  2335. }