Renderer.cpp 56 KB

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