View.cpp 97 KB

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