Renderer.cpp 56 KB

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