Renderer.cpp 51 KB

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