View.cpp 103 KB

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