Renderer.cpp 55 KB

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