Renderer.cpp 64 KB

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