View.cpp 96 KB

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