Renderer.cpp 56 KB

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