View.cpp 113 KB

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