Renderer.cpp 62 KB

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