View.cpp 100 KB

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