View.cpp 98 KB

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