View.cpp 97 KB

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