Renderer.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  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 (!graphics_->GetFallback())
  326. {
  327. if (!depthBuffer_)
  328. {
  329. if (!graphics_->GetHardwareDepthSupport())
  330. {
  331. depthBuffer_ = new Texture2D(context_);
  332. depthBuffer_->SetSize(0, 0, Graphics::GetDepthFormat(), TEXTURE_RENDERTARGET);
  333. }
  334. else
  335. depthBuffer_ = graphics_->GetDepthTexture();
  336. }
  337. }
  338. else
  339. depthBuffer_.Reset();
  340. if (!lightBuffer_)
  341. {
  342. lightBuffer_ = new Texture2D(context_);
  343. lightBuffer_->SetSize(0, 0, Graphics::GetRGBAFormat(), TEXTURE_RENDERTARGET);
  344. }
  345. }
  346. else
  347. {
  348. normalBuffer_.Reset();
  349. depthBuffer_.Reset();
  350. lightBuffer_.Reset();
  351. }
  352. lightPrepass_ = enable;
  353. shadersDirty_ = true;
  354. }
  355. }
  356. void Renderer::SetSpecularLighting(bool enable)
  357. {
  358. specularLighting_ = enable;
  359. }
  360. void Renderer::SetTextureAnisotropy(int level)
  361. {
  362. textureAnisotropy_ = Max(level, 1);
  363. }
  364. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  365. {
  366. textureFilterMode_ = mode;
  367. }
  368. void Renderer::SetTextureQuality(int quality)
  369. {
  370. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  371. if (quality != textureQuality_)
  372. {
  373. textureQuality_ = quality;
  374. ReloadTextures();
  375. }
  376. }
  377. void Renderer::SetMaterialQuality(int quality)
  378. {
  379. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  380. shadersDirty_ = true;
  381. ResetViews();
  382. }
  383. void Renderer::SetDrawShadows(bool enable)
  384. {
  385. if (!graphics_)
  386. return;
  387. drawShadows_ = enable;
  388. if (!drawShadows_)
  389. ResetShadowMaps();
  390. }
  391. void Renderer::SetShadowMapSize(int size)
  392. {
  393. if (!graphics_)
  394. return;
  395. size = NextPowerOfTwo(Max(size, SHADOW_MIN_PIXELS));
  396. if (size != shadowMapSize_)
  397. {
  398. shadowMapSize_ = size;
  399. ResetShadowMaps();
  400. }
  401. }
  402. void Renderer::SetShadowQuality(int quality)
  403. {
  404. if (!graphics_)
  405. return;
  406. quality &= SHADOWQUALITY_HIGH_24BIT;
  407. // If no hardware PCF, do not allow to select one-sample quality
  408. if (!graphics_->GetHardwareShadowSupport())
  409. quality |= SHADOWQUALITY_HIGH_16BIT;
  410. if (!graphics_->GetHiresShadowSupport())
  411. quality &= SHADOWQUALITY_HIGH_16BIT;
  412. if (graphics_->GetFallback())
  413. quality = SHADOWQUALITY_LOW_16BIT;
  414. if (quality != shadowQuality_)
  415. {
  416. shadowQuality_ = quality;
  417. shadersDirty_ = true;
  418. ResetShadowMaps();
  419. }
  420. }
  421. void Renderer::SetReuseShadowMaps(bool enable)
  422. {
  423. if (enable == reuseShadowMaps_)
  424. return;
  425. reuseShadowMaps_ = enable;
  426. }
  427. void Renderer::SetMaxShadowMaps(int shadowMaps)
  428. {
  429. if (shadowMaps < 1)
  430. return;
  431. maxShadowMaps_ = shadowMaps;
  432. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  433. {
  434. if ((int)i->second_.Size() > maxShadowMaps_)
  435. i->second_.Resize(maxShadowMaps_);
  436. }
  437. }
  438. void Renderer::SetMaxShadowCascades(int cascades)
  439. {
  440. cascades = Clamp(cascades, 1, MAX_CASCADE_SPLITS);
  441. if (cascades != maxShadowCascades_)
  442. {
  443. maxShadowCascades_ = cascades;
  444. ResetShadowMaps();
  445. }
  446. }
  447. void Renderer::SetLightStencilMasking(bool enable)
  448. {
  449. lightStencilMasking_ = enable;
  450. }
  451. void Renderer::SetDynamicInstancing(bool enable)
  452. {
  453. if (!instancingBuffer_)
  454. enable = false;
  455. dynamicInstancing_ = enable;
  456. }
  457. void Renderer::SetMaxInstanceTriangles(int triangles)
  458. {
  459. maxInstanceTriangles_ = Max(triangles, 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::SetOccluderSizeThreshold(float screenSize)
  471. {
  472. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  473. }
  474. const Viewport& Renderer::GetViewport(unsigned index) const
  475. {
  476. return index < viewports_.Size() ? viewports_[index] : noViewport;
  477. }
  478. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  479. {
  480. return GetShader(name, vsFormat_, checkExists);
  481. }
  482. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  483. {
  484. return GetShader(name, psFormat_, checkExists);
  485. }
  486. unsigned Renderer::GetNumGeometries(bool allViews) const
  487. {
  488. unsigned numGeometries = 0;
  489. unsigned lastView = allViews ? numViews_ : 1;
  490. for (unsigned i = 0; i < lastView; ++i)
  491. numGeometries += views_[i]->GetGeometries().Size();
  492. return numGeometries;
  493. }
  494. unsigned Renderer::GetNumLights(bool allViews) const
  495. {
  496. unsigned numLights = 0;
  497. unsigned lastView = allViews ? numViews_ : 1;
  498. for (unsigned i = 0; i < lastView; ++i)
  499. numLights += views_[i]->GetLights().Size();
  500. return numLights;
  501. }
  502. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  503. {
  504. unsigned numShadowMaps = 0;
  505. unsigned lastView = allViews ? numViews_ : 1;
  506. for (unsigned i = 0; i < lastView; ++i)
  507. {
  508. const List<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  509. for (List<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  510. {
  511. if (i->shadowMap_)
  512. ++numShadowMaps;
  513. }
  514. }
  515. return numShadowMaps;
  516. }
  517. unsigned Renderer::GetNumOccluders(bool allViews) const
  518. {
  519. unsigned numOccluders = 0;
  520. unsigned lastView = allViews ? numViews_ : 1;
  521. for (unsigned i = 0; i < lastView; ++i)
  522. numOccluders += views_[i]->GetOccluders().Size();
  523. return numOccluders;
  524. }
  525. void Renderer::Update(float timeStep)
  526. {
  527. PROFILE(UpdateViews);
  528. numViews_ = 0;
  529. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  530. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  531. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  532. return;
  533. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  534. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  535. frame_.timeStep_ = timeStep;
  536. frame_.camera_ = 0;
  537. numShadowCameras_ = 0;
  538. numOcclusionBuffers_ = 0;
  539. updateOctrees_.Clear();
  540. // Reload shaders if needed
  541. if (shadersDirty_)
  542. LoadShaders();
  543. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  544. // view dependencies correctly
  545. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  546. {
  547. unsigned mainView = numViews_;
  548. Viewport& viewport = viewports_[i];
  549. if (!AddView(0, viewport))
  550. continue;
  551. // Update octree (perform early update for nodes which need that, and reinsert moved nodes.)
  552. // However, if the same scene is viewed from multiple cameras, update the octree only once
  553. Octree* octree = viewport.scene_->GetComponent<Octree>();
  554. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  555. if (!updateOctrees_.Contains(octree))
  556. {
  557. frame_.camera_ = viewport.camera_;
  558. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  559. if (frame_.viewSize_ == IntVector2::ZERO)
  560. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  561. octree->Update(frame_);
  562. updateOctrees_.Insert(octree);
  563. // Set also the view for the debug graphics already here, so that it can use culling
  564. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  565. if (debug)
  566. debug->SetView(viewport.camera_);
  567. }
  568. // Update the viewport's main view and any auxiliary views it creates
  569. for (unsigned i = mainView; i < numViews_; ++i)
  570. views_[i]->Update(frame_);
  571. }
  572. return;
  573. }
  574. void Renderer::Render()
  575. {
  576. if (!graphics_)
  577. return;
  578. PROFILE(RenderViews);
  579. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  580. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  581. // If no views, just clear the screen
  582. if (!numViews_)
  583. {
  584. numPrimitives_ = 0;
  585. numBatches_ = 0;
  586. graphics_->SetAlphaTest(false);
  587. graphics_->SetBlendMode(BLEND_REPLACE);
  588. graphics_->SetColorWrite(true);
  589. graphics_->SetDepthWrite(true);
  590. graphics_->SetFillMode(FILL_SOLID);
  591. graphics_->SetScissorTest(false);
  592. graphics_->SetStencilTest(false);
  593. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  594. return;
  595. }
  596. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  597. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  598. views_[i]->Render();
  599. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  600. numPrimitives_ = graphics_->GetNumPrimitives();
  601. numBatches_ = graphics_->GetNumBatches();
  602. }
  603. void Renderer::DrawDebugGeometry(bool depthTest)
  604. {
  605. PROFILE(RendererDrawDebug);
  606. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  607. HashSet<Drawable*> processedGeometries;
  608. HashSet<Light*> processedLights;
  609. for (unsigned i = 0; i < numViews_; ++i)
  610. {
  611. // Make sure it's a main view, and process each node only once
  612. View* view = views_[i];
  613. if (view->GetRenderTarget())
  614. continue;
  615. Octree* octree = view->GetOctree();
  616. if (!octree)
  617. continue;
  618. Scene* scene = static_cast<Scene*>(octree->GetNode());
  619. if (!scene)
  620. continue;
  621. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  622. if (!debug)
  623. continue;
  624. const PODVector<Drawable*>& geometries = view->GetGeometries();
  625. const PODVector<Light*>& lights = view->GetLights();
  626. for (unsigned i = 0; i < geometries.Size(); ++i)
  627. {
  628. if (!processedGeometries.Contains(geometries[i]))
  629. {
  630. geometries[i]->DrawDebugGeometry(debug, depthTest);
  631. processedGeometries.Insert(geometries[i]);
  632. }
  633. }
  634. for (unsigned i = 0; i < lights.Size(); ++i)
  635. {
  636. if (!processedLights.Contains(lights[i]))
  637. {
  638. lights[i]->DrawDebugGeometry(debug, depthTest);
  639. processedLights.Insert(lights[i]);
  640. }
  641. }
  642. }
  643. }
  644. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  645. {
  646. // If using a render target texture, make sure it will not be rendered to multiple times
  647. if (renderTarget)
  648. {
  649. for (unsigned i = 0; i < numViews_; ++i)
  650. {
  651. if (views_[i]->GetRenderTarget() == renderTarget)
  652. return false;
  653. }
  654. }
  655. if (views_.Size() <= numViews_)
  656. views_.Resize(numViews_ + 1);
  657. if (!views_[numViews_])
  658. views_[numViews_] = new View(context_);
  659. if (views_[numViews_]->Define(renderTarget, viewport))
  660. {
  661. ++numViews_;
  662. return true;
  663. }
  664. else
  665. return false;
  666. }
  667. Geometry* Renderer::GetLightGeometry(Light* light)
  668. {
  669. LightType type = light->GetLightType();
  670. if (type == LIGHT_DIRECTIONAL)
  671. return dirLightGeometry_;
  672. if (type == LIGHT_SPOT)
  673. return spotLightGeometry_;
  674. else if (type == LIGHT_POINT)
  675. return pointLightGeometry_;
  676. else
  677. return 0;
  678. }
  679. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  680. {
  681. LightType type = light->GetLightType();
  682. const FocusParameters& parameters = light->GetShadowFocus();
  683. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  684. // Automatically reduce shadow map size when far away
  685. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  686. {
  687. Matrix3x4 view(camera->GetInverseWorldTransform());
  688. Matrix4 projection(camera->GetProjection());
  689. BoundingBox lightBox;
  690. float lightPixels;
  691. if (type == LIGHT_POINT)
  692. {
  693. // Calculate point light pixel size from the projection of its diagonal
  694. Vector3 center = view * light->GetWorldPosition();
  695. float extent = 0.58f * light->GetRange();
  696. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  697. }
  698. else
  699. {
  700. // Calculate spot light pixel size from the projection of its frustum far vertices
  701. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  702. lightBox.Define(&lightFrustum.vertices_[4], 4);
  703. }
  704. Vector2 projectionSize = lightBox.Projected(projection).Size();
  705. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  706. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  707. if (lightPixels < SHADOW_MIN_PIXELS)
  708. lightPixels = SHADOW_MIN_PIXELS;
  709. size = Min(size, lightPixels);
  710. }
  711. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  712. int width = NextPowerOfTwo((unsigned)size);
  713. int height = width;
  714. // Adjust the size for directional or point light shadow map atlases
  715. if (type == LIGHT_DIRECTIONAL)
  716. {
  717. if (maxShadowCascades_ > 1)
  718. width *= 2;
  719. if (maxShadowCascades_ > 2)
  720. height *= 2;
  721. }
  722. else if (type == LIGHT_POINT)
  723. {
  724. width *= 2;
  725. height *= 3;
  726. }
  727. int searchKey = (width << 16) | height;
  728. if (shadowMaps_.Contains(searchKey))
  729. {
  730. // If shadow maps are reused, always return the first
  731. if (reuseShadowMaps_)
  732. return shadowMaps_[searchKey][0];
  733. else
  734. {
  735. // If not reused, check allocation count and return existing shadow map if possible
  736. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  737. if (allocated < shadowMaps_[searchKey].Size())
  738. {
  739. shadowMapAllocations_[searchKey].Push(light);
  740. return shadowMaps_[searchKey][allocated];
  741. }
  742. else if ((int)allocated >= maxShadowMaps_)
  743. return 0;
  744. }
  745. }
  746. unsigned shadowMapFormat = (shadowQuality_ & SHADOWQUALITY_LOW_24BIT) ? graphics_->GetHiresShadowMapFormat() :
  747. graphics_->GetShadowMapFormat();
  748. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  749. if (!shadowMapFormat)
  750. return 0;
  751. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  752. int retries = 3;
  753. #ifdef USE_OPENGL
  754. // Create shadow map only. Color render target is not needed
  755. while (retries)
  756. {
  757. if (!newShadowMap->SetSize(width, height, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  758. {
  759. width >>= 1;
  760. height >>= 1;
  761. --retries;
  762. }
  763. else
  764. {
  765. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  766. newShadowMap->SetShadowCompare(true);
  767. break;
  768. }
  769. }
  770. #else
  771. // Create shadow map and dummy color render target
  772. bool fallback = graphics_->GetFallback();
  773. while (retries)
  774. {
  775. if (!newShadowMap->SetSize(width, height, shadowMapFormat, fallback ? TEXTURE_RENDERTARGET : TEXTURE_DEPTHSTENCIL))
  776. {
  777. width >>= 1;
  778. height >>= 1;
  779. --retries;
  780. }
  781. else
  782. {
  783. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  784. if (!fallback)
  785. {
  786. // If no dummy color render target for this size exists yet, create one now
  787. if (!colorShadowMaps_.Contains(searchKey))
  788. {
  789. colorShadowMaps_[searchKey] = new Texture2D(context_);
  790. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  791. }
  792. // Link the color render target to the shadow map
  793. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  794. }
  795. else
  796. {
  797. // In fallback mode link the shared shadow map depth stencil to the shadow map instead.
  798. // Create it first if not created yet, and resize larger if necessary
  799. if (!shadowDepthStencil_)
  800. shadowDepthStencil_ = new Texture2D(context_);
  801. if (shadowDepthStencil_->GetWidth() < width || shadowDepthStencil_->GetHeight() < height)
  802. shadowDepthStencil_->SetSize(width, height, D3DFMT_D16, TEXTURE_DEPTHSTENCIL);
  803. newShadowMap->GetRenderSurface()->SetLinkedDepthBuffer(shadowDepthStencil_->GetRenderSurface());
  804. }
  805. break;
  806. }
  807. }
  808. #endif
  809. // If failed to set size, store a null pointer so that we will not retry
  810. if (!retries)
  811. newShadowMap.Reset();
  812. shadowMaps_[searchKey].Push(newShadowMap);
  813. if (!reuseShadowMaps_)
  814. shadowMapAllocations_[searchKey].Push(light);
  815. return newShadowMap;
  816. }
  817. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  818. {
  819. if (numOcclusionBuffers_ >= occlusionBuffers_.Size())
  820. {
  821. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  822. occlusionBuffers_.Push(newBuffer);
  823. }
  824. int width = occlusionBufferSize_;
  825. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  826. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_];
  827. buffer->SetSize(width, height);
  828. buffer->SetView(camera);
  829. ++numOcclusionBuffers_;
  830. return buffer;
  831. }
  832. Camera* Renderer::GetShadowCamera()
  833. {
  834. MutexLock lock(rendererMutex_);
  835. if (numShadowCameras_ >= shadowCameraNodes_.Size())
  836. {
  837. SharedPtr<Node> newNode(new Node(context_));
  838. newNode->CreateComponent<Camera>();
  839. shadowCameraNodes_.Push(newNode);
  840. }
  841. Camera* camera = shadowCameraNodes_[numShadowCameras_]->GetComponent<Camera>();
  842. camera->SetOrthographic(false);
  843. camera->SetZoom(1.0f);
  844. ++numShadowCameras_;
  845. return camera;
  846. }
  847. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  848. {
  849. String shaderName = shaderPath_;
  850. String variationName;
  851. unsigned split = name.Find('_');
  852. if (split != String::NPOS)
  853. {
  854. shaderName += name.Substring(0, split) + extension;
  855. variationName = name.Substring(split + 1);
  856. }
  857. else
  858. shaderName += name + extension;
  859. if (checkExists)
  860. {
  861. if (!cache_->Exists(shaderName))
  862. return 0;
  863. }
  864. Shader* shader = cache_->GetResource<Shader>(shaderName);
  865. if (shader)
  866. return shader->GetVariation(variationName);
  867. else
  868. return 0;
  869. }
  870. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  871. {
  872. // Check if shaders are unloaded or need reloading
  873. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  874. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  875. if (!vertexShaders.Size() || !pixelShaders.Size() || technique->GetShadersLoadedFrameNumber() !=
  876. shadersChangedFrameNumber_)
  877. {
  878. // First release all previous shaders, then load
  879. technique->ReleaseShaders();
  880. LoadMaterialShaders(technique);
  881. }
  882. // Make sure shaders are loaded now
  883. if (vertexShaders.Size() && pixelShaders.Size())
  884. {
  885. GeometryType geomType = batch.geometryType_;
  886. // If instancing is not supported, but was requested, or the object is too large to be instanced,
  887. // choose static geometry vertex shader instead
  888. if (geomType == GEOM_INSTANCED && (!GetDynamicInstancing() || batch.geometry_->GetIndexCount() >
  889. (unsigned)maxInstanceTriangles_ * 3))
  890. geomType = GEOM_STATIC;
  891. // Check whether is a lit pass. If not, there is only one pixel shader
  892. PassType type = pass->GetType();
  893. if (type == PASS_LIGHT || type == PASS_LITBASE)
  894. {
  895. LightBatchQueue* lightQueue = batch.lightQueue_;
  896. if (!lightQueue)
  897. {
  898. // Do not log error, as it would result in a lot of spam
  899. batch.vertexShader_ = 0;
  900. batch.pixelShader_ = 0;
  901. return;
  902. }
  903. Light* light = lightQueue->light_;
  904. unsigned vsi = 0;
  905. unsigned psi = 0;
  906. vsi = geomType * MAX_LIGHT_VS_VARIATIONS;
  907. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  908. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  909. {
  910. vsi += LVS_SPEC;
  911. psi += LPS_SPEC;
  912. }
  913. if (allowShadows && lightQueue->shadowMap_)
  914. {
  915. vsi += LVS_SHADOW;
  916. psi += LPS_SHADOW;
  917. }
  918. switch (light->GetLightType())
  919. {
  920. case LIGHT_DIRECTIONAL:
  921. vsi += LVS_DIR;
  922. break;
  923. case LIGHT_POINT:
  924. if (light->GetShapeTexture())
  925. psi += LPS_POINTMASK;
  926. else
  927. psi += LPS_POINT;
  928. vsi += LVS_POINT;
  929. break;
  930. case LIGHT_SPOT:
  931. psi += LPS_SPOT;
  932. vsi += LVS_SPOT;
  933. break;
  934. }
  935. batch.vertexShader_ = vertexShaders[vsi];
  936. batch.pixelShader_ = pixelShaders[psi];
  937. // If shadow or specular variations do not exist, try without them
  938. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SHADOW))
  939. {
  940. vsi -= LVS_SHADOW;
  941. psi -= LPS_SHADOW;
  942. batch.vertexShader_ = vertexShaders[vsi];
  943. batch.pixelShader_ = pixelShaders[psi];
  944. }
  945. if ((!batch.vertexShader_ || !batch.pixelShader_) && (vsi >= LVS_SPEC))
  946. {
  947. vsi -= LVS_SPEC;
  948. psi -= LPS_SPEC;
  949. batch.vertexShader_ = vertexShaders[vsi];
  950. batch.pixelShader_ = pixelShaders[psi];
  951. }
  952. }
  953. else
  954. {
  955. if (type == PASS_BASE || type == PASS_MATERIAL)
  956. {
  957. unsigned numVertexLights = 0;
  958. if (batch.lightQueue_)
  959. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  960. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  961. batch.vertexShader_ = vertexShaders[vsi];
  962. // If vertex lights variations do not exist, try without them
  963. if (!batch.vertexShader_)
  964. {
  965. unsigned vsi = geomType * MAX_VERTEXLIGHT_VS_VARIATIONS;
  966. batch.vertexShader_ = vertexShaders[vsi];
  967. }
  968. }
  969. else
  970. {
  971. unsigned vsi = geomType;
  972. batch.vertexShader_ = vertexShaders[vsi];
  973. }
  974. batch.pixelShader_ = pixelShaders[0];
  975. }
  976. }
  977. // Log error if shaders could not be assigned, but only once per technique
  978. if (!batch.vertexShader_ || !batch.pixelShader_)
  979. {
  980. if (!shaderErrorDisplayed_.Contains(technique))
  981. {
  982. shaderErrorDisplayed_.Insert(technique);
  983. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  984. }
  985. }
  986. }
  987. void Renderer::SetLightVolumeShaders(Batch& batch)
  988. {
  989. bool fallback = graphics_->GetFallback();
  990. unsigned vsi = DLVS_NONE;
  991. unsigned psi = DLPS_NONE;
  992. Light* light = batch.lightQueue_->light_;
  993. switch (light->GetLightType())
  994. {
  995. case LIGHT_DIRECTIONAL:
  996. vsi += DLVS_DIR;
  997. break;
  998. case LIGHT_POINT:
  999. if (light->GetShapeTexture())
  1000. psi += DLPS_POINTMASK;
  1001. else
  1002. psi += DLPS_POINT;
  1003. break;
  1004. case LIGHT_SPOT:
  1005. psi += DLPS_SPOT;
  1006. break;
  1007. }
  1008. if (batch.lightQueue_->shadowMap_)
  1009. psi += DLPS_SHADOW;
  1010. if (!fallback && specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1011. psi += DLPS_SPEC;
  1012. if (batch.camera_->IsOrthographic())
  1013. {
  1014. vsi += DLVS_ORTHO;
  1015. psi += DLPS_ORTHO;
  1016. }
  1017. batch.vertexShader_ = lightVS_[vsi];
  1018. batch.pixelShader_ = lightPS_[psi];
  1019. }
  1020. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1021. {
  1022. if (!instancingBuffer_ || !dynamicInstancing_)
  1023. return false;
  1024. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1025. if (numInstances <= oldSize)
  1026. return true;
  1027. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1028. while (newSize < numInstances)
  1029. newSize <<= 1;
  1030. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1031. {
  1032. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1033. // If failed, try to restore the old size
  1034. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1035. return false;
  1036. }
  1037. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1038. return true;
  1039. }
  1040. void Renderer::ResetShadowMapAllocations()
  1041. {
  1042. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1043. i->second_.Clear();
  1044. }
  1045. void Renderer::Initialize()
  1046. {
  1047. Graphics* graphics = GetSubsystem<Graphics>();
  1048. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1049. if (!graphics || !graphics->IsInitialized() || !cache)
  1050. return;
  1051. PROFILE(InitRenderer);
  1052. graphics_ = graphics;
  1053. cache_ = cache;
  1054. // Check shader model support
  1055. #ifndef USE_OPENGL
  1056. if (graphics_->GetSM3Support())
  1057. {
  1058. shaderPath_ = "Shaders/SM3/";
  1059. vsFormat_ = ".vs3";
  1060. psFormat_ = ".ps3";
  1061. }
  1062. else
  1063. {
  1064. shaderPath_ = "Shaders/SM2/";
  1065. vsFormat_ = ".vs2";
  1066. psFormat_ = ".ps2";
  1067. }
  1068. #else
  1069. {
  1070. shaderPath_ = "Shaders/GLSL/";
  1071. vsFormat_ = ".vert";
  1072. psFormat_ = ".frag";
  1073. }
  1074. #endif
  1075. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1076. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1077. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  1078. CreateGeometries();
  1079. CreateInstancingBuffer();
  1080. viewports_.Resize(1);
  1081. ResetViews();
  1082. ResetShadowMaps();
  1083. shadersDirty_ = true;
  1084. initialized_ = true;
  1085. LOGINFO("Initialized renderer");
  1086. }
  1087. void Renderer::ResetViews()
  1088. {
  1089. views_.Clear();
  1090. numViews_ = 0;
  1091. }
  1092. void Renderer::LoadShaders()
  1093. {
  1094. LOGINFO("Reloading shaders");
  1095. // Release old material shaders, mark them for reload
  1096. ReleaseMaterialShaders();
  1097. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1098. // Load inbuilt shaders
  1099. stencilVS_ = GetVertexShader("Stencil");
  1100. stencilPS_ = GetPixelShader("Stencil");
  1101. lightVS_.Clear();
  1102. lightPS_.Clear();
  1103. if (lightPrepass_)
  1104. {
  1105. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  1106. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1107. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1108. unsigned fallback = graphics_->GetFallback() ? 1 : 0;
  1109. if (fallback)
  1110. shadows = SHADOWQUALITY_HIGH_16BIT;
  1111. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_VS_VARIATIONS; ++i)
  1112. lightVS_[i] = GetVertexShader("LightVolume_" + deferredLightVSVariations[i]);
  1113. for (unsigned i = 0; i < lightPS_.Size(); ++i)
  1114. {
  1115. // Specular variations do not exist for fallback shaders, so skip
  1116. if (fallback && i & DLPS_SPEC)
  1117. continue;
  1118. /// \todo Allow specifying the light volume shader name for different lighting models
  1119. String linearDepth = linearVariations[(!fallback && !graphics_->GetHardwareDepthSupport() && i < DLPS_ORTHO) ? 1 : 0];
  1120. if (i & DLPS_SHADOW)
  1121. {
  1122. lightPS_[i] = GetPixelShader("LightVolume_" + linearDepth + lightPSVariations[i % DLPS_ORTHO] +
  1123. shadowVariations[shadows] + fallbackVariations[fallback]);
  1124. }
  1125. else
  1126. {
  1127. lightPS_[i] = GetPixelShader("LightVolume_" + linearDepth + lightPSVariations[i % DLPS_ORTHO] +
  1128. fallbackVariations[fallback]);
  1129. }
  1130. }
  1131. }
  1132. shadersDirty_ = false;
  1133. }
  1134. void Renderer::LoadMaterialShaders(Technique* technique)
  1135. {
  1136. if (lightPrepass_ && technique->HasPass(PASS_GBUFFER))
  1137. {
  1138. LoadPassShaders(technique, PASS_GBUFFER);
  1139. LoadPassShaders(technique, PASS_MATERIAL);
  1140. }
  1141. else
  1142. {
  1143. LoadPassShaders(technique, PASS_BASE);
  1144. LoadPassShaders(technique, PASS_LITBASE);
  1145. LoadPassShaders(technique, PASS_LIGHT);
  1146. }
  1147. LoadPassShaders(technique, PASS_PREALPHA);
  1148. LoadPassShaders(technique, PASS_POSTALPHA);
  1149. LoadPassShaders(technique, PASS_SHADOW);
  1150. }
  1151. void Renderer::LoadPassShaders(Technique* technique, PassType type, bool allowShadows)
  1152. {
  1153. Pass* pass = technique->GetPass(type);
  1154. if (!pass)
  1155. return;
  1156. unsigned shadows = (graphics_->GetHardwareShadowSupport() ? 1 : 0) | (shadowQuality_ & SHADOWQUALITY_HIGH_16BIT);
  1157. unsigned fallback = graphics_->GetFallback() ? 1 : 0;
  1158. if (fallback)
  1159. shadows = SHADOWQUALITY_HIGH_16BIT;
  1160. String vertexShaderName = pass->GetVertexShaderName();
  1161. String pixelShaderName = pass->GetPixelShaderName();
  1162. // Check if the shader name is already a variation in itself
  1163. if (vertexShaderName.Find('_') == String::NPOS)
  1164. vertexShaderName += "_";
  1165. if (pixelShaderName.Find('_') == String::NPOS)
  1166. pixelShaderName += "_";
  1167. // If hardware depth is used, do not write depth into a rendertarget in the G-buffer pass
  1168. // Also check for fallback G-buffer (different layout)
  1169. if (type == PASS_GBUFFER)
  1170. {
  1171. unsigned hwDepth = graphics_->GetHardwareDepthSupport() ? 1 : 0;
  1172. vertexShaderName += hwVariations[hwDepth];
  1173. pixelShaderName += hwVariations[hwDepth];
  1174. pixelShaderName += fallbackVariations[fallback];
  1175. }
  1176. if (type == PASS_SHADOW)
  1177. {
  1178. vertexShaderName += fallbackVariations[fallback];
  1179. pixelShaderName += fallbackVariations[fallback];
  1180. }
  1181. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1182. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1183. // Forget all the old shaders
  1184. vertexShaders.Clear();
  1185. pixelShaders.Clear();
  1186. if (type == PASS_LIGHT || type == PASS_LITBASE)
  1187. {
  1188. // If ambient pass is transparent, and shadow maps are reused, do not load shadow variations
  1189. if (reuseShadowMaps_)
  1190. {
  1191. if (!technique->HasPass(PASS_BASE) || technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE)
  1192. allowShadows = false;
  1193. }
  1194. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1195. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS);
  1196. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1197. {
  1198. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1199. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1200. if (l < LVS_SHADOW || allowShadows)
  1201. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  1202. else
  1203. vertexShaders[j].Reset();
  1204. }
  1205. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS; ++j)
  1206. {
  1207. if (j & LPS_SHADOW)
  1208. {
  1209. if (allowShadows)
  1210. {
  1211. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] + shadowVariations[shadows] +
  1212. fallbackVariations[fallback]);
  1213. }
  1214. else
  1215. pixelShaders[j].Reset();
  1216. }
  1217. else
  1218. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  1219. }
  1220. }
  1221. else
  1222. {
  1223. if (type == PASS_BASE || type == PASS_MATERIAL)
  1224. {
  1225. vertexShaders.Resize(MAX_VERTEXLIGHT_VS_VARIATIONS * MAX_GEOMETRYTYPES);
  1226. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1227. {
  1228. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1229. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1230. vertexShaders[j] = GetVertexShader(vertexShaderName + vertexLightVSVariations[l] + geometryVSVariations[g], g != 0 || l != 0);
  1231. }
  1232. }
  1233. else
  1234. {
  1235. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1236. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1237. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  1238. }
  1239. pixelShaders.Resize(1);
  1240. pixelShaders[0] = GetPixelShader(pixelShaderName);
  1241. }
  1242. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  1243. }
  1244. void Renderer::ReleaseMaterialShaders()
  1245. {
  1246. PODVector<Material*> materials;
  1247. cache_->GetResources<Material>(materials);
  1248. for (unsigned i = 0; i < materials.Size(); ++i)
  1249. materials[i]->ReleaseShaders();
  1250. }
  1251. void Renderer::ReloadTextures()
  1252. {
  1253. PODVector<Resource*> textures;
  1254. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  1255. for (unsigned i = 0; i < textures.Size(); ++i)
  1256. cache_->ReloadResource(textures[i]);
  1257. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  1258. for (unsigned i = 0; i < textures.Size(); ++i)
  1259. cache_->ReloadResource(textures[i]);
  1260. }
  1261. void Renderer::CreateGeometries()
  1262. {
  1263. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1264. dlvb->SetSize(4, MASK_POSITION);
  1265. dlvb->SetData(dirLightVertexData);
  1266. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1267. dlib->SetSize(6, false);
  1268. dlib->SetData(dirLightIndexData);
  1269. dirLightGeometry_ = new Geometry(context_);
  1270. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1271. dirLightGeometry_->SetIndexBuffer(dlib);
  1272. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1273. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1274. slvb->SetSize(8, MASK_POSITION);
  1275. slvb->SetData(spotLightVertexData);
  1276. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1277. slib->SetSize(36, false);
  1278. slib->SetData(spotLightIndexData);
  1279. spotLightGeometry_ = new Geometry(context_);
  1280. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1281. spotLightGeometry_->SetIndexBuffer(slib);
  1282. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1283. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1284. plvb->SetSize(24, MASK_POSITION);
  1285. plvb->SetData(pointLightVertexData);
  1286. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1287. plib->SetSize(132, false);
  1288. plib->SetData(pointLightIndexData);
  1289. pointLightGeometry_ = new Geometry(context_);
  1290. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1291. pointLightGeometry_->SetIndexBuffer(plib);
  1292. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1293. faceSelectCubeMap_ = new TextureCube(context_);
  1294. faceSelectCubeMap_->SetNumLevels(1);
  1295. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1296. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1297. unsigned char data[256 * 256 * 4];
  1298. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1299. {
  1300. unsigned axis = i / 2;
  1301. data[0] = (axis == 0) ? 255 : 0;
  1302. data[1] = (axis == 1) ? 255 : 0;
  1303. data[2] = (axis == 2) ? 255 : 0;
  1304. data[3] = 0;
  1305. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1306. }
  1307. indirectionCubeMap_ = new TextureCube(context_);
  1308. indirectionCubeMap_->SetNumLevels(1);
  1309. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1310. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1311. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1312. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1313. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1314. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1315. {
  1316. unsigned char faceX = (i & 1) * 255;
  1317. unsigned char faceY = (i / 2) * 255 / 3;
  1318. unsigned char* dest = data;
  1319. for (unsigned y = 0; y < 256; ++y)
  1320. {
  1321. for (unsigned x = 0; x < 256; ++x)
  1322. {
  1323. #ifdef USE_OPENGL
  1324. *dest++ = x;
  1325. *dest++ = 255 - y;
  1326. *dest++ = faceX;
  1327. *dest++ = 255 * 2 / 3 - faceY;
  1328. #else
  1329. *dest++ = x;
  1330. *dest++ = y;
  1331. *dest++ = faceX;
  1332. *dest++ = faceY;
  1333. #endif
  1334. }
  1335. }
  1336. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1337. }
  1338. }
  1339. void Renderer::CreateInstancingBuffer()
  1340. {
  1341. // Do not create buffer if instancing not supported
  1342. if (!graphics_->GetSM3Support())
  1343. {
  1344. instancingBuffer_.Reset();
  1345. dynamicInstancing_ = false;
  1346. return;
  1347. }
  1348. // If must lock the buffer for each batch group, set a smaller size
  1349. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1350. instancingBuffer_ = new VertexBuffer(context_);
  1351. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1352. {
  1353. instancingBuffer_.Reset();
  1354. dynamicInstancing_ = false;
  1355. }
  1356. }
  1357. void Renderer::ResetShadowMaps()
  1358. {
  1359. shadowMaps_.Clear();
  1360. colorShadowMaps_.Clear();
  1361. shadowDepthStencil_.Reset();
  1362. }
  1363. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1364. {
  1365. if (!initialized_)
  1366. Initialize();
  1367. else
  1368. {
  1369. // When screen mode changes, purge old views
  1370. ResetViews();
  1371. }
  1372. }
  1373. void Renderer::HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData)
  1374. {
  1375. // Reinitialize if already initialized
  1376. if (initialized_)
  1377. Initialize();
  1378. }
  1379. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1380. {
  1381. if (initialized_)
  1382. {
  1383. using namespace RenderUpdate;
  1384. Update(eventData[P_TIMESTEP].GetFloat());
  1385. }
  1386. }