Renderer.cpp 50 KB

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