View.cpp 123 KB

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