View.cpp 100 KB

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