View.cpp 97 KB

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