Renderer.cpp 56 KB

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