Renderer.cpp 45 KB

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