Renderer.cpp 41 KB

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