View.cpp 109 KB

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