Renderer.cpp 56 KB

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