Renderer.cpp 56 KB

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