View.cpp 115 KB

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