Renderer.cpp 55 KB

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