2
0

Renderer.cpp 41 KB

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