Renderer.cpp 53 KB

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