Renderer.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/CoreEvents.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Camera.h"
  26. #include "../Graphics/DebugRenderer.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Graphics.h"
  29. #include "../Graphics/GraphicsEvents.h"
  30. #include "../Graphics/GraphicsImpl.h"
  31. #include "../Graphics/IndexBuffer.h"
  32. #include "../Graphics/Material.h"
  33. #include "../Graphics/OcclusionBuffer.h"
  34. #include "../Graphics/Octree.h"
  35. #include "../Graphics/Renderer.h"
  36. #include "../Graphics/RenderPath.h"
  37. #include "../Graphics/ShaderVariation.h"
  38. #include "../Graphics/Technique.h"
  39. #include "../Graphics/Texture2D.h"
  40. #include "../Graphics/TextureCube.h"
  41. #include "../Graphics/VertexBuffer.h"
  42. #include "../Graphics/View.h"
  43. #include "../Graphics/Zone.h"
  44. #include "../IO/Log.h"
  45. #include "../Resource/ResourceCache.h"
  46. #include "../Resource/XMLFile.h"
  47. #include "../Scene/Scene.h"
  48. #include "../DebugNew.h"
  49. #ifdef _MSC_VER
  50. #pragma warning(disable:6293)
  51. #endif
  52. namespace Urho3D
  53. {
  54. static const float dirLightVertexData[] =
  55. {
  56. -1, 1, 0,
  57. 1, 1, 0,
  58. 1, -1, 0,
  59. -1, -1, 0,
  60. };
  61. static const unsigned short dirLightIndexData[] =
  62. {
  63. 0, 1, 2,
  64. 2, 3, 0,
  65. };
  66. static const float pointLightVertexData[] =
  67. {
  68. -0.423169f, -1.000000f, 0.423169f,
  69. -0.423169f, -1.000000f, -0.423169f,
  70. 0.423169f, -1.000000f, -0.423169f,
  71. 0.423169f, -1.000000f, 0.423169f,
  72. 0.423169f, 1.000000f, -0.423169f,
  73. -0.423169f, 1.000000f, -0.423169f,
  74. -0.423169f, 1.000000f, 0.423169f,
  75. 0.423169f, 1.000000f, 0.423169f,
  76. -1.000000f, 0.423169f, -0.423169f,
  77. -1.000000f, -0.423169f, -0.423169f,
  78. -1.000000f, -0.423169f, 0.423169f,
  79. -1.000000f, 0.423169f, 0.423169f,
  80. 0.423169f, 0.423169f, -1.000000f,
  81. 0.423169f, -0.423169f, -1.000000f,
  82. -0.423169f, -0.423169f, -1.000000f,
  83. -0.423169f, 0.423169f, -1.000000f,
  84. 1.000000f, 0.423169f, 0.423169f,
  85. 1.000000f, -0.423169f, 0.423169f,
  86. 1.000000f, -0.423169f, -0.423169f,
  87. 1.000000f, 0.423169f, -0.423169f,
  88. 0.423169f, -0.423169f, 1.000000f,
  89. 0.423169f, 0.423169f, 1.000000f,
  90. -0.423169f, 0.423169f, 1.000000f,
  91. -0.423169f, -0.423169f, 1.000000f
  92. };
  93. static const unsigned short pointLightIndexData[] =
  94. {
  95. 0, 1, 2,
  96. 0, 2, 3,
  97. 4, 5, 6,
  98. 4, 6, 7,
  99. 8, 9, 10,
  100. 8, 10, 11,
  101. 12, 13, 14,
  102. 12, 14, 15,
  103. 16, 17, 18,
  104. 16, 18, 19,
  105. 20, 21, 22,
  106. 20, 22, 23,
  107. 0, 10, 9,
  108. 0, 9, 1,
  109. 13, 2, 1,
  110. 13, 1, 14,
  111. 23, 0, 3,
  112. 23, 3, 20,
  113. 17, 3, 2,
  114. 17, 2, 18,
  115. 21, 7, 6,
  116. 21, 6, 22,
  117. 7, 16, 19,
  118. 7, 19, 4,
  119. 5, 8, 11,
  120. 5, 11, 6,
  121. 4, 12, 15,
  122. 4, 15, 5,
  123. 22, 11, 10,
  124. 22, 10, 23,
  125. 8, 15, 14,
  126. 8, 14, 9,
  127. 12, 19, 18,
  128. 12, 18, 13,
  129. 16, 21, 20,
  130. 16, 20, 17,
  131. 0, 23, 10,
  132. 1, 9, 14,
  133. 2, 13, 18,
  134. 3, 17, 20,
  135. 6, 11, 22,
  136. 5, 15, 8,
  137. 4, 19, 12,
  138. 7, 21, 16
  139. };
  140. static const float spotLightVertexData[] =
  141. {
  142. 0.00001f, 0.00001f, 0.00001f,
  143. 0.00001f, -0.00001f, 0.00001f,
  144. -0.00001f, -0.00001f, 0.00001f,
  145. -0.00001f, 0.00001f, 0.00001f,
  146. 1.00000f, 1.00000f, 0.99999f,
  147. 1.00000f, -1.00000f, 0.99999f,
  148. -1.00000f, -1.00000f, 0.99999f,
  149. -1.00000f, 1.00000f, 0.99999f,
  150. };
  151. static const unsigned short spotLightIndexData[] =
  152. {
  153. 3, 0, 1,
  154. 3, 1, 2,
  155. 0, 4, 5,
  156. 0, 5, 1,
  157. 3, 7, 4,
  158. 3, 4, 0,
  159. 7, 3, 2,
  160. 7, 2, 6,
  161. 6, 2, 1,
  162. 6, 1, 5,
  163. 7, 5, 4,
  164. 7, 6, 5
  165. };
  166. static const char* geometryVSVariations[] =
  167. {
  168. "",
  169. "SKINNED ",
  170. "INSTANCED ",
  171. "BILLBOARD ",
  172. "DIRBILLBOARD "
  173. };
  174. static const char* lightVSVariations[] =
  175. {
  176. "PERPIXEL DIRLIGHT ",
  177. "PERPIXEL SPOTLIGHT ",
  178. "PERPIXEL POINTLIGHT ",
  179. "PERPIXEL DIRLIGHT SHADOW ",
  180. "PERPIXEL SPOTLIGHT SHADOW ",
  181. "PERPIXEL POINTLIGHT SHADOW ",
  182. };
  183. static const char* vertexLightVSVariations[] =
  184. {
  185. "",
  186. "NUMVERTEXLIGHTS=1 ",
  187. "NUMVERTEXLIGHTS=2 ",
  188. "NUMVERTEXLIGHTS=3 ",
  189. "NUMVERTEXLIGHTS=4 ",
  190. };
  191. static const char* deferredLightVSVariations[] =
  192. {
  193. "",
  194. "DIRLIGHT ",
  195. "ORTHO ",
  196. "DIRLIGHT ORTHO "
  197. };
  198. static const char* lightPSVariations[] =
  199. {
  200. "PERPIXEL DIRLIGHT ",
  201. "PERPIXEL SPOTLIGHT ",
  202. "PERPIXEL POINTLIGHT ",
  203. "PERPIXEL POINTLIGHT CUBEMASK ",
  204. "PERPIXEL DIRLIGHT SPECULAR ",
  205. "PERPIXEL SPOTLIGHT SPECULAR ",
  206. "PERPIXEL POINTLIGHT SPECULAR ",
  207. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR ",
  208. "PERPIXEL DIRLIGHT SHADOW ",
  209. "PERPIXEL SPOTLIGHT SHADOW ",
  210. "PERPIXEL POINTLIGHT SHADOW ",
  211. "PERPIXEL POINTLIGHT CUBEMASK SHADOW ",
  212. "PERPIXEL DIRLIGHT SPECULAR SHADOW ",
  213. "PERPIXEL SPOTLIGHT SPECULAR SHADOW ",
  214. "PERPIXEL POINTLIGHT SPECULAR SHADOW ",
  215. "PERPIXEL POINTLIGHT CUBEMASK SPECULAR SHADOW "
  216. };
  217. static const char* heightFogVariations[] =
  218. {
  219. "",
  220. "HEIGHTFOG "
  221. };
  222. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  223. static const unsigned MAX_BUFFER_AGE = 1000;
  224. Renderer::Renderer(Context* context) :
  225. Object(context),
  226. defaultZone_(new Zone(context)),
  227. shadowMapFilterInstance_(0),
  228. shadowMapFilter_(0),
  229. textureAnisotropy_(4),
  230. textureFilterMode_(FILTER_TRILINEAR),
  231. textureQuality_(QUALITY_HIGH),
  232. materialQuality_(QUALITY_HIGH),
  233. shadowMapSize_(1024),
  234. shadowQuality_(SHADOWQUALITY_PCF_16BIT),
  235. shadowSoftness_(2.0f),
  236. vsmShadowParams_(0.0000001f, 0.2f),
  237. maxShadowMaps_(1),
  238. minInstances_(2),
  239. maxSortedInstances_(1000),
  240. maxOccluderTriangles_(5000),
  241. occlusionBufferSize_(256),
  242. occluderSizeThreshold_(0.025f),
  243. mobileShadowBiasMul_(2.0f),
  244. mobileShadowBiasAdd_(0.0001f),
  245. numOcclusionBuffers_(0),
  246. numShadowCameras_(0),
  247. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  248. hdrRendering_(false),
  249. specularLighting_(true),
  250. drawShadows_(true),
  251. reuseShadowMaps_(true),
  252. dynamicInstancing_(true),
  253. threadedOcclusion_(false),
  254. shadersDirty_(true),
  255. initialized_(false),
  256. resetViews_(false)
  257. {
  258. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(Renderer, HandleScreenMode));
  259. // Try to initialize right now, but skip if screen mode is not yet set
  260. Initialize();
  261. }
  262. Renderer::~Renderer()
  263. {
  264. }
  265. void Renderer::SetNumViewports(unsigned num)
  266. {
  267. viewports_.Resize(num);
  268. }
  269. void Renderer::SetViewport(unsigned index, Viewport* viewport)
  270. {
  271. if (index >= viewports_.Size())
  272. viewports_.Resize(index + 1);
  273. viewports_[index] = viewport;
  274. }
  275. void Renderer::SetDefaultRenderPath(RenderPath* renderPath)
  276. {
  277. if (renderPath)
  278. defaultRenderPath_ = renderPath;
  279. }
  280. void Renderer::SetDefaultRenderPath(XMLFile* xmlFile)
  281. {
  282. SharedPtr<RenderPath> newRenderPath(new RenderPath());
  283. if (newRenderPath->Load(xmlFile))
  284. defaultRenderPath_ = newRenderPath;
  285. }
  286. void Renderer::SetDefaultTechnique(Technique* technique)
  287. {
  288. defaultTechnique_ = technique;
  289. }
  290. void Renderer::SetHDRRendering(bool enable)
  291. {
  292. hdrRendering_ = enable;
  293. }
  294. void Renderer::SetSpecularLighting(bool enable)
  295. {
  296. specularLighting_ = enable;
  297. }
  298. void Renderer::SetTextureAnisotropy(int level)
  299. {
  300. textureAnisotropy_ = Max(level, 1);
  301. }
  302. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  303. {
  304. textureFilterMode_ = mode;
  305. }
  306. void Renderer::SetTextureQuality(int quality)
  307. {
  308. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  309. if (quality != textureQuality_)
  310. {
  311. textureQuality_ = quality;
  312. ReloadTextures();
  313. }
  314. }
  315. void Renderer::SetMaterialQuality(int quality)
  316. {
  317. quality = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  318. if (quality != materialQuality_)
  319. {
  320. materialQuality_ = quality;
  321. shadersDirty_ = true;
  322. // Reallocate views to not store eg. pass information that might be unnecessary on the new material quality level
  323. resetViews_ = true;
  324. }
  325. }
  326. void Renderer::SetDrawShadows(bool enable)
  327. {
  328. if (!graphics_ || !graphics_->GetShadowMapFormat())
  329. return;
  330. drawShadows_ = enable;
  331. if (!drawShadows_)
  332. ResetShadowMaps();
  333. }
  334. void Renderer::SetShadowMapSize(int size)
  335. {
  336. if (!graphics_)
  337. return;
  338. size = NextPowerOfTwo((unsigned)Max(size, SHADOW_MIN_PIXELS));
  339. if (size != shadowMapSize_)
  340. {
  341. shadowMapSize_ = size;
  342. ResetShadowMaps();
  343. }
  344. }
  345. void Renderer::SetShadowQuality(ShadowQuality quality)
  346. {
  347. if (!graphics_)
  348. return;
  349. // If no hardware PCF, do not allow to select one-sample quality
  350. if (!graphics_->GetHardwareShadowSupport())
  351. {
  352. if (quality == SHADOWQUALITY_SIMPLE_16BIT)
  353. quality = SHADOWQUALITY_PCF_16BIT;
  354. if (quality == SHADOWQUALITY_SIMPLE_24BIT)
  355. quality = SHADOWQUALITY_PCF_24BIT;
  356. }
  357. // if high resolution is not allowed
  358. if (!graphics_->GetHiresShadowMapFormat())
  359. {
  360. if (quality == SHADOWQUALITY_SIMPLE_24BIT)
  361. quality = SHADOWQUALITY_SIMPLE_16BIT;
  362. if (quality == SHADOWQUALITY_PCF_24BIT)
  363. quality = SHADOWQUALITY_PCF_16BIT;
  364. }
  365. if (quality != shadowQuality_)
  366. {
  367. shadowQuality_ = quality;
  368. shadersDirty_ = true;
  369. if (quality == SHADOWQUALITY_BLUR_VSM)
  370. SetShadowMapFilter(this, static_cast<ShadowMapFilter>(&Renderer::BlurShadowMap));
  371. else
  372. SetShadowMapFilter(0, 0);
  373. ResetShadowMaps();
  374. }
  375. }
  376. void Renderer::SetShadowSoftness(float shadowSoftness)
  377. {
  378. shadowSoftness_ = Max(shadowSoftness, 0.0f);
  379. }
  380. void Renderer::SetVSMShadowParameters(float minVariance, float lightBleedingReduction)
  381. {
  382. vsmShadowParams_.x_ = Max(minVariance, 0.0f);
  383. vsmShadowParams_.y_ = Clamp(lightBleedingReduction, 0.0f, 1.0f);
  384. }
  385. void Renderer::SetShadowMapFilter(Object* instance, ShadowMapFilter functionPtr)
  386. {
  387. shadowMapFilterInstance_ = instance;
  388. shadowMapFilter_ = functionPtr;
  389. }
  390. void Renderer::SetReuseShadowMaps(bool enable)
  391. {
  392. reuseShadowMaps_ = enable;
  393. }
  394. void Renderer::SetMaxShadowMaps(int shadowMaps)
  395. {
  396. if (shadowMaps < 1)
  397. return;
  398. maxShadowMaps_ = shadowMaps;
  399. for (HashMap<int, Vector<SharedPtr<Texture2D> > >::Iterator i = shadowMaps_.Begin(); i != shadowMaps_.End(); ++i)
  400. {
  401. if ((int)i->second_.Size() > maxShadowMaps_)
  402. i->second_.Resize((unsigned)maxShadowMaps_);
  403. }
  404. }
  405. void Renderer::SetDynamicInstancing(bool enable)
  406. {
  407. if (!instancingBuffer_)
  408. enable = false;
  409. dynamicInstancing_ = enable;
  410. }
  411. void Renderer::SetMinInstances(int instances)
  412. {
  413. minInstances_ = Max(instances, 2);
  414. }
  415. void Renderer::SetMaxSortedInstances(int instances)
  416. {
  417. maxSortedInstances_ = Max(instances, 0);
  418. }
  419. void Renderer::SetMaxOccluderTriangles(int triangles)
  420. {
  421. maxOccluderTriangles_ = Max(triangles, 0);
  422. }
  423. void Renderer::SetOcclusionBufferSize(int size)
  424. {
  425. occlusionBufferSize_ = Max(size, 1);
  426. occlusionBuffers_.Clear();
  427. }
  428. void Renderer::SetMobileShadowBiasMul(float mul)
  429. {
  430. mobileShadowBiasMul_ = mul;
  431. }
  432. void Renderer::SetMobileShadowBiasAdd(float add)
  433. {
  434. mobileShadowBiasAdd_ = add;
  435. }
  436. void Renderer::SetOccluderSizeThreshold(float screenSize)
  437. {
  438. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  439. }
  440. void Renderer::SetThreadedOcclusion(bool enable)
  441. {
  442. if (enable != threadedOcclusion_)
  443. {
  444. threadedOcclusion_ = enable;
  445. occlusionBuffers_.Clear();
  446. }
  447. }
  448. void Renderer::ReloadShaders()
  449. {
  450. shadersDirty_ = true;
  451. }
  452. void Renderer::ApplyShadowMapFilter(View* view, Texture2D* shadowMap)
  453. {
  454. if (shadowMapFilterInstance_ && shadowMapFilter_)
  455. (shadowMapFilterInstance_->*shadowMapFilter_)(view, shadowMap);
  456. }
  457. Viewport* Renderer::GetViewport(unsigned index) const
  458. {
  459. return index < viewports_.Size() ? viewports_[index] : (Viewport*)0;
  460. }
  461. RenderPath* Renderer::GetDefaultRenderPath() const
  462. {
  463. return defaultRenderPath_;
  464. }
  465. Technique* Renderer::GetDefaultTechnique() const
  466. {
  467. // Assign default when first asked if not assigned yet
  468. if (!defaultTechnique_)
  469. const_cast<SharedPtr<Technique>& >(defaultTechnique_) = GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml");
  470. return defaultTechnique_;
  471. }
  472. unsigned Renderer::GetNumGeometries(bool allViews) const
  473. {
  474. unsigned numGeometries = 0;
  475. unsigned lastView = allViews ? views_.Size() : 1;
  476. for (unsigned i = 0; i < lastView; ++i)
  477. {
  478. // Use the source view's statistics if applicable
  479. View* view = GetActualView(views_[i]);
  480. if (!view)
  481. continue;
  482. numGeometries += view->GetGeometries().Size();
  483. }
  484. return numGeometries;
  485. }
  486. unsigned Renderer::GetNumLights(bool allViews) const
  487. {
  488. unsigned numLights = 0;
  489. unsigned lastView = allViews ? views_.Size() : 1;
  490. for (unsigned i = 0; i < lastView; ++i)
  491. {
  492. View* view = GetActualView(views_[i]);
  493. if (!view)
  494. continue;
  495. numLights += view->GetLights().Size();
  496. }
  497. return numLights;
  498. }
  499. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  500. {
  501. unsigned numShadowMaps = 0;
  502. unsigned lastView = allViews ? views_.Size() : 1;
  503. for (unsigned i = 0; i < lastView; ++i)
  504. {
  505. View* view = GetActualView(views_[i]);
  506. if (!view)
  507. continue;
  508. const Vector<LightBatchQueue>& lightQueues = view->GetLightQueues();
  509. for (Vector<LightBatchQueue>::ConstIterator i = lightQueues.Begin(); i != lightQueues.End(); ++i)
  510. {
  511. if (i->shadowMap_)
  512. ++numShadowMaps;
  513. }
  514. }
  515. return numShadowMaps;
  516. }
  517. unsigned Renderer::GetNumOccluders(bool allViews) const
  518. {
  519. unsigned numOccluders = 0;
  520. unsigned lastView = allViews ? views_.Size() : 1;
  521. for (unsigned i = 0; i < lastView; ++i)
  522. {
  523. View* view = GetActualView(views_[i]);
  524. if (!view)
  525. continue;
  526. numOccluders += view->GetNumActiveOccluders();
  527. }
  528. return numOccluders;
  529. }
  530. void Renderer::Update(float timeStep)
  531. {
  532. URHO3D_PROFILE(UpdateViews);
  533. views_.Clear();
  534. preparedViews_.Clear();
  535. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  536. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  537. if (!graphics_ || !graphics_->IsInitialized() || graphics_->IsDeviceLost())
  538. return;
  539. // Set up the frameinfo structure for this frame
  540. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  541. frame_.timeStep_ = timeStep;
  542. frame_.camera_ = 0;
  543. numShadowCameras_ = 0;
  544. numOcclusionBuffers_ = 0;
  545. updatedOctrees_.Clear();
  546. // Reload shaders now if needed
  547. if (shadersDirty_)
  548. LoadShaders();
  549. // Queue update of the main viewports. Use reverse order, as rendering order is also reverse
  550. // to render auxiliary views before dependant main views
  551. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  552. QueueViewport(0, viewports_[i]);
  553. // Gather other render surfaces that are autoupdated
  554. SendEvent(E_RENDERSURFACEUPDATE);
  555. // Process gathered views. This may queue further views (render surfaces that are only updated when visible)
  556. for (unsigned i = 0; i < queuedViewports_.Size(); ++i)
  557. {
  558. WeakPtr<RenderSurface>& renderTarget = queuedViewports_[i].first_;
  559. WeakPtr<Viewport>& viewport = queuedViewports_[i].second_;
  560. // Null pointer means backbuffer view. Differentiate between that and an expired rendersurface
  561. if ((renderTarget.NotNull() && renderTarget.Expired()) || viewport.Expired())
  562. continue;
  563. // (Re)allocate the view structure if necessary
  564. if (!viewport->GetView() || resetViews_)
  565. viewport->AllocateView();
  566. View* view = viewport->GetView();
  567. assert(view);
  568. // Check if view can be defined successfully (has either valid scene, camera and octree, or no scene passes)
  569. if (!view->Define(renderTarget, viewport))
  570. continue;
  571. views_.Push(WeakPtr<View>(view));
  572. const IntRect& viewRect = viewport->GetRect();
  573. Scene* scene = viewport->GetScene();
  574. if (!scene)
  575. continue;
  576. Octree* octree = scene->GetComponent<Octree>();
  577. // Update octree (perform early update for drawables which need that, and reinsert moved drawables.)
  578. // However, if the same scene is viewed from multiple cameras, update the octree only once
  579. if (!updatedOctrees_.Contains(octree))
  580. {
  581. frame_.camera_ = viewport->GetCamera();
  582. frame_.viewSize_ = viewRect.Size();
  583. if (frame_.viewSize_ == IntVector2::ZERO)
  584. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  585. octree->Update(frame_);
  586. updatedOctrees_.Insert(octree);
  587. // Set also the view for the debug renderer already here, so that it can use culling
  588. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  589. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  590. if (debug && viewport->GetDrawDebug())
  591. debug->SetView(viewport->GetCamera());
  592. }
  593. // Update view. This may queue further views. View will send update begin/end events once its state is set
  594. ResetShadowMapAllocations(); // Each view can reuse the same shadow maps
  595. view->Update(frame_);
  596. }
  597. queuedViewports_.Clear();
  598. resetViews_ = false;
  599. }
  600. void Renderer::Render()
  601. {
  602. // Engine does not render when window is closed or device is lost
  603. assert(graphics_ && graphics_->IsInitialized() && !graphics_->IsDeviceLost());
  604. URHO3D_PROFILE(RenderViews);
  605. // If the indirection textures have lost content (OpenGL mode only), restore them now
  606. if (faceSelectCubeMap_ && faceSelectCubeMap_->IsDataLost())
  607. SetIndirectionTextureData();
  608. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  609. graphics_->SetTextureAnisotropy((unsigned)textureAnisotropy_);
  610. // If no views, just clear the screen
  611. if (views_.Empty())
  612. {
  613. graphics_->SetBlendMode(BLEND_REPLACE);
  614. graphics_->SetColorWrite(true);
  615. graphics_->SetDepthWrite(true);
  616. graphics_->SetScissorTest(false);
  617. graphics_->SetStencilTest(false);
  618. graphics_->ResetRenderTargets();
  619. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, defaultZone_->GetFogColor());
  620. numPrimitives_ = 0;
  621. numBatches_ = 0;
  622. }
  623. else
  624. {
  625. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  626. for (unsigned i = views_.Size() - 1; i < views_.Size(); --i)
  627. {
  628. if (!views_[i])
  629. continue;
  630. using namespace BeginViewRender;
  631. RenderSurface* renderTarget = views_[i]->GetRenderTarget();
  632. VariantMap& eventData = GetEventDataMap();
  633. eventData[P_VIEW] = views_[i];
  634. eventData[P_SURFACE] = renderTarget;
  635. eventData[P_TEXTURE] = (renderTarget ? renderTarget->GetParentTexture() : 0);
  636. eventData[P_SCENE] = views_[i]->GetScene();
  637. eventData[P_CAMERA] = views_[i]->GetCamera();
  638. SendEvent(E_BEGINVIEWRENDER, eventData);
  639. // Screen buffers can be reused between views, as each is rendered completely
  640. PrepareViewRender();
  641. views_[i]->Render();
  642. SendEvent(E_ENDVIEWRENDER, eventData);
  643. }
  644. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  645. numPrimitives_ = graphics_->GetNumPrimitives();
  646. numBatches_ = graphics_->GetNumBatches();
  647. }
  648. // Remove unused occlusion buffers and renderbuffers
  649. RemoveUnusedBuffers();
  650. }
  651. void Renderer::DrawDebugGeometry(bool depthTest)
  652. {
  653. URHO3D_PROFILE(RendererDrawDebug);
  654. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  655. HashSet<Drawable*> processedGeometries;
  656. HashSet<Light*> processedLights;
  657. for (unsigned i = 0; i < views_.Size(); ++i)
  658. {
  659. View* view = views_[i];
  660. if (!view || !view->GetDrawDebug())
  661. continue;
  662. Octree* octree = view->GetOctree();
  663. if (!octree)
  664. continue;
  665. DebugRenderer* debug = octree->GetComponent<DebugRenderer>();
  666. if (!debug || !debug->IsEnabledEffective())
  667. continue;
  668. // Process geometries / lights only once
  669. const PODVector<Drawable*>& geometries = view->GetGeometries();
  670. const PODVector<Light*>& lights = view->GetLights();
  671. for (unsigned i = 0; i < geometries.Size(); ++i)
  672. {
  673. if (!processedGeometries.Contains(geometries[i]))
  674. {
  675. geometries[i]->DrawDebugGeometry(debug, depthTest);
  676. processedGeometries.Insert(geometries[i]);
  677. }
  678. }
  679. for (unsigned i = 0; i < lights.Size(); ++i)
  680. {
  681. if (!processedLights.Contains(lights[i]))
  682. {
  683. lights[i]->DrawDebugGeometry(debug, depthTest);
  684. processedLights.Insert(lights[i]);
  685. }
  686. }
  687. }
  688. }
  689. void Renderer::QueueRenderSurface(RenderSurface* renderTarget)
  690. {
  691. if (renderTarget)
  692. {
  693. unsigned numViewports = renderTarget->GetNumViewports();
  694. for (unsigned i = 0; i < numViewports; ++i)
  695. QueueViewport(renderTarget, renderTarget->GetViewport(i));
  696. }
  697. }
  698. void Renderer::QueueViewport(RenderSurface* renderTarget, Viewport* viewport)
  699. {
  700. if (viewport)
  701. {
  702. Pair<WeakPtr<RenderSurface>, WeakPtr<Viewport> > newView =
  703. MakePair(WeakPtr<RenderSurface>(renderTarget), WeakPtr<Viewport>(viewport));
  704. // Prevent double add of the same rendertarget/viewport combination
  705. if (!queuedViewports_.Contains(newView))
  706. queuedViewports_.Push(newView);
  707. }
  708. }
  709. Geometry* Renderer::GetLightGeometry(Light* light)
  710. {
  711. switch (light->GetLightType())
  712. {
  713. case LIGHT_DIRECTIONAL:
  714. return dirLightGeometry_;
  715. case LIGHT_SPOT:
  716. return spotLightGeometry_;
  717. case LIGHT_POINT:
  718. return pointLightGeometry_;
  719. }
  720. return 0;
  721. }
  722. Geometry* Renderer::GetQuadGeometry()
  723. {
  724. return dirLightGeometry_;
  725. }
  726. Texture2D* Renderer::GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight)
  727. {
  728. LightType type = light->GetLightType();
  729. const FocusParameters& parameters = light->GetShadowFocus();
  730. float size = (float)shadowMapSize_ * light->GetShadowResolution();
  731. // Automatically reduce shadow map size when far away
  732. if (parameters.autoSize_ && type != LIGHT_DIRECTIONAL)
  733. {
  734. const Matrix3x4& view = camera->GetView();
  735. const Matrix4& projection = camera->GetProjection();
  736. BoundingBox lightBox;
  737. float lightPixels;
  738. if (type == LIGHT_POINT)
  739. {
  740. // Calculate point light pixel size from the projection of its diagonal
  741. Vector3 center = view * light->GetNode()->GetWorldPosition();
  742. float extent = 0.58f * light->GetRange();
  743. lightBox.Define(center + Vector3(extent, extent, extent), center - Vector3(extent, extent, extent));
  744. }
  745. else
  746. {
  747. // Calculate spot light pixel size from the projection of its frustum far vertices
  748. Frustum lightFrustum = light->GetFrustum().Transformed(view);
  749. lightBox.Define(&lightFrustum.vertices_[4], 4);
  750. }
  751. Vector2 projectionSize = lightBox.Projected(projection).Size();
  752. lightPixels = Max(0.5f * (float)viewWidth * projectionSize.x_, 0.5f * (float)viewHeight * projectionSize.y_);
  753. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  754. if (lightPixels < SHADOW_MIN_PIXELS)
  755. lightPixels = SHADOW_MIN_PIXELS;
  756. size = Min(size, lightPixels);
  757. }
  758. /// \todo Allow to specify maximum shadow maps per resolution, as smaller shadow maps take less memory
  759. int width = NextPowerOfTwo((unsigned)size);
  760. int height = width;
  761. // Adjust the size for directional or point light shadow map atlases
  762. if (type == LIGHT_DIRECTIONAL)
  763. {
  764. unsigned numSplits = (unsigned)light->GetNumShadowSplits();
  765. if (numSplits > 1)
  766. width *= 2;
  767. if (numSplits > 2)
  768. height *= 2;
  769. }
  770. else if (type == LIGHT_POINT)
  771. {
  772. width *= 2;
  773. height *= 3;
  774. }
  775. int searchKey = (width << 16) | height;
  776. if (shadowMaps_.Contains(searchKey))
  777. {
  778. // If shadow maps are reused, always return the first
  779. if (reuseShadowMaps_)
  780. return shadowMaps_[searchKey][0];
  781. else
  782. {
  783. // If not reused, check allocation count and return existing shadow map if possible
  784. unsigned allocated = shadowMapAllocations_[searchKey].Size();
  785. if (allocated < shadowMaps_[searchKey].Size())
  786. {
  787. shadowMapAllocations_[searchKey].Push(light);
  788. return shadowMaps_[searchKey][allocated];
  789. }
  790. else if ((int)allocated >= maxShadowMaps_)
  791. return 0;
  792. }
  793. }
  794. // Find format and usage of the shadow map
  795. unsigned shadowMapFormat = 0;
  796. TextureUsage shadowMapUsage = TEXTURE_DEPTHSTENCIL;
  797. switch (shadowQuality_)
  798. {
  799. case SHADOWQUALITY_SIMPLE_16BIT:
  800. case SHADOWQUALITY_PCF_16BIT:
  801. shadowMapFormat = graphics_->GetShadowMapFormat();
  802. break;
  803. case SHADOWQUALITY_SIMPLE_24BIT:
  804. case SHADOWQUALITY_PCF_24BIT:
  805. shadowMapFormat = graphics_->GetHiresShadowMapFormat();
  806. break;
  807. case SHADOWQUALITY_VSM:
  808. case SHADOWQUALITY_BLUR_VSM:
  809. shadowMapFormat = graphics_->GetRGFloat32Format();
  810. shadowMapUsage = TEXTURE_RENDERTARGET;
  811. break;
  812. }
  813. if (!shadowMapFormat)
  814. return 0;
  815. SharedPtr<Texture2D> newShadowMap(new Texture2D(context_));
  816. int retries = 3;
  817. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  818. while (retries)
  819. {
  820. if (!newShadowMap->SetSize(width, height, shadowMapFormat, shadowMapUsage))
  821. {
  822. width >>= 1;
  823. height >>= 1;
  824. --retries;
  825. }
  826. else
  827. {
  828. #ifndef GL_ES_VERSION_2_0
  829. // OpenGL (desktop) and D3D11: shadow compare mode needs to be specifically enabled for the shadow map
  830. newShadowMap->SetFilterMode(FILTER_BILINEAR);
  831. newShadowMap->SetShadowCompare(shadowMapUsage == TEXTURE_DEPTHSTENCIL);
  832. #endif
  833. #ifndef URHO3D_OPENGL
  834. // Direct3D9: when shadow compare must be done manually, use nearest filtering so that the filtering of point lights
  835. // and other shadowed lights matches
  836. newShadowMap->SetFilterMode(graphics_->GetHardwareShadowSupport() ? FILTER_BILINEAR : FILTER_NEAREST);
  837. #endif
  838. // Create dummy color texture for the shadow map if necessary: Direct3D9, or OpenGL when working around an OS X +
  839. // Intel driver bug
  840. if (shadowMapUsage == TEXTURE_DEPTHSTENCIL && dummyColorFormat)
  841. {
  842. // If no dummy color rendertarget for this size exists yet, create one now
  843. if (!colorShadowMaps_.Contains(searchKey))
  844. {
  845. colorShadowMaps_[searchKey] = new Texture2D(context_);
  846. colorShadowMaps_[searchKey]->SetSize(width, height, dummyColorFormat, TEXTURE_RENDERTARGET);
  847. }
  848. // Link the color rendertarget to the shadow map
  849. newShadowMap->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[searchKey]->GetRenderSurface());
  850. }
  851. break;
  852. }
  853. }
  854. // If failed to set size, store a null pointer so that we will not retry
  855. if (!retries)
  856. newShadowMap.Reset();
  857. shadowMaps_[searchKey].Push(newShadowMap);
  858. if (!reuseShadowMaps_)
  859. shadowMapAllocations_[searchKey].Push(light);
  860. return newShadowMap;
  861. }
  862. Texture* Renderer::GetScreenBuffer(int width, int height, unsigned format, bool cubemap, bool filtered, bool srgb,
  863. unsigned persistentKey)
  864. {
  865. bool depthStencil = (format == Graphics::GetDepthStencilFormat()) || (format == Graphics::GetReadableDepthFormat());
  866. if (depthStencil)
  867. {
  868. filtered = false;
  869. srgb = false;
  870. }
  871. if (cubemap)
  872. height = width;
  873. long long searchKey = ((long long)format << 32) | (width << 16) | height;
  874. if (filtered)
  875. searchKey |= 0x8000000000000000LL;
  876. if (srgb)
  877. searchKey |= 0x4000000000000000LL;
  878. if (cubemap)
  879. searchKey |= 0x2000000000000000LL;
  880. // Add persistent key if defined
  881. if (persistentKey)
  882. searchKey += ((long long)persistentKey << 32);
  883. // If new size or format, initialize the allocation stats
  884. if (screenBuffers_.Find(searchKey) == screenBuffers_.End())
  885. screenBufferAllocations_[searchKey] = 0;
  886. // Reuse depth-stencil buffers whenever the size matches, instead of allocating new
  887. unsigned allocations = screenBufferAllocations_[searchKey];
  888. if (!depthStencil)
  889. ++screenBufferAllocations_[searchKey];
  890. if (allocations >= screenBuffers_[searchKey].Size())
  891. {
  892. SharedPtr<Texture> newBuffer;
  893. if (!cubemap)
  894. {
  895. SharedPtr<Texture2D> newTex2D(new Texture2D(context_));
  896. newTex2D->SetSize(width, height, format, depthStencil ? TEXTURE_DEPTHSTENCIL : TEXTURE_RENDERTARGET);
  897. #ifdef URHO3D_OPENGL
  898. // OpenGL hack: clear persistent floating point screen buffers to ensure the initial contents aren't illegal (NaN)?
  899. // Otherwise eg. the AutoExposure post process will not work correctly
  900. if (persistentKey && Texture::GetDataType(format) == GL_FLOAT)
  901. {
  902. // Note: this loses current rendertarget assignment
  903. graphics_->ResetRenderTargets();
  904. graphics_->SetRenderTarget(0, newTex2D);
  905. graphics_->SetDepthStencil((RenderSurface*)0);
  906. graphics_->SetViewport(IntRect(0, 0, width, height));
  907. graphics_->Clear(CLEAR_COLOR);
  908. }
  909. #endif
  910. newBuffer = newTex2D;
  911. }
  912. else
  913. {
  914. SharedPtr<TextureCube> newTexCube(new TextureCube(context_));
  915. newTexCube->SetSize(width, format, TEXTURE_RENDERTARGET);
  916. newBuffer = newTexCube;
  917. }
  918. newBuffer->SetSRGB(srgb);
  919. newBuffer->SetFilterMode(filtered ? FILTER_BILINEAR : FILTER_NEAREST);
  920. newBuffer->ResetUseTimer();
  921. screenBuffers_[searchKey].Push(newBuffer);
  922. URHO3D_LOGDEBUG("Allocated new screen buffer size " + String(width) + "x" + String(height) + " format " + String(format));
  923. return newBuffer;
  924. }
  925. else
  926. {
  927. Texture* buffer = screenBuffers_[searchKey][allocations];
  928. buffer->ResetUseTimer();
  929. return buffer;
  930. }
  931. }
  932. RenderSurface* Renderer::GetDepthStencil(int width, int height)
  933. {
  934. // Return the default depth-stencil surface if applicable
  935. // (when using OpenGL Graphics will allocate right size surfaces on demand to emulate Direct3D9)
  936. if (width == graphics_->GetWidth() && height == graphics_->GetHeight() && graphics_->GetMultiSample() <= 1)
  937. return 0;
  938. else
  939. {
  940. return static_cast<Texture2D*>(GetScreenBuffer(width, height, Graphics::GetDepthStencilFormat(), false, false,
  941. false))->GetRenderSurface();
  942. }
  943. }
  944. OcclusionBuffer* Renderer::GetOcclusionBuffer(Camera* camera)
  945. {
  946. assert(numOcclusionBuffers_ <= occlusionBuffers_.Size());
  947. if (numOcclusionBuffers_ == occlusionBuffers_.Size())
  948. {
  949. SharedPtr<OcclusionBuffer> newBuffer(new OcclusionBuffer(context_));
  950. occlusionBuffers_.Push(newBuffer);
  951. }
  952. int width = occlusionBufferSize_;
  953. int height = (int)((float)occlusionBufferSize_ / camera->GetAspectRatio() + 0.5f);
  954. OcclusionBuffer* buffer = occlusionBuffers_[numOcclusionBuffers_++];
  955. buffer->SetSize(width, height, threadedOcclusion_);
  956. buffer->SetView(camera);
  957. buffer->ResetUseTimer();
  958. return buffer;
  959. }
  960. Camera* Renderer::GetShadowCamera()
  961. {
  962. MutexLock lock(rendererMutex_);
  963. assert(numShadowCameras_ <= shadowCameraNodes_.Size());
  964. if (numShadowCameras_ == shadowCameraNodes_.Size())
  965. {
  966. SharedPtr<Node> newNode(new Node(context_));
  967. newNode->CreateComponent<Camera>();
  968. shadowCameraNodes_.Push(newNode);
  969. }
  970. Camera* camera = shadowCameraNodes_[numShadowCameras_++]->GetComponent<Camera>();
  971. camera->SetOrthographic(false);
  972. camera->SetZoom(1.0f);
  973. return camera;
  974. }
  975. void Renderer::StorePreparedView(View* view, Camera* camera)
  976. {
  977. if (view && camera)
  978. preparedViews_[camera] = view;
  979. }
  980. View* Renderer::GetPreparedView(Camera* camera)
  981. {
  982. HashMap<Camera*, WeakPtr<View> >::Iterator i = preparedViews_.Find(camera);
  983. return i != preparedViews_.End() ? i->second_ : (View*)0;
  984. }
  985. View* Renderer::GetActualView(View* view)
  986. {
  987. if (view && view->GetSourceView())
  988. return view->GetSourceView();
  989. else
  990. return view;
  991. }
  992. void Renderer::SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows)
  993. {
  994. // Check if shaders are unloaded or need reloading
  995. Pass* pass = batch.pass_;
  996. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  997. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  998. if (!vertexShaders.Size() || !pixelShaders.Size() || pass->GetShadersLoadedFrameNumber() != shadersChangedFrameNumber_)
  999. {
  1000. // First release all previous shaders, then load
  1001. pass->ReleaseShaders();
  1002. LoadPassShaders(pass);
  1003. }
  1004. // Make sure shaders are loaded now
  1005. if (vertexShaders.Size() && pixelShaders.Size())
  1006. {
  1007. bool heightFog = batch.zone_ && batch.zone_->GetHeightFog();
  1008. // If instancing is not supported, but was requested, choose static geometry vertex shader instead
  1009. if (batch.geometryType_ == GEOM_INSTANCED && !GetDynamicInstancing())
  1010. batch.geometryType_ = GEOM_STATIC;
  1011. if (batch.geometryType_ == GEOM_STATIC_NOINSTANCING)
  1012. batch.geometryType_ = GEOM_STATIC;
  1013. // Check whether is a pixel lit forward pass. If not, there is only one pixel shader
  1014. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  1015. {
  1016. LightBatchQueue* lightQueue = batch.lightQueue_;
  1017. if (!lightQueue)
  1018. {
  1019. // Do not log error, as it would result in a lot of spam
  1020. batch.vertexShader_ = 0;
  1021. batch.pixelShader_ = 0;
  1022. return;
  1023. }
  1024. Light* light = lightQueue->light_;
  1025. unsigned vsi = 0;
  1026. unsigned psi = 0;
  1027. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  1028. bool materialHasSpecular = batch.material_ ? batch.material_->GetSpecular() : true;
  1029. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f && materialHasSpecular)
  1030. psi += LPS_SPEC;
  1031. if (allowShadows && lightQueue->shadowMap_)
  1032. {
  1033. vsi += LVS_SHADOW;
  1034. psi += LPS_SHADOW;
  1035. }
  1036. switch (light->GetLightType())
  1037. {
  1038. case LIGHT_DIRECTIONAL:
  1039. vsi += LVS_DIR;
  1040. break;
  1041. case LIGHT_SPOT:
  1042. psi += LPS_SPOT;
  1043. vsi += LVS_SPOT;
  1044. break;
  1045. case LIGHT_POINT:
  1046. if (light->GetShapeTexture())
  1047. psi += LPS_POINTMASK;
  1048. else
  1049. psi += LPS_POINT;
  1050. vsi += LVS_POINT;
  1051. break;
  1052. }
  1053. if (heightFog)
  1054. psi += MAX_LIGHT_PS_VARIATIONS;
  1055. batch.vertexShader_ = vertexShaders[vsi];
  1056. batch.pixelShader_ = pixelShaders[psi];
  1057. }
  1058. else
  1059. {
  1060. // Check if pass has vertex lighting support
  1061. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1062. {
  1063. unsigned numVertexLights = 0;
  1064. if (batch.lightQueue_)
  1065. numVertexLights = batch.lightQueue_->vertexLights_.Size();
  1066. unsigned vsi = batch.geometryType_ * MAX_VERTEXLIGHT_VS_VARIATIONS + numVertexLights;
  1067. batch.vertexShader_ = vertexShaders[vsi];
  1068. }
  1069. else
  1070. {
  1071. unsigned vsi = batch.geometryType_;
  1072. batch.vertexShader_ = vertexShaders[vsi];
  1073. }
  1074. batch.pixelShader_ = pixelShaders[heightFog ? 1 : 0];
  1075. }
  1076. }
  1077. // Log error if shaders could not be assigned, but only once per technique
  1078. if (!batch.vertexShader_ || !batch.pixelShader_)
  1079. {
  1080. if (!shaderErrorDisplayed_.Contains(tech))
  1081. {
  1082. shaderErrorDisplayed_.Insert(tech);
  1083. URHO3D_LOGERROR("Technique " + tech->GetName() + " has missing shaders");
  1084. }
  1085. }
  1086. }
  1087. void Renderer::SetLightVolumeBatchShaders(Batch& batch, Camera* camera, const String& vsName, const String& psName, const String& vsDefines,
  1088. const String& psDefines)
  1089. {
  1090. assert(deferredLightPSVariations_.Size());
  1091. unsigned vsi = DLVS_NONE;
  1092. unsigned psi = DLPS_NONE;
  1093. Light* light = batch.lightQueue_->light_;
  1094. switch (light->GetLightType())
  1095. {
  1096. case LIGHT_DIRECTIONAL:
  1097. vsi += DLVS_DIR;
  1098. break;
  1099. case LIGHT_SPOT:
  1100. psi += DLPS_SPOT;
  1101. break;
  1102. case LIGHT_POINT:
  1103. if (light->GetShapeTexture())
  1104. psi += DLPS_POINTMASK;
  1105. else
  1106. psi += DLPS_POINT;
  1107. break;
  1108. }
  1109. if (batch.lightQueue_->shadowMap_)
  1110. psi += DLPS_SHADOW;
  1111. if (specularLighting_ && light->GetSpecularIntensity() > 0.0f)
  1112. psi += DLPS_SPEC;
  1113. if (camera->IsOrthographic())
  1114. {
  1115. vsi += DLVS_ORTHO;
  1116. psi += DLPS_ORTHO;
  1117. }
  1118. if (vsDefines.Length())
  1119. batch.vertexShader_ = graphics_->GetShader(VS, vsName, deferredLightVSVariations[vsi] + vsDefines);
  1120. else
  1121. batch.vertexShader_ = graphics_->GetShader(VS, vsName, deferredLightVSVariations[vsi]);
  1122. if (psDefines.Length())
  1123. batch.pixelShader_ = graphics_->GetShader(PS, psName, deferredLightPSVariations_[psi] + psDefines);
  1124. else
  1125. batch.pixelShader_ = graphics_->GetShader(PS, psName, deferredLightPSVariations_[psi]);
  1126. }
  1127. void Renderer::SetCullMode(CullMode mode, Camera* camera)
  1128. {
  1129. // If a camera is specified, check whether it reverses culling due to vertical flipping or reflection
  1130. if (camera && camera->GetReverseCulling())
  1131. {
  1132. if (mode == CULL_CW)
  1133. mode = CULL_CCW;
  1134. else if (mode == CULL_CCW)
  1135. mode = CULL_CW;
  1136. }
  1137. graphics_->SetCullMode(mode);
  1138. }
  1139. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1140. {
  1141. if (!instancingBuffer_ || !dynamicInstancing_)
  1142. return false;
  1143. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1144. if (numInstances <= oldSize)
  1145. return true;
  1146. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1147. while (newSize < numInstances)
  1148. newSize <<= 1;
  1149. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1150. {
  1151. URHO3D_LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1152. // If failed, try to restore the old size
  1153. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1154. return false;
  1155. }
  1156. URHO3D_LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1157. return true;
  1158. }
  1159. void Renderer::SaveScreenBufferAllocations()
  1160. {
  1161. savedScreenBufferAllocations_ = screenBufferAllocations_;
  1162. }
  1163. void Renderer::RestoreScreenBufferAllocations()
  1164. {
  1165. screenBufferAllocations_ = savedScreenBufferAllocations_;
  1166. }
  1167. void Renderer::OptimizeLightByScissor(Light* light, Camera* camera)
  1168. {
  1169. if (light && light->GetLightType() != LIGHT_DIRECTIONAL)
  1170. graphics_->SetScissorTest(true, GetLightScissor(light, camera));
  1171. else
  1172. graphics_->SetScissorTest(false);
  1173. }
  1174. void Renderer::OptimizeLightByStencil(Light* light, Camera* camera)
  1175. {
  1176. if (light)
  1177. {
  1178. LightType type = light->GetLightType();
  1179. if (type == LIGHT_DIRECTIONAL)
  1180. {
  1181. graphics_->SetStencilTest(false);
  1182. return;
  1183. }
  1184. Geometry* geometry = GetLightGeometry(light);
  1185. const Matrix3x4& view = camera->GetView();
  1186. const Matrix4& projection = camera->GetProjection();
  1187. Vector3 cameraPos = camera->GetNode()->GetWorldPosition();
  1188. float lightDist;
  1189. if (type == LIGHT_POINT)
  1190. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  1191. else
  1192. lightDist = light->GetFrustum().Distance(cameraPos);
  1193. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  1194. if (lightDist < M_EPSILON)
  1195. {
  1196. graphics_->SetStencilTest(false);
  1197. return;
  1198. }
  1199. // If the stencil value has wrapped, clear the whole stencil first
  1200. if (!lightStencilValue_)
  1201. {
  1202. graphics_->Clear(CLEAR_STENCIL);
  1203. lightStencilValue_ = 1;
  1204. }
  1205. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  1206. // to avoid clipping.
  1207. if (lightDist < camera->GetNearClip() * 2.0f)
  1208. {
  1209. SetCullMode(CULL_CW, camera);
  1210. graphics_->SetDepthTest(CMP_GREATER);
  1211. }
  1212. else
  1213. {
  1214. SetCullMode(CULL_CCW, camera);
  1215. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1216. }
  1217. graphics_->SetColorWrite(false);
  1218. graphics_->SetDepthWrite(false);
  1219. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  1220. graphics_->SetShaders(graphics_->GetShader(VS, "Stencil"), graphics_->GetShader(PS, "Stencil"));
  1221. graphics_->SetShaderParameter(VSP_VIEW, view);
  1222. graphics_->SetShaderParameter(VSP_VIEWINV, camera->GetEffectiveWorldTransform());
  1223. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1224. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform(camera));
  1225. geometry->Draw(graphics_);
  1226. graphics_->ClearTransformSources();
  1227. graphics_->SetColorWrite(true);
  1228. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  1229. // Increase stencil value for next light
  1230. ++lightStencilValue_;
  1231. }
  1232. else
  1233. graphics_->SetStencilTest(false);
  1234. }
  1235. const Rect& Renderer::GetLightScissor(Light* light, Camera* camera)
  1236. {
  1237. Pair<Light*, Camera*> combination(light, camera);
  1238. HashMap<Pair<Light*, Camera*>, Rect>::Iterator i = lightScissorCache_.Find(combination);
  1239. if (i != lightScissorCache_.End())
  1240. return i->second_;
  1241. const Matrix3x4& view = camera->GetView();
  1242. const Matrix4& projection = camera->GetProjection();
  1243. assert(light->GetLightType() != LIGHT_DIRECTIONAL);
  1244. if (light->GetLightType() == LIGHT_SPOT)
  1245. {
  1246. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  1247. return lightScissorCache_[combination] = viewFrustum.Projected(projection);
  1248. }
  1249. else // LIGHT_POINT
  1250. {
  1251. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  1252. return lightScissorCache_[combination] = viewBox.Projected(projection);
  1253. }
  1254. }
  1255. void Renderer::PrepareViewRender()
  1256. {
  1257. ResetScreenBufferAllocations();
  1258. lightScissorCache_.Clear();
  1259. lightStencilValue_ = 1;
  1260. }
  1261. void Renderer::RemoveUnusedBuffers()
  1262. {
  1263. for (unsigned i = occlusionBuffers_.Size() - 1; i < occlusionBuffers_.Size(); --i)
  1264. {
  1265. if (occlusionBuffers_[i]->GetUseTimer() > MAX_BUFFER_AGE)
  1266. {
  1267. URHO3D_LOGDEBUG("Removed unused occlusion buffer");
  1268. occlusionBuffers_.Erase(i);
  1269. }
  1270. }
  1271. for (HashMap<long long, Vector<SharedPtr<Texture> > >::Iterator i = screenBuffers_.Begin(); i != screenBuffers_.End();)
  1272. {
  1273. HashMap<long long, Vector<SharedPtr<Texture> > >::Iterator current = i++;
  1274. Vector<SharedPtr<Texture> >& buffers = current->second_;
  1275. for (unsigned j = buffers.Size() - 1; j < buffers.Size(); --j)
  1276. {
  1277. Texture* buffer = buffers[j];
  1278. if (buffer->GetUseTimer() > MAX_BUFFER_AGE)
  1279. {
  1280. URHO3D_LOGDEBUG("Removed unused screen buffer size " + String(buffer->GetWidth()) + "x" + String(buffer->GetHeight()) +
  1281. " format " + String(buffer->GetFormat()));
  1282. buffers.Erase(j);
  1283. }
  1284. }
  1285. if (buffers.Empty())
  1286. {
  1287. screenBufferAllocations_.Erase(current->first_);
  1288. screenBuffers_.Erase(current);
  1289. }
  1290. }
  1291. }
  1292. void Renderer::ResetShadowMapAllocations()
  1293. {
  1294. for (HashMap<int, PODVector<Light*> >::Iterator i = shadowMapAllocations_.Begin(); i != shadowMapAllocations_.End(); ++i)
  1295. i->second_.Clear();
  1296. }
  1297. void Renderer::ResetScreenBufferAllocations()
  1298. {
  1299. for (HashMap<long long, unsigned>::Iterator i = screenBufferAllocations_.Begin(); i != screenBufferAllocations_.End(); ++i)
  1300. i->second_ = 0;
  1301. }
  1302. void Renderer::Initialize()
  1303. {
  1304. Graphics* graphics = GetSubsystem<Graphics>();
  1305. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1306. if (!graphics || !graphics->IsInitialized() || !cache)
  1307. return;
  1308. URHO3D_PROFILE(InitRenderer);
  1309. graphics_ = graphics;
  1310. if (!graphics_->GetShadowMapFormat())
  1311. drawShadows_ = false;
  1312. // Validate the shadow quality level
  1313. SetShadowQuality(shadowQuality_);
  1314. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  1315. defaultLightSpot_ = cache->GetResource<Texture2D>("Textures/Spot.png");
  1316. defaultMaterial_ = new Material(context_);
  1317. defaultRenderPath_ = new RenderPath();
  1318. defaultRenderPath_->Load(cache->GetResource<XMLFile>("RenderPaths/Forward.xml"));
  1319. CreateGeometries();
  1320. CreateInstancingBuffer();
  1321. viewports_.Resize(1);
  1322. ResetShadowMaps();
  1323. ResetBuffers();
  1324. shadersDirty_ = true;
  1325. initialized_ = true;
  1326. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(Renderer, HandleRenderUpdate));
  1327. URHO3D_LOGINFO("Initialized renderer");
  1328. }
  1329. void Renderer::LoadShaders()
  1330. {
  1331. URHO3D_LOGDEBUG("Reloading shaders");
  1332. // Release old material shaders, mark them for reload
  1333. ReleaseMaterialShaders();
  1334. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  1335. // Construct new names for deferred light volume pixel shaders based on rendering options
  1336. deferredLightPSVariations_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  1337. for (unsigned i = 0; i < MAX_DEFERRED_LIGHT_PS_VARIATIONS; ++i)
  1338. {
  1339. deferredLightPSVariations_[i] = lightPSVariations[i % DLPS_ORTHO];
  1340. if (i & DLPS_SHADOW)
  1341. deferredLightPSVariations_[i] += GetShadowVariations();
  1342. if (i & DLPS_ORTHO)
  1343. deferredLightPSVariations_[i] += "ORTHO ";
  1344. }
  1345. shadersDirty_ = false;
  1346. }
  1347. void Renderer::LoadPassShaders(Pass* pass)
  1348. {
  1349. URHO3D_PROFILE(LoadPassShaders);
  1350. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  1351. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  1352. // Forget all the old shaders
  1353. vertexShaders.Clear();
  1354. pixelShaders.Clear();
  1355. String extraShaderDefines = " ";
  1356. if (pass->GetName() == "shadow"
  1357. && (shadowQuality_ == SHADOWQUALITY_VSM || shadowQuality_ == SHADOWQUALITY_BLUR_VSM))
  1358. {
  1359. extraShaderDefines = " VSM_SHADOW ";
  1360. }
  1361. if (pass->GetLightingMode() == LIGHTING_PERPIXEL)
  1362. {
  1363. // Load forward pixel lit variations
  1364. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  1365. pixelShaders.Resize(MAX_LIGHT_PS_VARIATIONS * 2);
  1366. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  1367. {
  1368. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  1369. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  1370. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(),
  1371. pass->GetVertexShaderDefines() + extraShaderDefines + lightVSVariations[l] + geometryVSVariations[g]);
  1372. }
  1373. for (unsigned j = 0; j < MAX_LIGHT_PS_VARIATIONS * 2; ++j)
  1374. {
  1375. unsigned l = j % MAX_LIGHT_PS_VARIATIONS;
  1376. unsigned h = j / MAX_LIGHT_PS_VARIATIONS;
  1377. if (l & LPS_SHADOW)
  1378. {
  1379. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(),
  1380. pass->GetPixelShaderDefines() + extraShaderDefines + lightPSVariations[l] + GetShadowVariations() +
  1381. heightFogVariations[h]);
  1382. }
  1383. else
  1384. pixelShaders[j] = graphics_->GetShader(PS, pass->GetPixelShader(),
  1385. pass->GetPixelShaderDefines() + extraShaderDefines + lightPSVariations[l] + heightFogVariations[h]);
  1386. }
  1387. }
  1388. else
  1389. {
  1390. // Load vertex light variations
  1391. if (pass->GetLightingMode() == LIGHTING_PERVERTEX)
  1392. {
  1393. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS);
  1394. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_VERTEXLIGHT_VS_VARIATIONS; ++j)
  1395. {
  1396. unsigned g = j / MAX_VERTEXLIGHT_VS_VARIATIONS;
  1397. unsigned l = j % MAX_VERTEXLIGHT_VS_VARIATIONS;
  1398. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(),
  1399. pass->GetVertexShaderDefines() + extraShaderDefines + vertexLightVSVariations[l] + geometryVSVariations[g]);
  1400. }
  1401. }
  1402. else
  1403. {
  1404. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  1405. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  1406. {
  1407. vertexShaders[j] = graphics_->GetShader(VS, pass->GetVertexShader(),
  1408. pass->GetVertexShaderDefines() + extraShaderDefines + geometryVSVariations[j]);
  1409. }
  1410. }
  1411. pixelShaders.Resize(2);
  1412. for (unsigned j = 0; j < 2; ++j)
  1413. {
  1414. pixelShaders[j] =
  1415. graphics_->GetShader(PS, pass->GetPixelShader(), pass->GetPixelShaderDefines() + extraShaderDefines + heightFogVariations[j]);
  1416. }
  1417. }
  1418. pass->MarkShadersLoaded(shadersChangedFrameNumber_);
  1419. }
  1420. void Renderer::ReleaseMaterialShaders()
  1421. {
  1422. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1423. PODVector<Material*> materials;
  1424. cache->GetResources<Material>(materials);
  1425. for (unsigned i = 0; i < materials.Size(); ++i)
  1426. materials[i]->ReleaseShaders();
  1427. }
  1428. void Renderer::ReloadTextures()
  1429. {
  1430. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1431. PODVector<Resource*> textures;
  1432. cache->GetResources(textures, Texture2D::GetTypeStatic());
  1433. for (unsigned i = 0; i < textures.Size(); ++i)
  1434. cache->ReloadResource(textures[i]);
  1435. cache->GetResources(textures, TextureCube::GetTypeStatic());
  1436. for (unsigned i = 0; i < textures.Size(); ++i)
  1437. cache->ReloadResource(textures[i]);
  1438. }
  1439. void Renderer::CreateGeometries()
  1440. {
  1441. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  1442. dlvb->SetShadowed(true);
  1443. dlvb->SetSize(4, MASK_POSITION);
  1444. dlvb->SetData(dirLightVertexData);
  1445. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1446. dlib->SetShadowed(true);
  1447. dlib->SetSize(6, false);
  1448. dlib->SetData(dirLightIndexData);
  1449. dirLightGeometry_ = new Geometry(context_);
  1450. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1451. dirLightGeometry_->SetIndexBuffer(dlib);
  1452. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1453. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1454. slvb->SetShadowed(true);
  1455. slvb->SetSize(8, MASK_POSITION);
  1456. slvb->SetData(spotLightVertexData);
  1457. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1458. slib->SetShadowed(true);
  1459. slib->SetSize(36, false);
  1460. slib->SetData(spotLightIndexData);
  1461. spotLightGeometry_ = new Geometry(context_);
  1462. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1463. spotLightGeometry_->SetIndexBuffer(slib);
  1464. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1465. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1466. plvb->SetShadowed(true);
  1467. plvb->SetSize(24, MASK_POSITION);
  1468. plvb->SetData(pointLightVertexData);
  1469. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1470. plib->SetShadowed(true);
  1471. plib->SetSize(132, false);
  1472. plib->SetData(pointLightIndexData);
  1473. pointLightGeometry_ = new Geometry(context_);
  1474. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1475. pointLightGeometry_->SetIndexBuffer(plib);
  1476. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1477. #if !defined(URHO3D_OPENGL) || !defined(GL_ES_VERSION_2_0)
  1478. if (graphics_->GetShadowMapFormat())
  1479. {
  1480. faceSelectCubeMap_ = new TextureCube(context_);
  1481. faceSelectCubeMap_->SetNumLevels(1);
  1482. faceSelectCubeMap_->SetSize(1, graphics_->GetRGBAFormat());
  1483. faceSelectCubeMap_->SetFilterMode(FILTER_NEAREST);
  1484. indirectionCubeMap_ = new TextureCube(context_);
  1485. indirectionCubeMap_->SetNumLevels(1);
  1486. indirectionCubeMap_->SetSize(256, graphics_->GetRGBAFormat());
  1487. indirectionCubeMap_->SetFilterMode(FILTER_BILINEAR);
  1488. indirectionCubeMap_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
  1489. indirectionCubeMap_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
  1490. indirectionCubeMap_->SetAddressMode(COORD_W, ADDRESS_CLAMP);
  1491. SetIndirectionTextureData();
  1492. }
  1493. #endif
  1494. }
  1495. void Renderer::SetIndirectionTextureData()
  1496. {
  1497. unsigned char data[256 * 256 * 4];
  1498. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1499. {
  1500. unsigned axis = i / 2;
  1501. data[0] = (unsigned char)((axis == 0) ? 255 : 0);
  1502. data[1] = (unsigned char)((axis == 1) ? 255 : 0);
  1503. data[2] = (unsigned char)((axis == 2) ? 255 : 0);
  1504. data[3] = 0;
  1505. faceSelectCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 1, 1, data);
  1506. }
  1507. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1508. {
  1509. unsigned char faceX = (unsigned char)((i & 1) * 255);
  1510. unsigned char faceY = (unsigned char)((i / 2) * 255 / 3);
  1511. unsigned char* dest = data;
  1512. for (unsigned y = 0; y < 256; ++y)
  1513. {
  1514. for (unsigned x = 0; x < 256; ++x)
  1515. {
  1516. #ifdef URHO3D_OPENGL
  1517. dest[0] = (unsigned char)x;
  1518. dest[1] = (unsigned char)(255 - y);
  1519. dest[2] = faceX;
  1520. dest[3] = (unsigned char)(255 * 2 / 3 - faceY);
  1521. #else
  1522. dest[0] = (unsigned char)x;
  1523. dest[1] = (unsigned char)y;
  1524. dest[2] = faceX;
  1525. dest[3] = faceY;
  1526. #endif
  1527. dest += 4;
  1528. }
  1529. }
  1530. indirectionCubeMap_->SetData((CubeMapFace)i, 0, 0, 0, 256, 256, data);
  1531. }
  1532. faceSelectCubeMap_->ClearDataLost();
  1533. indirectionCubeMap_->ClearDataLost();
  1534. }
  1535. void Renderer::CreateInstancingBuffer()
  1536. {
  1537. // Do not create buffer if instancing not supported
  1538. if (!graphics_->GetInstancingSupport())
  1539. {
  1540. instancingBuffer_.Reset();
  1541. dynamicInstancing_ = false;
  1542. return;
  1543. }
  1544. instancingBuffer_ = new VertexBuffer(context_);
  1545. if (!instancingBuffer_->SetSize(INSTANCING_BUFFER_DEFAULT_SIZE, INSTANCING_BUFFER_MASK, true))
  1546. {
  1547. instancingBuffer_.Reset();
  1548. dynamicInstancing_ = false;
  1549. }
  1550. }
  1551. void Renderer::ResetShadowMaps()
  1552. {
  1553. shadowMaps_.Clear();
  1554. shadowMapAllocations_.Clear();
  1555. colorShadowMaps_.Clear();
  1556. }
  1557. void Renderer::ResetBuffers()
  1558. {
  1559. occlusionBuffers_.Clear();
  1560. screenBuffers_.Clear();
  1561. screenBufferAllocations_.Clear();
  1562. }
  1563. String Renderer::GetShadowVariations() const
  1564. {
  1565. switch (shadowQuality_)
  1566. {
  1567. case SHADOWQUALITY_SIMPLE_16BIT:
  1568. #ifdef URHO3D_OPENGL
  1569. return "SIMPLE_SHADOW ";
  1570. #else
  1571. if (graphics_->GetHardwareShadowSupport())
  1572. return "SIMPLE_SHADOW ";
  1573. else
  1574. return "SIMPLE_SHADOW SHADOWCMP ";
  1575. #endif
  1576. case SHADOWQUALITY_SIMPLE_24BIT:
  1577. return "SIMPLE_SHADOW ";
  1578. case SHADOWQUALITY_PCF_16BIT:
  1579. #ifdef URHO3D_OPENGL
  1580. return "PCF_SHADOW ";
  1581. #else
  1582. if (graphics_->GetHardwareShadowSupport())
  1583. return "PCF_SHADOW ";
  1584. else
  1585. return "PCF_SHADOW SHADOWCMP ";
  1586. #endif
  1587. case SHADOWQUALITY_PCF_24BIT:
  1588. return "PCF_SHADOW ";
  1589. case SHADOWQUALITY_VSM:
  1590. return "VSM_SHADOW ";
  1591. case SHADOWQUALITY_BLUR_VSM:
  1592. return "VSM_SHADOW ";
  1593. }
  1594. return "";
  1595. };
  1596. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1597. {
  1598. if (!initialized_)
  1599. Initialize();
  1600. else
  1601. resetViews_ = true;
  1602. }
  1603. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1604. {
  1605. using namespace RenderUpdate;
  1606. Update(eventData[P_TIMESTEP].GetFloat());
  1607. }
  1608. void Renderer::BlurShadowMap(View* view, Texture2D* shadowMap)
  1609. {
  1610. graphics_->SetBlendMode(BLEND_REPLACE);
  1611. graphics_->SetDepthTest(CMP_ALWAYS);
  1612. graphics_->SetClipPlane(false);
  1613. graphics_->SetScissorTest(false);
  1614. // Get a temporary render buffer
  1615. Texture2D* tmpBuffer = static_cast<Texture2D*>(GetScreenBuffer(shadowMap->GetWidth(), shadowMap->GetHeight(), shadowMap->GetFormat(), false, false, false));
  1616. graphics_->SetRenderTarget(0, tmpBuffer->GetRenderSurface());
  1617. graphics_->SetDepthStencil(GetDepthStencil(shadowMap->GetWidth(), shadowMap->GetHeight()));
  1618. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  1619. // Get shaders
  1620. static const String shaderName("ShadowBlur");
  1621. ShaderVariation* vs = graphics_->GetShader(VS, shaderName);
  1622. ShaderVariation* ps = graphics_->GetShader(PS, shaderName);
  1623. graphics_->SetShaders(vs, ps);
  1624. view->SetGBufferShaderParameters(IntVector2(shadowMap->GetWidth(), shadowMap->GetHeight()), IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  1625. // Horizontal blur of the shadow map
  1626. static const StringHash blurOffsetParam("BlurOffsets");
  1627. graphics_->SetShaderParameter(blurOffsetParam, Vector2(shadowSoftness_ / shadowMap->GetWidth(), 0.0f));
  1628. graphics_->SetTexture(TU_DIFFUSE, shadowMap);
  1629. view->DrawFullscreenQuad(false);
  1630. // Vertical blur
  1631. graphics_->SetRenderTarget(0, shadowMap);
  1632. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  1633. graphics_->SetShaderParameter(blurOffsetParam, Vector2(0.0f, shadowSoftness_ / shadowMap->GetHeight()));
  1634. graphics_->SetTexture(TU_DIFFUSE, tmpBuffer);
  1635. view->DrawFullscreenQuad(false);
  1636. }
  1637. }