Renderer.cpp 55 KB

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