Renderer.cpp 47 KB

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