Renderer.cpp 54 KB

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