Renderer.cpp 41 KB

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