View.cpp 101 KB

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