Renderer.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Camera.h"
  25. #include "CoreEvents.h"
  26. #include "DebugRenderer.h"
  27. #include "Geometry.h"
  28. #include "Graphics.h"
  29. #include "GraphicsEvents.h"
  30. #include "GraphicsImpl.h"
  31. #include "IndexBuffer.h"
  32. #include "Light.h"
  33. #include "Log.h"
  34. #include "Material.h"
  35. #include "OcclusionBuffer.h"
  36. #include "Octree.h"
  37. #include "OctreeQuery.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ResourceCache.h"
  41. #include "Scene.h"
  42. #include "Shader.h"
  43. #include "ShaderVariation.h"
  44. #include "Technique.h"
  45. #include "Texture2D.h"
  46. #include "TextureCube.h"
  47. #include "VertexBuffer.h"
  48. #include "View.h"
  49. #include "XMLFile.h"
  50. #include "Zone.h"
  51. #include "DebugNew.h"
  52. static const float dirLightVertexData[] =
  53. {
  54. -1, 1, 0,
  55. 1, 1, 0,
  56. 1, -1, 0,
  57. -1, -1, 0,
  58. };
  59. static const unsigned short dirLightIndexData[] =
  60. {
  61. 0, 1, 2,
  62. 2, 3, 0,
  63. };
  64. static const float pointLightVertexData[] =
  65. {
  66. -0.423169f, -1.000000f, 0.423169f,
  67. -0.423169f, -1.000000f, -0.423169f,
  68. 0.423169f, -1.000000f, -0.423169f,
  69. 0.423169f, -1.000000f, 0.423169f,
  70. 0.423169f, 1.000000f, -0.423169f,
  71. -0.423169f, 1.000000f, -0.423169f,
  72. -0.423169f, 1.000000f, 0.423169f,
  73. 0.423169f, 1.000000f, 0.423169f,
  74. -1.000000f, 0.423169f, -0.423169f,
  75. -1.000000f, -0.423169f, -0.423169f,
  76. -1.000000f, -0.423169f, 0.423169f,
  77. -1.000000f, 0.423169f, 0.423169f,
  78. 0.423169f, 0.423169f, -1.000000f,
  79. 0.423169f, -0.423169f, -1.000000f,
  80. -0.423169f, -0.423169f, -1.000000f,
  81. -0.423169f, 0.423169f, -1.000000f,
  82. 1.000000f, 0.423169f, 0.423169f,
  83. 1.000000f, -0.423169f, 0.423169f,
  84. 1.000000f, -0.423169f, -0.423169f,
  85. 1.000000f, 0.423169f, -0.423169f,
  86. 0.423169f, -0.423169f, 1.000000f,
  87. 0.423169f, 0.423169f, 1.000000f,
  88. -0.423169f, 0.423169f, 1.000000f,
  89. -0.423169f, -0.423169f, 1.000000f
  90. };
  91. static const unsigned short pointLightIndexData[] =
  92. {
  93. 0, 1, 2,
  94. 0, 2, 3,
  95. 4, 5, 6,
  96. 4, 6, 7,
  97. 8, 9, 10,
  98. 8, 10, 11,
  99. 12, 13, 14,
  100. 12, 14, 15,
  101. 16, 17, 18,
  102. 16, 18, 19,
  103. 20, 21, 22,
  104. 20, 22, 23,
  105. 0, 10, 9,
  106. 0, 9, 1,
  107. 13, 2, 1,
  108. 13, 1, 14,
  109. 23, 0, 3,
  110. 23, 3, 20,
  111. 17, 3, 2,
  112. 17, 2, 18,
  113. 21, 7, 6,
  114. 21, 6, 22,
  115. 7, 16, 19,
  116. 7, 19, 4,
  117. 5, 8, 11,
  118. 5, 11, 6,
  119. 4, 12, 15,
  120. 4, 15, 5,
  121. 22, 11, 10,
  122. 22, 10, 23,
  123. 8, 15, 14,
  124. 8, 14, 9,
  125. 12, 19, 18,
  126. 12, 18, 13,
  127. 16, 21, 20,
  128. 16, 20, 17,
  129. 0, 23, 10,
  130. 1, 9, 14,
  131. 2, 13, 18,
  132. 3, 17, 20,
  133. 6, 11, 22,
  134. 5, 15, 8,
  135. 4, 19, 12,
  136. 7, 21, 16
  137. };
  138. static const float spotLightVertexData[] =
  139. {
  140. // Use slightly clamped Z-range so that shadowed point light splits line up nicely
  141. 0.00001f, 0.00001f, 0.00001f,
  142. 0.00001f, -0.00001f, 0.00001f,
  143. -0.00001f, -0.00001f, 0.00001f,
  144. -0.00001f, 0.00001f, 0.00001f,
  145. 1.00000f, 1.00000f, 0.99999f,
  146. 1.00000f, -1.00000f, 0.99999f,
  147. -1.00000f, -1.00000f, 0.99999f,
  148. -1.00000f, 1.00000f, 0.99999f,
  149. };
  150. static const unsigned short spotLightIndexData[] =
  151. {
  152. 3, 0, 1,
  153. 3, 1, 2,
  154. 0, 4, 5,
  155. 0, 5, 1,
  156. 3, 7, 4,
  157. 3, 4, 0,
  158. 7, 3, 2,
  159. 7, 2, 6,
  160. 6, 2, 1,
  161. 6, 1, 5,
  162. 7, 5, 4,
  163. 7, 6, 5
  164. };
  165. static const String hwVariations[] =
  166. {
  167. "",
  168. "HW"
  169. };
  170. static const String geometryVSVariations[] =
  171. {
  172. "",
  173. "Skinned",
  174. "Instanced",
  175. "Billboard"
  176. };
  177. static const String lightVSVariations[] =
  178. {
  179. "",
  180. "Spot",
  181. "Shadow",
  182. "SpotShadow"
  183. };
  184. static const String deferredLightVSVariations[] =
  185. {
  186. "",
  187. "Dir",
  188. "Ortho",
  189. "OrthoDir"
  190. };
  191. static const String lightPSVariations[] =
  192. {
  193. "Dir",
  194. "DirSpec",
  195. "DirShadow",
  196. "DirShadowSpec",
  197. "Spot",
  198. "SpotSpec",
  199. "SpotShadow",
  200. "SpotShadowSpec",
  201. "Point",
  202. "PointSpec",
  203. "PointShadow",
  204. "PointShadowSpec",
  205. "PointMask",
  206. "PointMaskSpec",
  207. "PointMaskShadow",
  208. "PointMaskShadowSpec",
  209. "OrthoDir",
  210. "OrthoDirSpec",
  211. "OrthoDirShadow",
  212. "OrthoDirShadowSpec",
  213. "OrthoSpot",
  214. "OrthoSpotSpec",
  215. "OrthoSpotShadow",
  216. "OrthoSpotShadowSpec",
  217. "OrthoPoint",
  218. "OrthoPointSpec",
  219. "OrthoPointShadow",
  220. "OrthoPointShadowSpec",
  221. "OrthoPointMask",
  222. "OrthoPointMaskSpec",
  223. "OrthoPointMaskShadow",
  224. "OrthoPointMaskShadowSpec"
  225. };
  226. static const unsigned INSTANCING_BUFFER_MASK = MASK_INSTANCEMATRIX1 | MASK_INSTANCEMATRIX2 | MASK_INSTANCEMATRIX3;
  227. static const Viewport noViewport;
  228. OBJECTTYPESTATIC(Renderer);
  229. Renderer::Renderer(Context* context) :
  230. Object(context),
  231. defaultZone_(new Zone(context)),
  232. numViews_(0),
  233. numShadowCameras_(0),
  234. numSplitLights_(0),
  235. numTempNodes_(0),
  236. specularLighting_(true),
  237. drawShadows_(true),
  238. textureAnisotropy_(4),
  239. textureFilterMode_(FILTER_TRILINEAR),
  240. textureQuality_(QUALITY_HIGH),
  241. materialQuality_(QUALITY_HIGH),
  242. shadowMapSize_(1024),
  243. shadowMapHiresDepth_(false),
  244. reuseShadowMaps_(true),
  245. dynamicInstancing_(true),
  246. maxOccluderTriangles_(5000),
  247. occlusionBufferSize_(256),
  248. occluderSizeThreshold_(0.1f),
  249. shadersChangedFrameNumber_(M_MAX_UNSIGNED),
  250. shadersDirty_(true),
  251. initialized_(false)
  252. {
  253. SubscribeToEvent(E_SCREENMODE, HANDLER(Renderer, HandleScreenMode));
  254. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Renderer, HandleRenderUpdate));
  255. // Default to one of each shadow map resolution
  256. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  257. shadowMaps_[i].Resize(1);
  258. // Try to initialize right now, but skip if screen mode is not yet set
  259. Initialize();
  260. }
  261. Renderer::~Renderer()
  262. {
  263. }
  264. void Renderer::SetNumViewports(unsigned num)
  265. {
  266. viewports_.Resize(num);
  267. }
  268. void Renderer::SetViewport(unsigned index, const Viewport& viewport)
  269. {
  270. if (index >= viewports_.Size())
  271. {
  272. LOGERROR("Viewport index out of bounds");
  273. return;
  274. }
  275. viewports_[index] = viewport;
  276. }
  277. void Renderer::SetSpecularLighting(bool enable)
  278. {
  279. specularLighting_ = enable;
  280. }
  281. void Renderer::SetDrawShadows(bool enable)
  282. {
  283. if (!graphics_)
  284. return;
  285. drawShadows_ = enable;
  286. if (!CreateShadowMaps())
  287. drawShadows_ = false;
  288. }
  289. void Renderer::SetTextureAnisotropy(int level)
  290. {
  291. textureAnisotropy_ = Max(level, 1);
  292. }
  293. void Renderer::SetTextureFilterMode(TextureFilterMode mode)
  294. {
  295. textureFilterMode_ = mode;
  296. }
  297. void Renderer::SetTextureQuality(int quality)
  298. {
  299. quality = Clamp(quality, QUALITY_LOW, QUALITY_HIGH);
  300. if (quality != textureQuality_)
  301. {
  302. textureQuality_ = quality;
  303. ReloadTextures();
  304. }
  305. }
  306. void Renderer::SetMaterialQuality(int quality)
  307. {
  308. materialQuality_ = Clamp(quality, QUALITY_LOW, QUALITY_MAX);
  309. shadersDirty_ = true;
  310. ResetViews();
  311. }
  312. void Renderer::SetShadowMapSize(int size)
  313. {
  314. if (!graphics_)
  315. return;
  316. shadowMapSize_ = Max(size, SHADOW_MIN_PIXELS);
  317. if (!CreateShadowMaps())
  318. {
  319. shadowMapSize_ = 1024;
  320. if (!CreateShadowMaps())
  321. drawShadows_ = false;
  322. }
  323. }
  324. void Renderer::SetShadowMapHiresDepth(bool enable)
  325. {
  326. if (!graphics_)
  327. return;
  328. if (!graphics_->GetHiresShadowSupport())
  329. enable = false;
  330. shadowMapHiresDepth_ = enable;
  331. if (!CreateShadowMaps())
  332. drawShadows_ = false;
  333. }
  334. void Renderer::SetReuseShadowMaps(bool enable)
  335. {
  336. if (enable == reuseShadowMaps_)
  337. return;
  338. reuseShadowMaps_ = enable;
  339. if (reuseShadowMaps_)
  340. {
  341. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  342. shadowMaps_[i].Resize(1);
  343. }
  344. if (!CreateShadowMaps())
  345. drawShadows_ = false;
  346. shadersDirty_ = true;
  347. }
  348. void Renderer::SetNumShadowMaps(unsigned full, unsigned half, unsigned quarter)
  349. {
  350. shadowMaps_[0].Resize(full ? full : 1);
  351. shadowMaps_[1].Resize(half ? half : 1);
  352. shadowMaps_[2].Resize(quarter ? quarter : 1);
  353. if (!CreateShadowMaps())
  354. drawShadows_ = false;
  355. }
  356. void Renderer::SetDynamicInstancing(bool enable)
  357. {
  358. if (!instancingBuffer_)
  359. enable = false;
  360. dynamicInstancing_ = enable;
  361. }
  362. void Renderer::SetMaxOccluderTriangles(int triangles)
  363. {
  364. maxOccluderTriangles_ = Max(triangles, 0);
  365. }
  366. void Renderer::SetOcclusionBufferSize(int size)
  367. {
  368. occlusionBufferSize_ = Max(size, 1);
  369. occlusionBuffers_.Clear();
  370. }
  371. void Renderer::SetOccluderSizeThreshold(float screenSize)
  372. {
  373. occluderSizeThreshold_ = Max(screenSize, 0.0f);
  374. }
  375. const Viewport& Renderer::GetViewport(unsigned index) const
  376. {
  377. return index < viewports_.Size() ? viewports_[index] : noViewport;
  378. }
  379. ShaderVariation* Renderer::GetVertexShader(const String& name, bool checkExists) const
  380. {
  381. return GetShader(name, vsFormat_, checkExists);
  382. }
  383. ShaderVariation* Renderer::GetPixelShader(const String& name, bool checkExists) const
  384. {
  385. return GetShader(name, psFormat_, checkExists);
  386. }
  387. unsigned Renderer::GetNumGeometries(bool allViews) const
  388. {
  389. unsigned numGeometries = 0;
  390. unsigned lastView = allViews ? numViews_ : 1;
  391. for (unsigned i = 0; i < lastView; ++i)
  392. numGeometries += views_[i]->GetGeometries().Size();
  393. return numGeometries;
  394. }
  395. unsigned Renderer::GetNumLights(bool allViews) const
  396. {
  397. unsigned nulights_ = 0;
  398. unsigned lastView = allViews ? numViews_ : 1;
  399. for (unsigned i = 0; i < lastView; ++i)
  400. nulights_ += views_[i]->GetLights().Size();
  401. return nulights_;
  402. }
  403. unsigned Renderer::GetNumShadowMaps(bool allViews) const
  404. {
  405. unsigned numShadowMaps = 0;
  406. unsigned lastView = allViews ? numViews_ : 1;
  407. for (unsigned i = 0; i < lastView; ++i)
  408. {
  409. const Vector<LightBatchQueue>& lightQueues = views_[i]->GetLightQueues();
  410. for (unsigned j = 0; j < lightQueues.Size(); ++j)
  411. {
  412. Light* light = lightQueues[j].light_;
  413. if ((light) && (light->GetShadowMap()))
  414. ++numShadowMaps;
  415. }
  416. }
  417. return numShadowMaps;
  418. }
  419. unsigned Renderer::GetNumOccluders(bool allViews) const
  420. {
  421. unsigned numOccluders = 0;
  422. unsigned lastView = allViews ? numViews_ : 1;
  423. for (unsigned i = 0; i < lastView; ++i)
  424. numOccluders += views_[i]->GetOccluders().Size();
  425. return numOccluders;
  426. }
  427. unsigned Renderer::GetNumShadowOccluders(bool allViews) const
  428. {
  429. unsigned numShadowOccluders = 0;
  430. unsigned lastView = allViews ? numViews_ : 1;
  431. for (unsigned i = 0; i < lastView; ++i)
  432. numShadowOccluders += views_[i]->GetShadowOccluders().Size();
  433. return numShadowOccluders;
  434. }
  435. const OcclusionBuffer* Renderer::GetOcclusionBuffer(float aspectRatio, bool halfResolution)
  436. {
  437. // Return an occlusion buffer for debug output purposes. Do not allocate new
  438. int width = occlusionBufferSize_;
  439. int height = (int)(occlusionBufferSize_ / aspectRatio);
  440. if (halfResolution)
  441. {
  442. width >>= 1;
  443. height >>= 1;
  444. }
  445. int searchKey = (width << 16) | height;
  446. Map<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  447. if (i != occlusionBuffers_.End())
  448. return i->second_;
  449. else
  450. return 0;
  451. }
  452. void Renderer::Update(float timeStep)
  453. {
  454. PROFILE(UpdateViewports);
  455. numViews_ = 0;
  456. // If device lost, do not perform update. This is because any dynamic vertex/index buffer updates happen already here,
  457. // and if the device is lost, the updates queue up, causing memory use to rise constantly
  458. if ((!graphics_) || (!graphics_->IsInitialized()) || (graphics_->IsDeviceLost()))
  459. return;
  460. // Advance frame number & time, set up the frameinfo structure, and reset views & stats
  461. frame_.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  462. frame_.timeStep_ = timeStep;
  463. frame_.camera_ = 0;
  464. numShadowCameras_ = 0;
  465. numSplitLights_ = 0;
  466. numTempNodes_ = 0;
  467. updateOctrees_.Clear();
  468. // Reload shaders if needed
  469. if (shadersDirty_)
  470. LoadShaders();
  471. // Process all viewports. Use reverse order, because during rendering the order will be reversed again to handle auxiliary
  472. // view dependencies correctly
  473. for (unsigned i = viewports_.Size() - 1; i < viewports_.Size(); --i)
  474. {
  475. unsigned mainView = numViews_;
  476. Viewport& viewport = viewports_[i];
  477. if (!AddView(0, viewport))
  478. continue;
  479. // Update octree (perform early update for nodes which need that, and reinsert moved nodes.)
  480. // However, if the same scene is viewed from multiple cameras, update the octree only once
  481. Octree* octree = viewport.scene_->GetComponent<Octree>();
  482. DebugRenderer* debug = viewport.scene_->GetComponent<DebugRenderer>();
  483. if (updateOctrees_.Find(octree) == updateOctrees_.End())
  484. {
  485. frame_.camera_ = viewport.camera_;
  486. frame_.viewSize_ = IntVector2(viewport.rect_.right_ - viewport.rect_.left_, viewport.rect_.bottom_ - viewport.rect_.top_);
  487. if (frame_.viewSize_ == IntVector2::ZERO)
  488. frame_.viewSize_ = IntVector2(graphics_->GetWidth(), graphics_->GetHeight());
  489. octree->Update(frame_);
  490. updateOctrees_.Insert(octree);
  491. // Set also the view for the debug graphics already here, so that it can use culling
  492. /// \todo May result in incorrect debug geometry culling if the same scene is drawn from multiple viewports
  493. if (debug)
  494. debug->SetView(viewport.camera_);
  495. }
  496. // Update the viewport's main view and any auxiliary views it Creates
  497. for (unsigned i = mainView; i < numViews_; ++i)
  498. views_[i]->Update(frame_);
  499. }
  500. return;
  501. }
  502. void Renderer::Render()
  503. {
  504. if (!graphics_)
  505. return;
  506. PROFILE(RenderViewports);
  507. graphics_->SetDefaultTextureFilterMode(textureFilterMode_);
  508. graphics_->SetTextureAnisotropy(textureAnisotropy_);
  509. // If no views, just clear the screen
  510. if (!numViews_)
  511. {
  512. numPrimitives_ = 0;
  513. numBatches_ = 0;
  514. graphics_->SetAlphaTest(false);
  515. graphics_->SetBlendMode(BLEND_REPLACE);
  516. graphics_->SetColorWrite(true);
  517. graphics_->SetDepthWrite(true);
  518. graphics_->SetFillMode(FILL_SOLID);
  519. graphics_->SetScissorTest(false);
  520. graphics_->SetStencilTest(false);
  521. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL);
  522. return;
  523. }
  524. // Render views from last to first (each main view is rendered after the auxiliary views it depends on)
  525. for (unsigned i = numViews_ - 1; i < numViews_; --i)
  526. views_[i]->Render();
  527. // Disable scissor/stencil tests if left on by lights, and reset stream frequencies
  528. graphics_->SetScissorTest(false);
  529. graphics_->SetStencilTest(false);
  530. graphics_->ResetStreamFrequencies();
  531. // Copy the number of batches & primitives from Graphics so that we can account for 3D geometry only
  532. numPrimitives_ = graphics_->GetNumPrimitives();
  533. numBatches_ = graphics_->GetNumBatches();
  534. }
  535. void Renderer::DrawDebugGeometry(bool depthTest)
  536. {
  537. PROFILE(RendererDrawDebug);
  538. /// \todo Because debug geometry is per-scene, if two cameras show views of the same area, occlusion is not shown correctly
  539. HashSet<Drawable*> processedGeometries;
  540. HashSet<Light*> processedLights;
  541. for (unsigned i = 0; i < numViews_; ++i)
  542. {
  543. // Make sure it's a main view, and process each node only once
  544. View* view = views_[i];
  545. if (view->GetRenderTarget())
  546. continue;
  547. Octree* octree = view->GetOctree();
  548. if (!octree)
  549. continue;
  550. Scene* scene = static_cast<Scene*>(octree->GetNode());
  551. if (!scene)
  552. continue;
  553. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  554. if (!debug)
  555. continue;
  556. const PODVector<Drawable*>& geometries = view->GetGeometries();
  557. const PODVector<Light*>& lights = view->GetLights();
  558. for (unsigned i = 0; i < geometries.Size(); ++i)
  559. {
  560. if (processedGeometries.Find(geometries[i]) == processedGeometries.End())
  561. {
  562. geometries[i]->DrawDebugGeometry(debug, depthTest);
  563. processedGeometries.Insert(geometries[i]);
  564. }
  565. }
  566. for (unsigned i = 0; i < lights.Size(); ++i)
  567. {
  568. if (processedLights.Find(lights[i]) == processedLights.End())
  569. {
  570. lights[i]->DrawDebugGeometry(debug, depthTest);
  571. processedLights.Insert(lights[i]);
  572. }
  573. }
  574. }
  575. }
  576. void Renderer::Initialize()
  577. {
  578. Graphics* graphics = GetSubsystem<Graphics>();
  579. ResourceCache* cache = GetSubsystem<ResourceCache>();
  580. if ((!graphics) || (!graphics->IsInitialized()) || (!cache))
  581. return;
  582. PROFILE(InitRenderer);
  583. graphics_ = graphics;
  584. cache_ = cache;
  585. // Check shader model support
  586. #ifndef USE_OPENGL
  587. if (graphics_->GetSM3Support())
  588. {
  589. shaderPath_ = "Shaders/SM3/";
  590. vsFormat_ = ".vs3";
  591. psFormat_ = ".ps3";
  592. }
  593. else
  594. {
  595. shaderPath_ = "Shaders/SM2/";
  596. vsFormat_ = ".vs2";
  597. psFormat_ = ".ps2";
  598. }
  599. #else
  600. {
  601. shaderPath_ = "Shaders/GLSL/";
  602. vsFormat_ = ".vert";
  603. psFormat_ = ".frag";
  604. }
  605. #endif
  606. defaultLightRamp_ = cache->GetResource<Texture2D>("Textures/Ramp.png");
  607. defaultLightSpot = cache->GetResource<Texture2D>("Textures/Spot.png");
  608. defaultMaterial_ = cache->GetResource<Material>("Materials/Default.xml");
  609. CreateGeometries();
  610. CreateInstancingBuffer();
  611. if (!CreateShadowMaps())
  612. drawShadows_ = false;
  613. viewports_.Resize(1);
  614. ResetViews();
  615. LOGINFO("Initialized renderer");
  616. initialized_ = true;
  617. }
  618. void Renderer::ResetViews()
  619. {
  620. views_.Clear();
  621. numViews_ = 0;
  622. }
  623. bool Renderer::AddView(RenderSurface* renderTarget, const Viewport& viewport)
  624. {
  625. // If using a render target texture, make sure it will not be rendered to multiple times
  626. if (renderTarget)
  627. {
  628. for (unsigned i = 0; i < numViews_; ++i)
  629. {
  630. if (views_[i]->GetRenderTarget() == renderTarget)
  631. return false;
  632. }
  633. }
  634. if (views_.Size() <= numViews_)
  635. views_.Resize(numViews_ + 1);
  636. if (!views_[numViews_])
  637. views_[numViews_] = new View(context_);
  638. if (views_[numViews_]->Define(renderTarget, viewport))
  639. {
  640. ++numViews_;
  641. return true;
  642. }
  643. else
  644. return false;
  645. }
  646. OcclusionBuffer* Renderer::GetOrCreateOcclusionBuffer(Camera* camera, int maxOccluderTriangles, bool halfResolution)
  647. {
  648. // Get an occlusion buffer matching the aspect ratio. If not found, allocate new
  649. int width = occlusionBufferSize_;
  650. int height = (int)(occlusionBufferSize_ / camera->GetAspectRatio());
  651. if (halfResolution)
  652. {
  653. width >>= 1;
  654. height >>= 1;
  655. }
  656. int searchKey = (width << 16) | height;
  657. SharedPtr<OcclusionBuffer> buffer;
  658. Map<int, SharedPtr<OcclusionBuffer> >::Iterator i = occlusionBuffers_.Find(searchKey);
  659. if (i != occlusionBuffers_.End())
  660. buffer = i->second_;
  661. else
  662. {
  663. buffer = new OcclusionBuffer(context_);
  664. buffer->SetSize(width, height);
  665. occlusionBuffers_[searchKey] = buffer;
  666. }
  667. buffer->SetView(camera);
  668. buffer->SetMaxTriangles(maxOccluderTriangles);
  669. buffer->Clear();
  670. return buffer;
  671. }
  672. Geometry* Renderer::GetLightGeometry(Light* light)
  673. {
  674. switch (light->GetLightType())
  675. {
  676. case LIGHT_POINT:
  677. return pointLightGeometry_;
  678. case LIGHT_SPOT:
  679. case LIGHT_SPLITPOINT:
  680. return spotLightGeometry_;
  681. default:
  682. return dirLightGeometry_;
  683. }
  684. }
  685. Texture2D* Renderer::GetShadowMap(float resolution)
  686. {
  687. unsigned index = 0;
  688. if (resolution < 0.75f)
  689. index = (resolution >= 0.375f) ? 1 : 2;
  690. if (reuseShadowMaps_)
  691. return shadowMaps_[index][0];
  692. else
  693. {
  694. // If higher resolution shadow maps already used up, fall back to lower resolutions
  695. while (index < NUM_SHADOWMAP_RESOLUTIONS)
  696. {
  697. if (shadowMapUseCount_[index] < shadowMaps_[index].Size())
  698. return shadowMaps_[index][shadowMapUseCount_[index]++];
  699. ++index;
  700. }
  701. return 0;
  702. }
  703. }
  704. void Renderer::ResetShadowMapUseCount()
  705. {
  706. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  707. shadowMapUseCount_[i] = 0;
  708. }
  709. ShaderVariation* Renderer::GetShader(const String& name, const String& extension, bool checkExists) const
  710. {
  711. String shaderName = shaderPath_;
  712. String variationName;
  713. unsigned split = name.Find('_');
  714. if (split != String::NPOS)
  715. {
  716. shaderName += name.Substring(0, split) + extension;
  717. variationName = name.Substring(split + 1);
  718. }
  719. else
  720. shaderName += name + extension;
  721. if (checkExists)
  722. {
  723. if (!cache_->Exists(shaderName))
  724. return 0;
  725. }
  726. Shader* shader = cache_->GetResource<Shader>(shaderName);
  727. if (shader)
  728. return shader->GetVariation(variationName);
  729. else
  730. return 0;
  731. }
  732. void Renderer::SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows)
  733. {
  734. batch.pass_ = pass;
  735. // Check if shaders are unloaded or need reloading
  736. Vector<SharedPtr<ShaderVariation> >& vertexShaders = pass->GetVertexShaders();
  737. Vector<SharedPtr<ShaderVariation> >& pixelShaders = pass->GetPixelShaders();
  738. if ((!vertexShaders.Size()) || (!pixelShaders.Size()) || (technique->GetShadersLoadedFrameNumber() !=
  739. shadersChangedFrameNumber_))
  740. {
  741. // First release all previous shaders, then load
  742. technique->ReleaseShaders();
  743. LoadMaterialShaders(technique);
  744. }
  745. // Make sure shaders are loaded now
  746. if ((vertexShaders.Size()) && (pixelShaders.Size()))
  747. {
  748. // Check whether is a forward lit pass. If not, there is only one pixel shader
  749. PassType type = pass->GetType();
  750. if ((type != PASS_LITBASE) && (type != PASS_LIGHT))
  751. {
  752. unsigned vsi = batch.geometryType_;
  753. batch.vertexShader_ = vertexShaders[vsi];
  754. batch.pixelShader_ = pixelShaders[0];
  755. batch.vertexShaderIndex_ = vsi;
  756. }
  757. else
  758. {
  759. Light* light = batch.light_;
  760. if (!light)
  761. {
  762. // Do not log error, as it would result in a lot of spam
  763. batch.vertexShader_ = 0;
  764. batch.pixelShader_ = 0;
  765. return;
  766. }
  767. unsigned vsi = 0;
  768. unsigned psi = 0;
  769. vsi = batch.geometryType_ * MAX_LIGHT_VS_VARIATIONS;
  770. if ((specularLighting_) && (light->GetSpecularIntensity() > 0.0f))
  771. psi += LPS_SPEC;
  772. if ((allowShadows) && (light->GetShadowMap()))
  773. {
  774. vsi += LVS_SHADOW;
  775. psi += LPS_SHADOW;
  776. }
  777. switch (light->GetLightType())
  778. {
  779. case LIGHT_POINT:
  780. case LIGHT_SPLITPOINT:
  781. if (light->GetShapeTexture())
  782. psi += LPS_POINTMASK;
  783. else
  784. psi += LPS_POINT;
  785. break;
  786. case LIGHT_SPOT:
  787. psi += LPS_SPOT;
  788. vsi += LVS_SPOT;
  789. break;
  790. }
  791. batch.vertexShader_ = vertexShaders[vsi];
  792. batch.pixelShader_ = pixelShaders[psi];
  793. batch.vertexShaderIndex_ = vsi;
  794. }
  795. }
  796. batch.CalculateSortKey();
  797. // Log error if shaders could not be assigned, but only once per technique
  798. if ((!batch.vertexShader_) || (!batch.pixelShader_))
  799. {
  800. if (shaderErrorDisplayed_.Find(technique) == shaderErrorDisplayed_.End())
  801. {
  802. shaderErrorDisplayed_.Insert(technique);
  803. LOGERROR("Technique " + technique->GetName() + " has missing shaders");
  804. }
  805. }
  806. }
  807. void Renderer::SetLightVolumeShaders(Batch& batch)
  808. {
  809. unsigned vsi = DLVS_NONE;
  810. unsigned psi = DLPS_NONE;
  811. Light* light = batch.light_;
  812. switch(light->GetLightType())
  813. {
  814. case LIGHT_DIRECTIONAL:
  815. vsi += DLVS_DIR;
  816. break;
  817. case LIGHT_POINT:
  818. case LIGHT_SPLITPOINT:
  819. if (light->GetShapeTexture())
  820. psi += DLPS_POINTMASK;
  821. else
  822. psi += DLPS_POINT;
  823. break;
  824. case LIGHT_SPOT:
  825. psi += DLPS_SPOT;
  826. break;
  827. }
  828. if (light->GetShadowMap())
  829. psi += DLPS_SHADOW;
  830. if ((specularLighting_) && (light->GetSpecularIntensity() > 0.0))
  831. psi += DLPS_SPEC;
  832. if (batch.camera_->IsOrthographic())
  833. {
  834. vsi += DLVS_ORTHO;
  835. psi += DLPS_ORTHO;
  836. }
  837. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  838. if (!lightVS_[vsi])
  839. lightVS_[vsi] = GetVertexShader(lightShaderName_ + deferredLightVSVariations[vsi]);
  840. if (!lightPS_[psi])
  841. {
  842. unsigned variation = psi % DLPS_SPOT;
  843. if ((variation == DLPS_SHADOW) || (variation == DLPS_SHADOWSPEC))
  844. lightPS_[psi] = GetPixelShader(lightShaderName_ + lightPSVariations[psi] + hwVariations[hwShadows]);
  845. else
  846. lightPS_[psi] = GetPixelShader(lightShaderName_ + lightPSVariations[psi]);
  847. }
  848. batch.material_ = 0;
  849. batch.pass_ = 0;
  850. batch.vertexShader_ = lightVS_[vsi];
  851. batch.pixelShader_ = lightPS_[psi];
  852. batch.vertexShaderIndex_ = vsi;
  853. batch.CalculateSortKey();
  854. }
  855. void Renderer::LoadShaders()
  856. {
  857. LOGINFO("Reloading shaders");
  858. // Release old material shaders, mark them for reload
  859. ReleaseMaterialShaders();
  860. shadersChangedFrameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  861. // Load inbuilt shaders
  862. stencilVS_ = GetVertexShader("Stencil");
  863. stencilPS_ = GetPixelShader("Stencil");
  864. lightVS_.Clear();
  865. lightPS_.Clear();
  866. RenderMode mode = graphics_->GetRenderMode();
  867. if (mode != RENDER_FORWARD)
  868. {
  869. // There are rather many light volume shader variations, so load them later on-demand
  870. lightVS_.Resize(MAX_DEFERRED_LIGHT_VS_VARIATIONS);
  871. lightPS_.Resize(MAX_DEFERRED_LIGHT_PS_VARIATIONS);
  872. if (mode == RENDER_DEFERRED)
  873. lightShaderName_ = "Deferred/Light_";
  874. else
  875. lightShaderName_ = "Prepass/Light_";
  876. }
  877. // Remove shaders that are no longer referenced from the cache
  878. cache_->ReleaseResources(Shader::GetTypeStatic());
  879. shadersDirty_ = false;
  880. }
  881. void Renderer::LoadMaterialShaders(Technique* technique)
  882. {
  883. LoadPassShaders(technique, PASS_SHADOW);
  884. LoadPassShaders(technique, PASS_EXTRA);
  885. RenderMode mode = graphics_->GetRenderMode();
  886. if (mode == RENDER_FORWARD)
  887. {
  888. LoadPassShaders(technique, PASS_BASE);
  889. LoadPassShaders(technique, PASS_LITBASE);
  890. LoadPassShaders(technique, PASS_LIGHT);
  891. }
  892. else
  893. {
  894. // G-Buffer pass types depend on whether deferred shading or light prepass is in use
  895. if (mode == RENDER_DEFERRED)
  896. LoadPassShaders(technique, PASS_DEFERRED);
  897. else if (mode == RENDER_PREPASS)
  898. {
  899. LoadPassShaders(technique, PASS_PREPASS);
  900. LoadPassShaders(technique, PASS_MATERIAL);
  901. }
  902. else
  903. {
  904. LoadPassShaders(technique, PASS_BASE);
  905. // If shadow maps are not reused, transparencies can be rendered shadowed
  906. LoadPassShaders(technique, PASS_LITBASE, !reuseShadowMaps_);
  907. LoadPassShaders(technique, PASS_LIGHT, !reuseShadowMaps_);
  908. }
  909. }
  910. }
  911. void Renderer::LoadPassShaders(Technique* technique, PassType pass, bool allowShadows)
  912. {
  913. Map<PassType, Pass>::Iterator i = technique->passes_.Find(pass);
  914. if (i == technique->passes_.End())
  915. return;
  916. String vertexShaderName = i->second_.GetVertexShaderName();
  917. String pixelShaderName = i->second_.GetPixelShaderName();
  918. // Check if the shader name is already a variation in itself
  919. if (vertexShaderName.Find('_') == String::NPOS)
  920. vertexShaderName += "_";
  921. if (pixelShaderName.Find('_') == String::NPOS)
  922. pixelShaderName += "_";
  923. // If ambient pass is not using REPLACE as the blend mode, and shadow maps are reused, do not load shadow variations
  924. if ((reuseShadowMaps_) && ((pass == PASS_LIGHT) || (pass == PASS_LITBASE)))
  925. {
  926. if ((!technique->HasPass(PASS_BASE)) || (technique->GetPass(PASS_BASE)->GetBlendMode() != BLEND_REPLACE))
  927. allowShadows = false;
  928. }
  929. unsigned hwShadows = graphics_->GetHardwareShadowSupport() ? 1 : 0;
  930. Vector<SharedPtr<ShaderVariation> >& vertexShaders = i->second_.GetVertexShaders();
  931. Vector<SharedPtr<ShaderVariation> >& pixelShaders = i->second_.GetPixelShaders();
  932. // Forget all the old shaders
  933. vertexShaders.Clear();
  934. pixelShaders.Clear();
  935. switch (i->first_)
  936. {
  937. default:
  938. vertexShaders.Resize(MAX_GEOMETRYTYPES);
  939. pixelShaders.Resize(1);
  940. for (unsigned j = 0; j < MAX_GEOMETRYTYPES; ++j)
  941. vertexShaders[j] = GetVertexShader(vertexShaderName + geometryVSVariations[j], j != 0);
  942. pixelShaders[0] = GetPixelShader(pixelShaderName);
  943. break;
  944. case PASS_LITBASE:
  945. case PASS_LIGHT:
  946. {
  947. // In first light pass, load only directional light shaders
  948. unsigned numPS = i->first_ == PASS_LIGHT ? MAX_LIGHT_PS_VARIATIONS : LPS_SPOT;
  949. vertexShaders.Resize(MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS);
  950. pixelShaders.Resize(numPS);
  951. for (unsigned j = 0; j < MAX_GEOMETRYTYPES * MAX_LIGHT_VS_VARIATIONS; ++j)
  952. {
  953. unsigned g = j / MAX_LIGHT_VS_VARIATIONS;
  954. unsigned l = j % MAX_LIGHT_VS_VARIATIONS;
  955. if ((!(l & LVS_SHADOW)) || (allowShadows))
  956. vertexShaders[j] = GetVertexShader(vertexShaderName + lightVSVariations[l] + geometryVSVariations[g], g != 0);
  957. else
  958. vertexShaders[j].Reset();
  959. }
  960. for (unsigned j = 0; j < numPS; ++j)
  961. {
  962. unsigned variation = j % LPS_SPOT;
  963. if ((variation == LPS_SHADOW) || (variation == LPS_SHADOWSPEC))
  964. {
  965. if (allowShadows)
  966. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j] +
  967. hwVariations[hwShadows]);
  968. else
  969. pixelShaders[j].Reset();
  970. }
  971. else
  972. pixelShaders[j] = GetPixelShader(pixelShaderName + lightPSVariations[j]);
  973. }
  974. break;
  975. }
  976. }
  977. technique->MarkShadersLoaded(shadersChangedFrameNumber_);
  978. }
  979. void Renderer::ReleaseMaterialShaders()
  980. {
  981. PODVector<Material*> materials;
  982. cache_->GetResources<Material>(materials);
  983. for (unsigned i = 0; i < materials.Size(); ++i)
  984. materials[i]->ReleaseShaders();
  985. }
  986. void Renderer::ReloadTextures()
  987. {
  988. PODVector<Resource*> textures;
  989. cache_->GetResources(textures, Texture2D::GetTypeStatic());
  990. for (unsigned i = 0; i < textures.Size(); ++i)
  991. cache_->ReloadResource(textures[i]);
  992. cache_->GetResources(textures, TextureCube::GetTypeStatic());
  993. for (unsigned i = 0; i < textures.Size(); ++i)
  994. cache_->ReloadResource(textures[i]);
  995. }
  996. void Renderer::CreateGeometries()
  997. {
  998. SharedPtr<VertexBuffer> dlvb(new VertexBuffer(context_));
  999. dlvb->SetSize(4, MASK_POSITION);
  1000. dlvb->SetData(dirLightVertexData);
  1001. SharedPtr<IndexBuffer> dlib(new IndexBuffer(context_));
  1002. dlib->SetSize(6, false);
  1003. dlib->SetData(dirLightIndexData);
  1004. dirLightGeometry_ = new Geometry(context_);
  1005. dirLightGeometry_->SetVertexBuffer(0, dlvb);
  1006. dirLightGeometry_->SetIndexBuffer(dlib);
  1007. dirLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, dlib->GetIndexCount());
  1008. SharedPtr<VertexBuffer> plvb(new VertexBuffer(context_));
  1009. plvb->SetSize(24, MASK_POSITION);
  1010. plvb->SetData(pointLightVertexData);
  1011. SharedPtr<IndexBuffer> plib(new IndexBuffer(context_));
  1012. plib->SetSize(132, false);
  1013. plib->SetData(pointLightIndexData);
  1014. pointLightGeometry_ = new Geometry(context_);
  1015. pointLightGeometry_->SetVertexBuffer(0, plvb);
  1016. pointLightGeometry_->SetIndexBuffer(plib);
  1017. pointLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, plib->GetIndexCount());
  1018. SharedPtr<VertexBuffer> slvb(new VertexBuffer(context_));
  1019. slvb->SetSize(8, MASK_POSITION);
  1020. slvb->SetData(spotLightVertexData);
  1021. SharedPtr<IndexBuffer> slib(new IndexBuffer(context_));
  1022. slib->SetSize(36, false);
  1023. slib->SetData(spotLightIndexData);
  1024. spotLightGeometry_ = new Geometry(context_);
  1025. spotLightGeometry_->SetVertexBuffer(0, slvb);
  1026. spotLightGeometry_->SetIndexBuffer(slib);
  1027. spotLightGeometry_->SetDrawRange(TRIANGLE_LIST, 0, slib->GetIndexCount());
  1028. }
  1029. void Renderer::CreateInstancingBuffer()
  1030. {
  1031. // Do not create buffer if instancing not supported
  1032. if (!graphics_->GetSM3Support())
  1033. {
  1034. dynamicInstancing_ = false;
  1035. return;
  1036. }
  1037. // If must lock the buffer for each batch group, set a smaller size
  1038. unsigned defaultSize = graphics_->GetStreamOffsetSupport() ? INSTANCING_BUFFER_DEFAULT_SIZE : INSTANCING_BUFFER_DEFAULT_SIZE / 4;
  1039. instancingBuffer_ = new VertexBuffer(context_);
  1040. if (!instancingBuffer_->SetSize(defaultSize, INSTANCING_BUFFER_MASK, true))
  1041. {
  1042. instancingBuffer_.Reset();
  1043. dynamicInstancing_ = false;
  1044. }
  1045. }
  1046. bool Renderer::ResizeInstancingBuffer(unsigned numInstances)
  1047. {
  1048. if (!instancingBuffer_)
  1049. return false;
  1050. unsigned oldSize = instancingBuffer_->GetVertexCount();
  1051. if (numInstances <= oldSize)
  1052. return true;
  1053. unsigned newSize = INSTANCING_BUFFER_DEFAULT_SIZE;
  1054. while (newSize < numInstances)
  1055. newSize <<= 1;
  1056. if (!instancingBuffer_->SetSize(newSize, INSTANCING_BUFFER_MASK, true))
  1057. {
  1058. LOGERROR("Failed to resize instancing buffer to " + String(newSize));
  1059. // If failed, try to restore the old size
  1060. instancingBuffer_->SetSize(oldSize, INSTANCING_BUFFER_MASK, true);
  1061. return false;
  1062. }
  1063. LOGDEBUG("Resized instancing buffer to " + String(newSize));
  1064. return true;
  1065. }
  1066. bool Renderer::CreateShadowMaps()
  1067. {
  1068. unsigned shadowMapFormat = shadowMapHiresDepth_ ? graphics_->GetHiresShadowMapFormat() : graphics_->GetShadowMapFormat();
  1069. unsigned dummyColorFormat = graphics_->GetDummyColorFormat();
  1070. bool hardwarePCF = graphics_->GetHardwareShadowSupport();
  1071. if (!shadowMapFormat)
  1072. return false;
  1073. if (!drawShadows_)
  1074. {
  1075. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1076. {
  1077. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1078. shadowMaps_[i][j].Reset();
  1079. }
  1080. return true;
  1081. }
  1082. #ifdef USE_OPENGL
  1083. // Create shadow maps only. Color rendertargets are not needed
  1084. unsigned size = shadowMapSize_;
  1085. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1086. {
  1087. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1088. {
  1089. if (!shadowMaps_[i][j])
  1090. shadowMaps_[i][j] = new Texture2D(context_);
  1091. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1092. return false;
  1093. shadowMaps_[i][j]->SetFilterMode(FILTER_BILINEAR);
  1094. shadowMaps_[i][j]->SetShadowCompare(true);
  1095. }
  1096. size >>= 1;
  1097. }
  1098. #else
  1099. // Create shadow maps and dummy color rendertargets
  1100. unsigned size = shadowMapSize_;
  1101. for (unsigned i = 0; i < NUM_SHADOWMAP_RESOLUTIONS; ++i)
  1102. {
  1103. if (!colorShadowMaps_[i])
  1104. colorShadowMaps_[i] = new Texture2D(context_);
  1105. if (!colorShadowMaps_[i]->SetSize(size, size, dummyColorFormat, TEXTURE_RENDERTARGET))
  1106. return false;
  1107. for (unsigned j = 0; j < shadowMaps_[i].Size(); ++j)
  1108. {
  1109. if (!shadowMaps_[i][j])
  1110. shadowMaps_[i][j] = new Texture2D(context_);
  1111. if (!shadowMaps_[i][j]->SetSize(size, size, shadowMapFormat, TEXTURE_DEPTHSTENCIL))
  1112. return false;
  1113. shadowMaps_[i][j]->SetFilterMode(hardwarePCF ? FILTER_BILINEAR : FILTER_NEAREST);
  1114. // Link the color rendertarget to depth rendertarget
  1115. shadowMaps_[i][j]->GetRenderSurface()->SetLinkedRenderTarget(colorShadowMaps_[i]->GetRenderSurface());
  1116. }
  1117. size >>= 1;
  1118. }
  1119. #endif
  1120. return true;
  1121. }
  1122. Camera* Renderer::CreateShadowCamera()
  1123. {
  1124. if (numShadowCameras_ >= shadowCameraStore_.Size())
  1125. shadowCameraStore_.Push(SharedPtr<Camera>(new Camera(context_)));
  1126. Camera* camera = shadowCameraStore_[numShadowCameras_];
  1127. camera->SetNode(CreateTempNode());
  1128. ++numShadowCameras_;
  1129. return camera;
  1130. }
  1131. Light* Renderer::CreateSplitLight(Light* original)
  1132. {
  1133. if (numSplitLights_ >= splitLightStore_.Size())
  1134. splitLightStore_.Push(SharedPtr<Light>(new Light(context_)));
  1135. Light* light = splitLightStore_[numSplitLights_];
  1136. light->SetNode(CreateTempNode());
  1137. light->copyFrom(original);
  1138. ++numSplitLights_;
  1139. return light;
  1140. }
  1141. Node* Renderer::CreateTempNode()
  1142. {
  1143. if (numTempNodes_ >= tempNodeStore_.Size())
  1144. tempNodeStore_.Push(SharedPtr<Node>(new Node(context_)));
  1145. Node* node = tempNodeStore_[numTempNodes_];
  1146. ++numTempNodes_;
  1147. return node;
  1148. }
  1149. void Renderer::SetupLightBatch(Batch& batch)
  1150. {
  1151. graphics_->ClearTransformSources();
  1152. Matrix3x4 view(batch.camera_->GetInverseWorldTransform());
  1153. Light* light = batch.light_;
  1154. float lightExtent = light->GetVolumeExtent();
  1155. float lightViewDist = (light->GetWorldPosition() - batch.camera_->GetWorldPosition()).LengthFast();
  1156. graphics_->SetAlphaTest(false);
  1157. graphics_->SetBlendMode(BLEND_ADD);
  1158. graphics_->SetDepthWrite(false);
  1159. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  1160. {
  1161. // Get projection without jitter offset to ensure the whole screen is filled
  1162. Matrix4 projection(batch.camera_->GetProjection(false));
  1163. // If the light does not extend to the near plane, use a stencil test. Else just draw with depth fail
  1164. if (light->GetNearSplit() <= batch.camera_->GetNearClip())
  1165. {
  1166. graphics_->SetCullMode(CULL_NONE);
  1167. graphics_->SetDepthTest(CMP_GREATER);
  1168. graphics_->SetStencilTest(false);
  1169. }
  1170. else
  1171. {
  1172. Matrix3x4 nearTransform = light->GetDirLightTransform(*batch.camera_, true);
  1173. // Set state for stencil rendering
  1174. graphics_->SetColorWrite(false);
  1175. graphics_->SetCullMode(CULL_NONE);
  1176. graphics_->SetDepthTest(CMP_LESSEQUAL);
  1177. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1178. graphics_->SetShaders(stencilVS_, stencilPS_);
  1179. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1180. graphics_->SetShaderParameter(VSP_MODEL, nearTransform);
  1181. // Draw to stencil
  1182. batch.geometry_->Draw(graphics_);
  1183. // Re-enable color write, set test for rendering the actual light
  1184. graphics_->SetColorWrite(true);
  1185. graphics_->SetDepthTest(CMP_GREATER);
  1186. graphics_->SetStencilTest(true, CMP_EQUAL, OP_ZERO, OP_KEEP, OP_ZERO, 1);
  1187. }
  1188. }
  1189. else
  1190. {
  1191. Matrix4 projection(batch.camera_->GetProjection());
  1192. const Matrix3x4& model = light->GetVolumeTransform(*batch.camera_);
  1193. if (light->GetLightType() == LIGHT_SPLITPOINT)
  1194. {
  1195. // Shadowed point light, split in 6 frustums: mask out overlapping pixels to prevent overlighting
  1196. // Check whether we should draw front or back faces
  1197. bool drawBackFaces = lightViewDist < (lightExtent + batch.camera_->GetNearClip());
  1198. graphics_->SetColorWrite(false);
  1199. graphics_->SetCullMode(drawBackFaces ? CULL_CCW : CULL_CW);
  1200. graphics_->SetDepthTest(drawBackFaces ? CMP_GREATER : CMP_LESS);
  1201. graphics_->SetStencilTest(true, CMP_EQUAL, OP_INCR, OP_KEEP, OP_KEEP, 0);
  1202. graphics_->SetShaders(stencilVS_, stencilPS_);
  1203. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1204. graphics_->SetShaderParameter(VSP_MODEL, model);
  1205. // Draw the other faces to stencil to mark where we should not draw
  1206. batch.geometry_->Draw(graphics_);
  1207. graphics_->SetColorWrite(true);
  1208. graphics_->SetCullMode(drawBackFaces ? CULL_CW : CULL_CCW);
  1209. graphics_->SetStencilTest(true, CMP_EQUAL, OP_DECR, OP_DECR, OP_KEEP, 0);
  1210. }
  1211. else
  1212. {
  1213. // If light is close to near clip plane, we might be inside light volume
  1214. if (lightViewDist < (lightExtent + batch.camera_->GetNearClip()))
  1215. {
  1216. // In this case reverse cull mode & depth test and render back faces
  1217. graphics_->SetCullMode(CULL_CW);
  1218. graphics_->SetDepthTest(CMP_GREATER);
  1219. graphics_->SetStencilTest(false);
  1220. }
  1221. else
  1222. {
  1223. // If not too close to far clip plane, write the back faces to stencil for optimization,
  1224. // then render front faces. Else just render front faces.
  1225. if (lightViewDist < (batch.camera_->GetFarClip() - lightExtent))
  1226. {
  1227. // Set state for stencil rendering
  1228. graphics_->SetColorWrite(false);
  1229. graphics_->SetCullMode(CULL_CW);
  1230. graphics_->SetDepthTest(CMP_GREATEREQUAL);
  1231. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_INCR, OP_KEEP, OP_KEEP, 1);
  1232. graphics_->SetShaders(stencilVS_, stencilPS_);
  1233. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  1234. graphics_->SetShaderParameter(VSP_MODEL, model);
  1235. // Draw to stencil
  1236. batch.geometry_->Draw(graphics_);
  1237. // Re-enable color write, set test for rendering the actual light
  1238. graphics_->SetColorWrite(true);
  1239. graphics_->SetStencilTest(true, CMP_EQUAL, OP_ZERO, OP_KEEP, OP_ZERO, 1);
  1240. graphics_->SetCullMode(CULL_CCW);
  1241. graphics_->SetDepthTest(CMP_LESS);
  1242. }
  1243. else
  1244. {
  1245. graphics_->SetStencilTest(false);
  1246. graphics_->SetCullMode(CULL_CCW);
  1247. graphics_->SetDepthTest(CMP_LESS);
  1248. }
  1249. }
  1250. }
  1251. }
  1252. }
  1253. void Renderer::DrawFullScreenQuad(Camera& camera, ShaderVariation* vs, ShaderVariation* ps, bool nearQuad, const HashMap<ShaderParameter, Vector4>& shaderParameters)
  1254. {
  1255. graphics_->ClearTransformSources();
  1256. Light quadDirLight(context_);
  1257. Matrix3x4 model(quadDirLight.GetDirLightTransform(camera, nearQuad));
  1258. graphics_->SetCullMode(CULL_NONE);
  1259. graphics_->SetShaders(vs, ps);
  1260. graphics_->SetShaderParameter(VSP_MODEL, model);
  1261. // Get projection without jitter offset to ensure the whole screen is filled
  1262. graphics_->SetShaderParameter(VSP_VIEWPROJ, camera.GetProjection(false));
  1263. // Set global shader parameters as needed
  1264. for (HashMap<ShaderParameter, Vector4>::ConstIterator i = shaderParameters.Begin(); i != shaderParameters.End(); ++i)
  1265. {
  1266. if (graphics_->NeedParameterUpdate(i->first_, &shaderParameters))
  1267. graphics_->SetShaderParameter(i->first_, i->second_);
  1268. }
  1269. dirLightGeometry_->Draw(graphics_);
  1270. }
  1271. void Renderer::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1272. {
  1273. if (!initialized_)
  1274. Initialize();
  1275. else
  1276. {
  1277. // When screen mode changes, reload shaders and purge old views and occlusion buffers
  1278. shadersDirty_ = true;
  1279. occlusionBuffers_.Clear();
  1280. ResetViews();
  1281. }
  1282. }
  1283. void Renderer::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  1284. {
  1285. if (initialized_)
  1286. {
  1287. using namespace RenderUpdate;
  1288. Update(eventData[P_TIMESTEP].GetFloat());
  1289. }
  1290. }