Renderer.cpp 55 KB

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