View.cpp 91 KB

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