Renderer.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "CoreEvents.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Graphics.h"
  29. #include "GraphicsEvents.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Log.h"
  33. #include "Material.h"
  34. #include "OcclusionBuffer.h"
  35. #include "Octree.h"
  36. #include "Profiler.h"
  37. #include "Renderer.h"
  38. #include "ResourceCache.h"
  39. #include "Scene.h"
  40. #include "Shader.h"
  41. #include "ShaderVariation.h"
  42. #include "Technique.h"
  43. #include "Texture2D.h"
  44. #include "TextureCube.h"
  45. #include "VertexBuffer.h"
  46. #include "View.h"
  47. #include "XMLFile.h"
  48. #include "Zone.h"
  49. #include "DebugNew.h"
  50. static const float dirLightVertexData[] =
  51. {
  52. -1, 1, 0,
  53. 1, 1, 0,
  54. 1, -1, 0,
  55. -1, -1, 0,
  56. };
  57. static const unsigned short dirLightIndexData[] =
  58. {
  59. 0, 1, 2,
  60. 2, 3, 0,
  61. };
  62. static const float pointLightVertexData[] =
  63. {
  64. -0.423169f, -1.000000f, 0.423169f,
  65. -0.423169f, -1.000000f, -0.423169f,
  66. 0.423169f, -1.000000f, -0.423169f,
  67. 0.423169f, -1.000000f, 0.423169f,
  68. 0.423169f, 1.000000f, -0.423169f,
  69. -0.423169f, 1.000000f, -0.423169f,
  70. -0.423169f, 1.000000f, 0.423169f,
  71. 0.423169f, 1.000000f, 0.423169f,
  72. -1.000000f, 0.423169f, -0.423169f,
  73. -1.000000f, -0.423169f, -0.423169f,
  74. -1.000000f, -0.423169f, 0.423169f,
  75. -1.000000f, 0.423169f, 0.423169f,
  76. 0.423169f, 0.423169f, -1.000000f,
  77. 0.423169f, -0.423169f, -1.000000f,
  78. -0.423169f, -0.423169f, -1.000000f,
  79. -0.423169f, 0.423169f, -1.000000f,
  80. 1.000000f, 0.423169f, 0.423169f,
  81. 1.000000f, -0.423169f, 0.423169f,
  82. 1.000000f, -0.423169f, -0.423169f,
  83. 1.000000f, 0.423169f, -0.423169f,
  84. 0.423169f, -0.423169f, 1.000000f,
  85. 0.423169f, 0.423169f, 1.000000f,
  86. -0.423169f, 0.423169f, 1.000000f,
  87. -0.423169f, -0.423169f, 1.000000f
  88. };
  89. static const unsigned short pointLightIndexData[] =
  90. {
  91. 0, 1, 2,
  92. 0, 2, 3,
  93. 4, 5, 6,
  94. 4, 6, 7,
  95. 8, 9, 10,
  96. 8, 10, 11,
  97. 12, 13, 14,
  98. 12, 14, 15,
  99. 16, 17, 18,
  100. 16, 18, 19,
  101. 20, 21, 22,
  102. 20, 22, 23,
  103. 0, 10, 9,
  104. 0, 9, 1,
  105. 13, 2, 1,
  106. 13, 1, 14,
  107. 23, 0, 3,
  108. 23, 3, 20,
  109. 17, 3, 2,
  110. 17, 2, 18,
  111. 21, 7, 6,
  112. 21, 6, 22,
  113. 7, 16, 19,
  114. 7, 19, 4,
  115. 5, 8, 11,
  116. 5, 11, 6,
  117. 4, 12, 15,
  118. 4, 15, 5,
  119. 22, 11, 10,
  120. 22, 10, 23,
  121. 8, 15, 14,
  122. 8, 14, 9,
  123. 12, 19, 18,
  124. 12, 18, 13,
  125. 16, 21, 20,
  126. 16, 20, 17,
  127. 0, 23, 10,
  128. 1, 9, 14,
  129. 2, 13, 18,
  130. 3, 17, 20,
  131. 6, 11, 22,
  132. 5, 15, 8,
  133. 4, 19, 12,
  134. 7, 21, 16
  135. };
  136. static const float spotLightVertexData[] =
  137. {
  138. 0.00001f, 0.00001f, 0.00001f,
  139. 0.00001f, -0.00001f, 0.00001f,
  140. -0.00001f, -0.00001f, 0.00001f,
  141. -0.00001f, 0.00001f, 0.00001f,
  142. 1.00000f, 1.00000f, 0.99999f,
  143. 1.00000f, -1.00000f, 0.99999f,
  144. -1.00000f, -1.00000f, 0.99999f,
  145. -1.00000f, 1.00000f, 0.99999f,
  146. };
  147. static const unsigned short spotLightIndexData[] =
  148. {
  149. 3, 0, 1,
  150. 3, 1, 2,
  151. 0, 4, 5,
  152. 0, 5, 1,
  153. 3, 7, 4,
  154. 3, 4, 0,
  155. 7, 3, 2,
  156. 7, 2, 6,
  157. 6, 2, 1,
  158. 6, 1, 5,
  159. 7, 5, 4,
  160. 7, 6, 5
  161. };
  162. static const String shadowVariations[] =
  163. {
  164. // No specific hardware shadow compare variation on OpenGL, it is always supported
  165. #ifdef USE_OPENGL
  166. "LQ",
  167. "LQ",
  168. "",
  169. ""
  170. #else
  171. "",
  172. "LQHW",
  173. "",
  174. "HW"
  175. #endif
  176. };
  177. static const String hwVariations[] =
  178. {
  179. "",
  180. "HW"
  181. };
  182. static const String geometryVSVariations[] =
  183. {
  184. "",
  185. "Skinned",
  186. "Instanced",
  187. "Billboard"
  188. };
  189. static const String lightVSVariations[] =
  190. {
  191. "Dir",
  192. "Spot",
  193. "Point",
  194. "DirSpec",
  195. "SpotSpec",
  196. "PointSpec",
  197. "DirShadow",
  198. "SpotShadow",
  199. "PointShadow",
  200. "DirSpecShadow",
  201. "SpotSpecShadow",
  202. "PointSpecShadow"
  203. };
  204. static const String vertexLightVSVariations[] =
  205. {
  206. "",
  207. "1VL",
  208. "2VL",
  209. "3VL",
  210. "4VL",
  211. "5VL",
  212. "6VL"
  213. };
  214. static const String deferredLightVSVariations[] =
  215. {
  216. "",
  217. "Dir",
  218. "Ortho",
  219. "OrthoDir"
  220. };
  221. static const String lightPSVariations[] =
  222. {
  223. "Dir",
  224. "Spot",
  225. "Point",
  226. "PointMask",
  227. "DirSpec",
  228. "SpotSpec",
  229. "PointSpec",
  230. "PointMaskSpec",
  231. "DirShadow",
  232. "SpotShadow",
  233. "PointShadow",
  234. "PointMaskShadow",
  235. "DirSpecShadow",
  236. "SpotSpecShadow",
  237. "PointSpecShadow",
  238. "PointMaskSpecShadow"
  239. };
  240. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  241. static const unsigned MAX_BUFFER_AGE = 2000;
  242. OBJECTTYPESTATIC(Renderer);
  243. Renderer::Renderer(Context* context) :
  244. Object(context),
  245. defaultZone_(new Zone(context)),
  246. quadDirLight_(new Light(context)),
  247. renderMode_(RENDER_FORWARD),
  248. textureAnisotropy_(4),
  249. textureFilterMode_(FILTER_TRILINEAR),
  250. textureQuality_(QUALITY_HIGH),
  251. materialQuality_(QUALITY_HIGH),
  252. shadowMapSize_(1024),
  253. shadowQuality_(SHADOWQUALITY_HIGH_16BIT),
  254. maxShadowMaps_(1),
  255. maxShadowCascades_(MAX_CASCADE_SPLITS),
  256. maxInstanceTriangles_(500),
  257. maxSortedInstances_(1000),
  258. maxOccluderTriangles_(5000),
  259. occlusionBufferSize_(256),
  260. occluderSizeThreshold_(0.025f),
  261. numViews_(0),
  262. numOcclusionBuffers_(0),
  263. numShadowCameras_(0),
  264. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  265. specularLighting_(true),
  266. drawShadows_(true),
  267. reuseShadowMaps_(true),
  268. dynamicInstancing_(true),
  269. shadersDirty_(true),
  270. initialized_(false)
  271. {
  272. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  273. SubscribeToEvent(E_GRAPHICSFEATURES, HANDLER(Renderer, HandleGraphicsFeatures));
  274. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  275. quadDirLight_->SetLightType(LIGHT_DIRECTIONAL);
  276. // Try to initialize right now, but skip if screen mode is not yet set
  277. Initialize();
  278. SetNumViewports(1);
  279. }
  280. Renderer::~Renderer()
  281. {
  282. }
  283. void Renderer::SetNumViewports(unsigned num)
  284. {
  285. viewports_.Resize(num);
  286. for (unsigned i = 0; i < viewports_.Size(); ++i)
  287. {
  288. if (!viewports_[i])
  289. viewports_[i] = new Viewport();
  290. }
  291. }
  292. bool Renderer::SetViewport(unsigned index, Viewport* viewport)
  293. {
  294. if (index >= viewports_.Size())
  295. {
  296. LOGERROR("Viewport index out of bounds");
  297. return false;
  298. }
  299. if (!viewport)
  300. {
  301. LOGERROR("Null viewport");
  302. return false;
  303. }
  304. viewports_[index] = viewport;
  305. return true;
  306. }
  307. void Renderer::SetRenderMode(RenderMode mode)
  308. {
  309. if (!initialized_)
  310. {
  311. LOGERROR("Can not switch rendering mode before setting initial screen mode");
  312. return;
  313. }
  314. if (mode == RENDER_PREPASS && !graphics_->GetLightPrepassSupport())
  315. mode = RENDER_FORWARD;
  316. if (mode == RENDER_DEFERRED && !graphics_->GetDeferredSupport())
  317. mode = RENDER_FORWARD;
  318. if (mode != renderMode_)
  319. {
  320. // Deferred rendering is incompatible with hardware multisampling, so set new screen mode with 1x sampling if in use
  321. if (mode != RENDER_FORWARD && graphics_->GetMultiSample() > 1)
  322. {
  323. graphics_->SetMode(graphics_->GetWidth(), graphics_->GetHeight(), graphics_->GetFullscreen(), graphics_->GetVSync(),
  324. graphics_->GetTripleBuffer(), 1);
  325. }
  326. ResetBuffers();
  327. ResetShadowMaps();
  328. renderMode_ = mode;
  329. shadersDirty_ = true;
  330. }
  331. }
  332. void Renderer::SetSpecularLighting(bool enable)
  333. {
  334. specularLighting_ = enable;
  335. }
  336. void Renderer::SetTextureAnisotropy(int level)
  337. {
  338. textureAnisotropy_ = Max(level, 1);
  339. }
  340. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  341. {
  342. textureFilterMode_ = mode;
  343. }
  344. void Renderer::SetTextureQuality(int quality)
  345. {
  346. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  347. if (quality != textureQuality_)
  348. {
  349. textureQuality_ = quality;
  350. ReloadTextures();
  351. }
  352. }
  353. void Renderer::SetMaterialQuality(int quality)
  354. {
  355. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  356. shadersDirty_ = true;
  357. ResetViews();
  358. }
  359. void Renderer::SetDrawShadows(bool enable)
  360. {
  361. if (!graphics_ || !graphics_->GetShadowMapFormat())
  362. return;
  363. drawShadows_ = enable;
  364. if (!drawShadows_)
  365. ResetShadowMaps();
  366. }
  367. void Renderer::SetShadowMapSize(int size)
  368. {
  369. if (!graphics_)
  370. return;
  371. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  372. if (size != shadowMapSize_)
  373. {
  374. shadowMapSize_ = size;
  375. ResetShadowMaps();
  376. }
  377. }
  378. void Renderer::SetShadowQuality(int quality)
  379. {
  380. if (!graphics_)
  381. return;
  382. quality &= SHADOWQUALITY_HIGH_24BIT;
  383. // If no hardware PCF, do not allow to select one-sample quality
  384. if (!graphics_->GetHardwareShadowSupport())
  385. quality |= SHADOWQUALITY_HIGH_16BIT;
  386. if (!graphics_->GetHiresShadowMapFormat())
  387. quality &= SHADOWQUALITY_HIGH_16BIT;
  388. if (quality != shadowQuality_)
  389. {
  390. shadowQuality_ = quality;
  391. shadersDirty_ = true;
  392. ResetShadowMaps();
  393. }
  394. }
  395. void Renderer::SetReuseShadowMaps(bool enable)
  396. {
  397. if (enable == reuseShadowMaps_)
  398. return;
  399. reuseShadowMaps_ = enable;
  400. }
  401. void Renderer::SetMaxShadowMaps(int shadowMaps)
  402. {
  403. if (shadowMaps < 1)
  404. return;
  405. maxShadowMaps_ = shadowMaps;
  406. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  407. {
  408. if ((int)i->second_.Size() > maxShadowMaps_)
  409. i->second_.Resize(maxShadowMaps_);
  410. }
  411. }
  412. void Renderer::SetMaxShadowCascades(int cascades)
  413. {
  414. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  415. if (cascades != maxShadowCascades_)
  416. {
  417. maxShadowCascades_ = cascades;
  418. ResetShadowMaps();
  419. }
  420. }
  421. void Renderer::SetDynamicInstancing(bool enable)
  422. {
  423. if (!instancingBuffer_)
  424. enable = false;
  425. dynamicInstancing_ = enable;
  426. }
  427. void Renderer::SetMaxInstanceTriangles(int triangles)
  428. {
  429. maxInstanceTriangles_ = Max(triangles, 0);
  430. }
  431. void Renderer::SetMaxSortedInstances(int instances)
  432. {
  433. maxSortedInstances_ = Max(instances, 0);
  434. }
  435. void Renderer::SetMaxOccluderTriangles(int triangles)
  436. {
  437. maxOccluderTriangles_ = Max(triangles, 0);
  438. }
  439. void Renderer::SetOcclusionBufferSize(int size)
  440. {
  441. occlusionBufferSize_ = Max(size, 1);
  442. occlusionBuffers_.Clear();
  443. }
  444. void Renderer::SetOccluderSizeThreshold(float screenSize)
  445. {
  446. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  447. }
  448. void Renderer::ReloadShaders()
  449. {
  450. shadersDirty_ = true;
  451. }
  452. Viewport* Renderer::GetViewport(unsigned index) const
  453. {
  454. return index < viewports_.Size() ? viewports_[index] : (Viewport*)0;
  455. }
  456. int Renderer::GetMaxShadowCascades() const
  457. {
  458. // Due to instruction count limits, deferred modes in SM2.0 can only support up to 3 cascades
  459. #ifndef USE_OPENGL
  460. if (renderMode_ != RENDER_FORWARD && !graphics_->GetSM3Support())
  461. return Max(maxShadowCascades_, 3);
  462. #endif
  463. return maxShadowCascades_;
  464. }
  465. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  466. {
  467. return GetShader(VS, name, checkExists);
  468. }
  469. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  470. {
  471. return GetShader(PS, name, checkExists);
  472. }
  473. unsigned Renderer::GetNumGeometries(bool allViews) const
  474. {
  475. unsigned numGeometries = 0;
  476. unsigned lastView = allViews ? numViews_ : 1;
  477. for (unsigned i = 0; i < lastView; ++i)
  478. numGeometries += views_[i]->GetGeometries().Size();
  479. return numGeometries;
  480. }
  481. unsigned Renderer::GetNumLights(bool allViews) const
  482. {
  483. unsigned numLights = 0;
  484. unsigned lastView = allViews ? numViews_ : 1;
  485. for (unsigned i = 0; i < lastView; ++i)
  486. numLights += views_[i]->GetLights().Size();
  487. return numLights;
  488. }
  489. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  490. {
  491. unsigned numShadowMaps = 0;
  492. unsigned lastView = allViews ? numViews_ : 1;
  493. for (unsigned i = 0; i < lastView; ++i)
  494. {
  495. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  496. for (Vector<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  497. {
  498. if (i->shadowMap_)
  499. ++numShadowMaps;
  500. }
  501. }
  502. return numShadowMaps;
  503. }
  504. unsigned Renderer::GetNumOccluders(bool allViews) const
  505. {
  506. unsigned numOccluders = 0;
  507. unsigned lastView = allViews ? numViews_ : 1;
  508. for (unsigned i = 0; i < lastView; ++i)
  509. numOccluders += views_[i]->GetOccluders().Size();
  510. return numOccluders;
  511. }
  512. void Renderer::Update(float timeStep)
  513. {
  514. PROFILE(UpdateViews);
  515. numViews_ = 0;
  516. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  517. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  518. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  519. return;
  520. // Set up the frameinfo structure for this frame
  521. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  522. frame_.timeStep_ = timeStep;
  523. frame_.camera_ = 0;
  524. numShadowCameras_ = 0;
  525. numOcclusionBuffers_ = 0;
  526. updatedOctrees_.Clear();
  527. // Reload shaders now if needed
  528. if (shadersDirty_)
  529. LoadShaders();
  530. // Process all viewports. Use reverse order, because during rendering the order will be reversed again
  531. // to handle auxiliary view dependencies correctly
  532. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  533. {
  534. unsigned mainView = numViews_;
  535. Viewport* viewport = viewports_[i];
  536. if (!viewport || !AddView(0, viewport))
  537. continue;
  538. const IntRect& viewRect = viewport->GetRect();
  539. Scene* scene = viewport->GetScene();
  540. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  541. // However, if the same scene is viewed from multiple cameras, update the octree only once
  542. Octree* octree = scene->GetComponent<Octree>();
  543. if (!updatedOctrees_.Contains(octree))
  544. {
  545. frame_.camera_ = viewport->GetCamera();
  546. frame_.viewSize_ = IntVector2(viewRect.right_ - viewRect.left_, viewRect.bottom_ - viewRect.top_);
  547. if (frame_.viewSize_ == IntVector2::ZERO)
  548. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  549. octree->Update(frame_);
  550. updatedOctrees_.Insert(octree);
  551. // Set also the view for the debug graphics already here, so that it can use culling
  552. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  553. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  554. if (debug)
  555. debug->SetView(viewport->GetCamera());
  556. }
  557. // Update the viewport's main view and any auxiliary views it has created
  558. for (unsigned i = mainView; i < numViews_; ++i)
  559. {
  560. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  561. ResetShadowMapAllocations();
  562. views_[i]->Update(frame_);
  563. }
  564. }
  565. }
  566. void Renderer::Render()
  567. {
  568. if (!graphics_)
  569. return;
  570. PROFILE(RenderViews);
  571. // If the indirection textures have lost content (OpenGL mode only), restore them now
  572. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  573. SetIndirectionTextureData();
  574. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  575. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  576. graphics_->ClearParameterSources();
  577. // If no views, just clear the screen
  578. if (!numViews_)
  579. {
  580. graphics_->SetBlendMode(BLEND_REPLACE);
  581. graphics_->SetColorWrite(true);
  582. graphics_->SetDepthWrite(true);
  583. graphics_->SetScissorTest(false);
  584. graphics_->SetStencilTest(false);
  585. graphics_->ResetRenderTargets();
  586. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  587. numPrimitives_ = 0;
  588. numBatches_ = 0;
  589. }
  590. else
  591. {
  592. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  593. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  594. {
  595. // Screen buffers can be reused between views, as each is rendered completely
  596. PrepareViewRender();
  597. views_[i]->Render();
  598. }
  599. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  600. numPrimitives_ = graphics_->GetNumPrimitives();
  601. numBatches_ = graphics_->GetNumBatches();
  602. }
  603. // Remove unused occlusion buffers and renderbuffers
  604. RemoveUnusedBuffers();
  605. }
  606. void Renderer::DrawDebugGeometry(bool depthTest)
  607. {
  608. PROFILE(RendererDrawDebug);
  609. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  610. HashSet<Drawable*> processedGeometries;
  611. HashSet<Light*> processedLights;
  612. for (unsigned i = 0; i < numViews_; ++i)
  613. {
  614. // Make sure it's a main view, and process each node only once
  615. View* view = views_[i];
  616. if (view->GetRenderTarget())
  617. continue;
  618. Octree* octree = view->GetOctree();
  619. if (!octree)
  620. continue;
  621. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  622. if (!debug)
  623. continue;
  624. const PODVector<Drawable*>& geometries = view->GetGeometries();
  625. const PODVector<Light*>& lights = view->GetLights();
  626. for (unsigned i = 0; i < geometries.Size(); ++i)
  627. {
  628. if (!processedGeometries.Contains(geometries[i]))
  629. {
  630. geometries[i]->DrawDebugGeometry(debug, depthTest);
  631. processedGeometries.Insert(geometries[i]);
  632. }
  633. }
  634. for (unsigned i = 0; i < lights.Size(); ++i)
  635. {
  636. if (!processedLights.Contains(lights[i]))
  637. {
  638. lights[i]->DrawDebugGeometry(debug, depthTest);
  639. processedLights.Insert(lights[i]);
  640. }
  641. }
  642. }
  643. }
  644. bool Renderer::AddView(RenderSurface* renderTarget, Viewport* viewport)
  645. {
  646. // If using a rendertarget texture, make sure it will not be rendered to multiple times
  647. if (renderTarget)
  648. {
  649. for (unsigned i = 0; i < numViews_; ++i)
  650. {
  651. if (views_[i]->GetRenderTarget() == renderTarget)
  652. return false;
  653. }
  654. }
  655. if (views_.Size() <= numViews_)
  656. views_.Resize(numViews_ + 1);
  657. if (!views_[numViews_])
  658. views_[numViews_] = new View(context_);
  659. if (views_[numViews_]->Define(renderTarget, viewport))
  660. {
  661. ++numViews_;
  662. return true;
  663. }
  664. else
  665. return false;
  666. }
  667. Geometry* Renderer::GetLightGeometry(Light* light)
  668. {
  669. LightType type = light->GetLightType();
  670. if (type == LIGHT_DIRECTIONAL)
  671. return dirLightGeometry_;
  672. if (type == LIGHT_SPOT)
  673. return spotLightGeometry_;
  674. else if (type == LIGHT_POINT)
  675. return pointLightGeometry_;
  676. else
  677. return 0;
  678. }
  679. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  680. {
  681. LightType type = light->GetLightType();
  682. const FocusParameters& parameters = light->GetShadowFocus();
  683. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  684. // Automatically reduce shadow map size when far away
  685. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  686. {
  687. const Matrix3x4& view = camera->GetInverseWorldTransform();
  688. const Matrix4& projection = camera->GetProjection();
  689. BoundingBox lightBox;
  690. float lightPixels;
  691. if (type == LIGHT_POINT)
  692. {
  693. // Calculate point light pixel size from the projection of its diagonal
  694. Vector3 center = view * light->GetNode()->GetWorldPosition();
  695. float extent = 0.58f * light->GetRange();
  696. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  697. }
  698. else
  699. {
  700. // Calculate spot light pixel size from the projection of its frustum far vertices
  701. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  702. lightBox.Define(&lightFrustum.vertices_[4], 4);
  703. }
  704. Vector2 projectionSize = lightBox.Projected(projection).Size();
  705. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  706. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  707. if (lightPixels < SHADOW_MIN_PIXELS)
  708. lightPixels = SHADOW_MIN_PIXELS;
  709. size = Min(size, lightPixels);
  710. }
  711. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  712. int width = NextPowerOfTwo((unsigned)size);
  713. int height = width;
  714. // Adjust the size for directional or point light shadow map atlases
  715. if (type == LIGHT_DIRECTIONAL)
  716. {
  717. if (maxShadowCascades_ > 1)
  718. width *= 2;
  719. if (maxShadowCascades_ > 2)
  720. height *= 2;
  721. }
  722. else if (type == LIGHT_POINT)
  723. {
  724. width *= 2;
  725. height *= 3;
  726. }
  727. int searchKey = (width << 16) | height;
  728. if (shadowMaps_.Contains(searchKey))
  729. {
  730. // If shadow maps are reused, always return the first
  731. if (reuseShadowMaps_)
  732. return shadowMaps_[searchKey][0];
  733. else
  734. {
  735. // If not reused, check allocation count and return existing shadow map if possible
  736. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  737. if (allocated < shadowMaps_[searchKey].Size())
  738. {
  739. shadowMapAllocations_[searchKey].Push(light);
  740. return shadowMaps_[searchKey][allocated];
  741. }
  742. else if ((int)allocated >= maxShadowMaps_)
  743. return 0;
  744. }
  745. }
  746. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  747. graphics_->GetShadowMapFormat();
  748. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  749. if (!shadowMapFormat)
  750. return 0;
  751. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  752. int retries = 3;
  753. // OpenGL: create shadow map only. Color rendertarget is not needed
  754. #ifdef USE_OPENGL
  755. while (retries)
  756. {
  757. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  758. {
  759. width >>= 1;
  760. height >>= 1;
  761. --retries;
  762. }
  763. else
  764. {
  765. #ifndef GL_ES_VERSION_2_0
  766. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  767. newShadowMap->SetShadowCompare(true);
  768. #endif
  769. break;
  770. }
  771. }
  772. #else
  773. // Direct3D9: create shadow map and dummy color rendertarget
  774. while (retries)
  775. {
  776. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  777. {
  778. width >>= 1;
  779. height >>= 1;
  780. --retries;
  781. }
  782. else
  783. {
  784. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  785. // If no dummy color rendertarget for this size exists yet, create one now
  786. if (!colorShadowMaps_.Contains(searchKey))
  787. {
  788. colorShadowMaps_[searchKey] = new Texture2D(context_);
  789. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  790. }
  791. // Link the color rendertarget to the shadow map
  792. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  793. break;
  794. }
  795. }
  796. #endif
  797. // If failed to set size, store a null pointer so that we will not retry
  798. if (!retries)
  799. newShadowMap.Reset();
  800. shadowMaps_[searchKey].Push(newShadowMap);
  801. if (!reuseShadowMaps_)
  802. shadowMapAllocations_[searchKey].Push(light);
  803. return newShadowMap;
  804. }
  805. Texture2D* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool filtered)
  806. {
  807. bool depthStencil = (format == Graphics::GetDepthStencilFormat());
  808. if (depthStencil)
  809. filtered = false;
  810. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  811. if (filtered)
  812. searchKey |= 0x8000000000000000LL;
  813. // Return the default depth-stencil if applicable (Direct3D9 only)
  814. if (width <= graphics_->GetWidth() && height <= graphics_->GetHeight() && depthStencil)
  815. {
  816. Texture2D* depthTexture = graphics_->GetDepthTexture();
  817. if (depthTexture)
  818. return depthTexture;
  819. }
  820. // If new size or format, initialize the allocation stats
  821. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  822. screenBufferAllocations_[searchKey] = 0;
  823. unsigned allocations = screenBufferAllocations_[searchKey]++;
  824. if (allocations >= screenBuffers_[searchKey].Size())
  825. {
  826. SharedPtr<Texture2D> newBuffer(new Texture2D(context_));
  827. newBuffer->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  828. if (filtered)
  829. newBuffer->SetFilterMode(FILTER_BILINEAR);
  830. newBuffer->ResetUseTimer();
  831. screenBuffers_[searchKey].Push(newBuffer);
  832. LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  833. return newBuffer;
  834. }
  835. else
  836. {
  837. Texture2D* buffer = screenBuffers_[searchKey][allocations];
  838. buffer->ResetUseTimer();
  839. return buffer;
  840. }
  841. }
  842. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  843. {
  844. // Return the default depth-stencil surface if applicable
  845. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  846. if (width <= graphics_->GetWidth() && height <= graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  847. return 0;
  848. else
  849. return GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat())->GetRenderSurface();
  850. }
  851. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  852. {
  853. if (numOcclusionBuffers_ >= occlusionBuffers_.Size())
  854. {
  855. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  856. occlusionBuffers_.Push(newBuffer);
  857. }
  858. int width = occlusionBufferSize_;
  859. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  860. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_];
  861. buffer->SetSize(width, height);
  862. buffer->SetView(camera);
  863. buffer->ResetUseTimer();
  864. ++numOcclusionBuffers_;
  865. return buffer;
  866. }
  867. Camera* Renderer::GetShadowCamera()
  868. {
  869. MutexLock lock(rendererMutex_);
  870. if (numShadowCameras_ >= shadowCameraNodes_.Size())
  871. {
  872. SharedPtr<Node> newNode(new Node(context_));
  873. newNode->CreateComponent<Camera>();
  874. shadowCameraNodes_.Push(newNode);
  875. }
  876. Camera* camera = shadowCameraNodes_[numShadowCameras_]->GetComponent<Camera>();
  877. camera->SetOrthographic(false);
  878. camera->SetZoom(1.0f);
  879. ++numShadowCameras_;
  880. return camera;
  881. }
  882. ShaderVariation* Renderer::GetShader(ShaderType type, const String& name, bool checkExists) const
  883. {
  884. String shaderName = shaderPath_;
  885. String variationName;
  886. unsigned split = name.Find('_');
  887. if (split != String::NPOS)
  888. {
  889. shaderName += name.Substring(0, split) + ".xml";
  890. variationName = name.Substring(split + 1);
  891. }
  892. else
  893. shaderName += name + ".xml";
  894. if (checkExists)
  895. {
  896. if (!cache_->Exists(shaderName))
  897. return 0;
  898. }
  899. Shader* shader = cache_->GetResource<Shader>(shaderName);
  900. if (shader)
  901. return shader->GetVariation(type, variationName);
  902. else
  903. return 0;
  904. }
  905. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  906. {
  907. // Check if shaders are unloaded or need reloading
  908. Vector<SharedPtr<ShaderVariation> >& vertexShaders = batch.pass_->GetVertexShaders();
  909. Vector<SharedPtr<ShaderVariation> >& pixelShaders = batch.pass_->GetPixelShaders();
  910. if (!vertexShaders.Size() || !pixelShaders.Size() || tech->GetShadersLoadedFrameNumber() !=
  911. shadersChangedFrameNumber_)
  912. {
  913. // First release all previous shaders, then load
  914. tech->ReleaseShaders();
  915. LoadMaterialShaders(tech);
  916. }
  917. // Make sure shaders are loaded now
  918. if (vertexShaders.Size() && pixelShaders.Size())
  919. {
  920. GeometryType geomType = batch.geometryType_;
  921. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  922. // choose static geometry vertex shader instead
  923. if (geomType == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  924. (unsigned)maxInstanceTriangles_ * 3))
  925. geomType = GEOM_STATIC;
  926. if (geomType == GEOM_STATIC_NOINSTANCING)
  927. geomType = GEOM_STATIC;
  928. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  929. PassType type = batch.pass_->GetType();
  930. if (type == PASS_LIGHT || type == PASS_LITBASE)
  931. {
  932. LightBatchQueue* lightQueue = batch.lightQueue_;
  933. if (!lightQueue)
  934. {
  935. // Do not log error, as it would result in a lot of spam
  936. batch.vertexShader_ = 0;
  937. batch.pixelShader_ = 0;
  938. return;
  939. }
  940. Light* light = lightQueue->light_;
  941. unsigned vsi = 0;
  942. unsigned psi = 0;
  943. vsi = geomType * MAX_LIGHT_VS_VARIATIONS;
  944. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  945. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  946. {
  947. vsi += LVS_SPEC;
  948. psi += LPS_SPEC;
  949. }
  950. if (allowShadows && lightQueue->shadowMap_)
  951. {
  952. vsi += LVS_SHADOW;
  953. psi += LPS_SHADOW;
  954. }
  955. switch (light->GetLightType())
  956. {
  957. case LIGHT_DIRECTIONAL:
  958. vsi += LVS_DIR;
  959. break;
  960. case LIGHT_POINT:
  961. if (light->GetShapeTexture())
  962. psi += LPS_POINTMASK;
  963. else
  964. psi += LPS_POINT;
  965. vsi += LVS_POINT;
  966. break;
  967. case LIGHT_SPOT:
  968. psi += LPS_SPOT;
  969. vsi += LVS_SPOT;
  970. break;
  971. }
  972. batch.vertexShader_ = vertexShaders[vsi];
  973. batch.pixelShader_ = pixelShaders[psi];
  974. // If shadow or specular variations do not exist, try without them
  975. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SHADOW))
  976. {
  977. vsi -= LVS_SHADOW;
  978. psi -= LPS_SHADOW;
  979. batch.vertexShader_ = vertexShaders[vsi];
  980. batch.pixelShader_ = pixelShaders[psi];
  981. }
  982. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SPEC))
  983. {
  984. vsi -= LVS_SPEC;
  985. psi -= LPS_SPEC;
  986. batch.vertexShader_ = vertexShaders[vsi];
  987. batch.pixelShader_ = pixelShaders[psi];
  988. }
  989. }
  990. else
  991. {
  992. // Check if pass has vertex lighting support
  993. if (type == PASS_BASE || type == PASS_MATERIAL || type == PASS_DEFERRED)
  994. {
  995. unsigned numVertexLights = 0;
  996. if (batch.lightQueue_)
  997. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  998. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  999. batch.vertexShader_ = vertexShaders[vsi];
  1000. // If vertex lights variations do not exist, try without them
  1001. if (!batch.vertexShader_)
  1002. {
  1003. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS;
  1004. batch.vertexShader_ = vertexShaders[vsi];
  1005. }
  1006. }
  1007. else
  1008. {
  1009. unsigned vsi = geomType;
  1010. batch.vertexShader_ = vertexShaders[vsi];
  1011. }
  1012. batch.pixelShader_ = pixelShaders[0];
  1013. }
  1014. }
  1015. // Log error if shaders could not be assigned, but only once per technique
  1016. if (!batch.vertexShader_ || !batch.pixelShader_)
  1017. {
  1018. if (!shaderErrorDisplayed_.Contains(tech))
  1019. {
  1020. shaderErrorDisplayed_.Insert(tech);
  1021. LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  1022. }
  1023. }
  1024. }
  1025. void Renderer::SetLightVolumeBatchShaders(Batch& batch)
  1026. {
  1027. unsigned vsi = DLVS_NONE;
  1028. unsigned psi = DLPS_NONE;
  1029. Light* light = batch.lightQueue_->light_;
  1030. switch (light->GetLightType())
  1031. {
  1032. case LIGHT_DIRECTIONAL:
  1033. vsi += DLVS_DIR;
  1034. break;
  1035. case LIGHT_POINT:
  1036. if (light->GetShapeTexture())
  1037. psi += DLPS_POINTMASK;
  1038. else
  1039. psi += DLPS_POINT;
  1040. break;
  1041. case LIGHT_SPOT:
  1042. psi += DLPS_SPOT;
  1043. break;
  1044. }
  1045. if (batch.lightQueue_->shadowMap_)
  1046. psi += DLPS_SHADOW;
  1047. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1048. psi += DLPS_SPEC;
  1049. if (batch.camera_->IsOrthographic())
  1050. {
  1051. vsi += DLVS_ORTHO;
  1052. psi += DLPS_ORTHO;
  1053. }
  1054. batch.vertexShader_ = lightVS_[vsi];
  1055. batch.pixelShader_ = lightPS_[psi];
  1056. }
  1057. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1058. {
  1059. // If a camera is specified, check for vertical flipping and reverse culling in that case
  1060. if (camera && camera->GetFlipVertical())
  1061. {
  1062. if (mode == CULL_CW)
  1063. mode = CULL_CCW;
  1064. else if (mode == CULL_CCW)
  1065. mode = CULL_CW;
  1066. }
  1067. graphics_->SetCullMode(mode);
  1068. }
  1069. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1070. {
  1071. if (!instancingBuffer_ || !dynamicInstancing_)
  1072. return false;
  1073. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1074. if (numInstances <= oldSize)
  1075. return true;
  1076. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1077. while (newSize < numInstances)
  1078. newSize <<= 1;
  1079. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1080. {
  1081. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1082. // If failed, try to restore the old size
  1083. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1084. return false;
  1085. }
  1086. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1087. return true;
  1088. }
  1089. void Renderer::SaveScreenBufferAllocations()
  1090. {
  1091. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1092. }
  1093. void Renderer::RestoreScreenBufferAllocations()
  1094. {
  1095. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1096. }
  1097. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1098. {
  1099. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1100. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1101. else
  1102. graphics_->SetScissorTest(false);
  1103. }
  1104. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1105. {
  1106. #ifndef GL_ES_VERSION_2_0
  1107. if (light)
  1108. {
  1109. LightType type = light->GetLightType();
  1110. if (type == LIGHT_DIRECTIONAL)
  1111. {
  1112. graphics_->SetStencilTest(false);
  1113. return;
  1114. }
  1115. Geometry* geometry = GetLightGeometry(light);
  1116. const Matrix3x4& view = camera->GetInverseWorldTransform();
  1117. const Matrix4& projection = camera->GetProjection();
  1118. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1119. float lightDist;
  1120. if (type == LIGHT_POINT)
  1121. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1122. else
  1123. lightDist = light->GetFrustum().Distance(cameraPos);
  1124. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1125. if (lightDist < M_EPSILON)
  1126. {
  1127. graphics_->SetStencilTest(false);
  1128. return;
  1129. }
  1130. // If the stencil value has wrapped, clear the whole stencil first
  1131. if (!lightStencilValue_)
  1132. {
  1133. graphics_->Clear(CLEAR_STENCIL);
  1134. lightStencilValue_ = 1;
  1135. }
  1136. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1137. // to avoid clipping.
  1138. if (lightDist < camera->GetNearClip() * 2.0f)
  1139. {
  1140. SetCullMode(CULL_CW, camera);
  1141. graphics_->SetDepthTest(CMP_GREATER);
  1142. }
  1143. else
  1144. {
  1145. SetCullMode(CULL_CCW, camera);
  1146. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1147. }
  1148. graphics_->SetColorWrite(false);
  1149. graphics_->SetDepthWrite(false);
  1150. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1151. graphics_->SetShaders(stencilVS_, stencilPS_);
  1152. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1153. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1154. geometry->Draw(graphics_);
  1155. graphics_->ClearTransformSources();
  1156. graphics_->SetColorWrite(true);
  1157. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1158. // Increase stencil value for next light
  1159. ++lightStencilValue_;
  1160. }
  1161. else
  1162. graphics_->SetStencilTest(false);
  1163. #endif
  1164. }
  1165. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1166. {
  1167. Pair<Light*, Camera*> combination(light, camera);
  1168. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1169. if (i != lightScissorCache_.End())
  1170. return i->second_;
  1171. const Matrix3x4& view = camera->GetInverseWorldTransform();
  1172. const Matrix4& projection = camera->GetProjection();
  1173. switch (light->GetLightType())
  1174. {
  1175. case LIGHT_POINT:
  1176. {
  1177. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1178. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1179. }
  1180. case LIGHT_SPOT:
  1181. {
  1182. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1183. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1184. }
  1185. default:
  1186. return lightScissorCache_[combination] = Rect::FULL;
  1187. }
  1188. }
  1189. void Renderer::PrepareViewRender()
  1190. {
  1191. ResetScreenBufferAllocations();
  1192. lightScissorCache_.Clear();
  1193. lightStencilValue_ = 1;
  1194. }
  1195. void Renderer::RemoveUnusedBuffers()
  1196. {
  1197. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1198. {
  1199. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1200. {
  1201. LOGDEBUG("Removed unused occlusion buffer");
  1202. occlusionBuffers_.Erase(i);
  1203. }
  1204. }
  1205. for (HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1206. {
  1207. HashMap<long long, Vector<SharedPtr<Texture2D> > >::Iterator current = i++;
  1208. Vector<SharedPtr<Texture2D> >& buffers = current->second_;
  1209. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1210. {
  1211. Texture2D* buffer = buffers[j];
  1212. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1213. {
  1214. LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) + " format " + String(buffer->GetFormat()));
  1215. buffers.Erase(j);
  1216. }
  1217. }
  1218. if (buffers.Empty())
  1219. {
  1220. screenBufferAllocations_.Erase(current->first_);
  1221. screenBuffers_.Erase(current);
  1222. }
  1223. }
  1224. }
  1225. void Renderer::ResetShadowMapAllocations()
  1226. {
  1227. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1228. i->second_.Clear();
  1229. }
  1230. void Renderer::ResetScreenBufferAllocations()
  1231. {
  1232. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1233. i->second_ = 0;
  1234. }
  1235. void Renderer::Initialize()
  1236. {
  1237. Graphics* graphics = GetSubsystem<Graphics>();
  1238. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1239. if (!graphics || !graphics->IsInitialized() || !cache)
  1240. return;
  1241. PROFILE(InitRenderer);
  1242. graphics_ = graphics;
  1243. cache_ = cache;
  1244. #ifndef USE_OPENGL
  1245. shaderPath_ = "Shaders/HLSL/";
  1246. #else
  1247. shaderPath_ = "Shaders/GLSL/";
  1248. #endif
  1249. if (!graphics_->GetShadowMapFormat())
  1250. drawShadows_ = false;
  1251. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1252. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1253. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1254. // If default material not found, create one. This will actually not render properly, but prevents crashing
  1255. if (!defaultMaterial_)
  1256. defaultMaterial_ = new Material(context_);
  1257. CreateGeometries();
  1258. CreateInstancingBuffer();
  1259. viewports_.Resize(1);
  1260. ResetViews();
  1261. ResetShadowMaps();
  1262. ResetBuffers();
  1263. shadersDirty_ = true;
  1264. initialized_ = true;
  1265. LOGINFO("Initialized renderer");
  1266. }
  1267. void Renderer::ResetViews()
  1268. {
  1269. views_.Clear();
  1270. numViews_ = 0;
  1271. }
  1272. void Renderer::LoadShaders()
  1273. {
  1274. LOGINFO("Reloading shaders");
  1275. // Release old material shaders, mark them for reload
  1276. ReleaseMaterialShaders();
  1277. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1278. // Load inbuilt shaders
  1279. stencilVS_ = GetVertexShader("Stencil");
  1280. stencilPS_ = GetPixelShader("Stencil");
  1281. lightVS_.Clear();
  1282. lightPS_.Clear();
  1283. if (renderMode_ != RENDER_FORWARD)
  1284. {
  1285. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  1286. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1287. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1288. String shaderName = renderMode_ == RENDER_PREPASS ? "PrepassLight_" : "DeferredLight_";
  1289. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  1290. lightVS_[i] = GetVertexShader(shaderName + deferredLightVSVariations[i]);
  1291. for (unsigned i = 0; i < lightPS_.Size(); ++i)
  1292. {
  1293. String ortho, hwDepth;
  1294. #ifdef USE_OPENGL
  1295. hwDepth = hwVariations[graphics_->GetHardwareDepthSupport() ? 1 : 0];
  1296. #else
  1297. if (!graphics_->GetHardwareDepthSupport() && i < DLPS_ORTHO)
  1298. ortho = "Linear";
  1299. #endif
  1300. if (i >= DLPS_ORTHO)
  1301. ortho = "Ortho";
  1302. if (i & DLPS_SHADOW)
  1303. {
  1304. lightPS_[i] = GetPixelShader(shaderName + ortho + lightPSVariations[i % DLPS_ORTHO] +
  1305. shadowVariations[shadows] + hwDepth);
  1306. }
  1307. else
  1308. lightPS_[i] = GetPixelShader(shaderName + ortho + lightPSVariations[i % DLPS_ORTHO] + hwDepth);
  1309. }
  1310. }
  1311. shadersDirty_ = false;
  1312. }
  1313. void Renderer::LoadMaterialShaders(Technique* tech)
  1314. {
  1315. if (renderMode_ == RENDER_PREPASS && tech->HasPass(PASS_PREPASS))
  1316. {
  1317. LoadPassShaders(tech, PASS_PREPASS);
  1318. LoadPassShaders(tech, PASS_MATERIAL);
  1319. }
  1320. else if (renderMode_ == RENDER_DEFERRED && tech->HasPass(PASS_DEFERRED))
  1321. LoadPassShaders(tech, PASS_DEFERRED);
  1322. else
  1323. {
  1324. LoadPassShaders(tech, PASS_BASE);
  1325. LoadPassShaders(tech, PASS_LITBASE);
  1326. LoadPassShaders(tech, PASS_LIGHT);
  1327. }
  1328. LoadPassShaders(tech, PASS_PREALPHA);
  1329. LoadPassShaders(tech, PASS_POSTALPHA);
  1330. LoadPassShaders(tech, PASS_SHADOW);
  1331. }
  1332. void Renderer::LoadPassShaders(Technique* tech, PassType type, bool allowShadows)
  1333. {
  1334. Pass* pass = tech->GetPass(type);
  1335. if (!pass)
  1336. return;
  1337. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1338. String vertexShaderName = pass->GetVertexShader();
  1339. String pixelShaderName = pass->GetPixelShader();
  1340. // Check if the shader name is already a variation in itself
  1341. if (vertexShaderName.Find('_') == String::NPOS)
  1342. vertexShaderName += "_";
  1343. if (pixelShaderName.Find('_') == String::NPOS)
  1344. pixelShaderName += "_";
  1345. // If hardware depth is used, choose a G-buffer shader that does not write depth manually
  1346. if (type == PASS_PREPASS || type == PASS_DEFERRED)
  1347. {
  1348. unsigned hwDepth = graphics_->GetHardwareDepthSupport() ? 1 : 0;
  1349. pixelShaderName += hwVariations[hwDepth];
  1350. }
  1351. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1352. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1353. // Forget all the old shaders
  1354. vertexShaders.Clear();
  1355. pixelShaders.Clear();
  1356. if (type == PASS_LIGHT || type == PASS_LITBASE)
  1357. {
  1358. // Load forward pixel lit variations. If material is transparent, and shadow maps are reused,
  1359. // do not load shadowed variations
  1360. if (reuseShadowMaps_)
  1361. {
  1362. if (!tech->HasPass(PASS_BASE) || tech->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  1363. allowShadows = false;
  1364. }
  1365. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1366. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  1367. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1368. {
  1369. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1370. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1371. if (l < LVS_SHADOW || allowShadows)
  1372. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1373. else
  1374. vertexShaders[j].Reset();
  1375. }
  1376. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1377. {
  1378. if (j & LPS_SHADOW)
  1379. {
  1380. if (allowShadows)
  1381. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows]);
  1382. else
  1383. pixelShaders[j].Reset();
  1384. }
  1385. else
  1386. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1387. }
  1388. }
  1389. else
  1390. {
  1391. // Load vertex light variations for forward ambient pass, deferred G-buffer pass and pre-pass material pass
  1392. if (type == PASS_BASE || type == PASS_MATERIAL || type == PASS_DEFERRED)
  1393. {
  1394. vertexShaders.Resize(MAX_VERTEXLIGHT_VS_VARIATIONS * MAX_GEOMETRYTYPES);
  1395. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1396. {
  1397. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1398. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1399. vertexShaders[j] = GetVertexShader(vertexShaderName + vertexLightVSVariations[l] + geometryVSVariations[g],
  1400. g != 0 || l != 0);
  1401. }
  1402. }
  1403. else
  1404. {
  1405. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1406. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1407. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1408. }
  1409. pixelShaders.Resize(1);
  1410. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1411. }
  1412. tech->MarkShadersLoaded(shadersChangedFrameNumber_);
  1413. }
  1414. void Renderer::ReleaseMaterialShaders()
  1415. {
  1416. PODVector<Material*> materials;
  1417. cache_->GetResources<Material>(materials);
  1418. for (unsigned i = 0; i < materials.Size(); ++i)
  1419. materials[i]->ReleaseShaders();
  1420. }
  1421. void Renderer::ReloadTextures()
  1422. {
  1423. PODVector<Resource*> textures;
  1424. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1425. for (unsigned i = 0; i < textures.Size(); ++i)
  1426. cache_->ReloadResource(textures[i]);
  1427. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1428. for (unsigned i = 0; i < textures.Size(); ++i)
  1429. cache_->ReloadResource(textures[i]);
  1430. }
  1431. void Renderer::CreateGeometries()
  1432. {
  1433. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1434. dlvb->SetShadowed(true);
  1435. dlvb->SetSize(4, MASK_POSITION);
  1436. dlvb->SetData(dirLightVertexData);
  1437. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1438. dlib->SetShadowed(true);
  1439. dlib->SetSize(6, false);
  1440. dlib->SetData(dirLightIndexData);
  1441. dirLightGeometry_ = new Geometry(context_);
  1442. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1443. dirLightGeometry_->SetIndexBuffer(dlib);
  1444. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1445. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1446. slvb->SetShadowed(true);
  1447. slvb->SetSize(8, MASK_POSITION);
  1448. slvb->SetData(spotLightVertexData);
  1449. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1450. slib->SetShadowed(true);
  1451. slib->SetSize(36, false);
  1452. slib->SetData(spotLightIndexData);
  1453. spotLightGeometry_ = new Geometry(context_);
  1454. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1455. spotLightGeometry_->SetIndexBuffer(slib);
  1456. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1457. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1458. plvb->SetShadowed(true);
  1459. plvb->SetSize(24, MASK_POSITION);
  1460. plvb->SetData(pointLightVertexData);
  1461. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1462. plib->SetShadowed(true);
  1463. plib->SetSize(132, false);
  1464. plib->SetData(pointLightIndexData);
  1465. pointLightGeometry_ = new Geometry(context_);
  1466. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1467. pointLightGeometry_->SetIndexBuffer(plib);
  1468. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1469. #if !defined(USE_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1470. if (graphics_->GetShadowMapFormat())
  1471. {
  1472. faceSelectCubeMap_ = new TextureCube(context_);
  1473. faceSelectCubeMap_->SetNumLevels(1);
  1474. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1475. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1476. indirectionCubeMap_ = new TextureCube(context_);
  1477. indirectionCubeMap_->SetNumLevels(1);
  1478. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1479. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1480. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1481. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1482. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1483. SetIndirectionTextureData();
  1484. }
  1485. #endif
  1486. }
  1487. void Renderer::SetIndirectionTextureData()
  1488. {
  1489. unsigned char data[256 * 256 * 4];
  1490. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1491. {
  1492. unsigned axis = i / 2;
  1493. data[0] = (axis == 0) ? 255 : 0;
  1494. data[1] = (axis == 1) ? 255 : 0;
  1495. data[2] = (axis == 2) ? 255 : 0;
  1496. data[3] = 0;
  1497. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1498. }
  1499. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1500. {
  1501. unsigned char faceX = (i & 1) * 255;
  1502. unsigned char faceY = (i / 2) * 255 / 3;
  1503. unsigned char* dest = data;
  1504. for (unsigned y = 0; y < 256; ++y)
  1505. {
  1506. for (unsigned x = 0; x < 256; ++x)
  1507. {
  1508. #ifdef USE_OPENGL
  1509. *dest++ = x;
  1510. *dest++ = 255 - y;
  1511. *dest++ = faceX;
  1512. *dest++ = 255 * 2 / 3 - faceY;
  1513. #else
  1514. *dest++ = x;
  1515. *dest++ = y;
  1516. *dest++ = faceX;
  1517. *dest++ = faceY;
  1518. #endif
  1519. }
  1520. }
  1521. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1522. }
  1523. faceSelectCubeMap_->ClearDataLost();
  1524. indirectionCubeMap_->ClearDataLost();
  1525. }
  1526. void Renderer::CreateInstancingBuffer()
  1527. {
  1528. // Do not create buffer if instancing not supported
  1529. if (!graphics_->GetSM3Support())
  1530. {
  1531. instancingBuffer_.Reset();
  1532. dynamicInstancing_ = false;
  1533. return;
  1534. }
  1535. // If must lock the buffer for each batch group, set a smaller size
  1536. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1537. instancingBuffer_ = new VertexBuffer(context_);
  1538. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1539. {
  1540. instancingBuffer_.Reset();
  1541. dynamicInstancing_ = false;
  1542. }
  1543. }
  1544. void Renderer::ResetShadowMaps()
  1545. {
  1546. shadowMaps_.Clear();
  1547. shadowMapAllocations_.Clear();
  1548. colorShadowMaps_.Clear();
  1549. }
  1550. void Renderer::ResetBuffers()
  1551. {
  1552. occlusionBuffers_.Clear();
  1553. screenBuffers_.Clear();
  1554. screenBufferAllocations_.Clear();
  1555. }
  1556. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1557. {
  1558. if (!initialized_)
  1559. Initialize();
  1560. else
  1561. {
  1562. // When screen mode changes, purge old views
  1563. ResetViews();
  1564. }
  1565. }
  1566. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1567. {
  1568. // Reinitialize if already initialized
  1569. if (initialized_)
  1570. Initialize();
  1571. }
  1572. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1573. {
  1574. if (initialized_)
  1575. {
  1576. using namespace RenderUpdate;
  1577. Update(eventData[P_TIMESTEP].GetFloat());
  1578. }
  1579. }