Renderer.cpp 63 KB

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