View.cpp 99 KB

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