Renderer.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. #pragma once
  24. #include "Batch.h"
  25. #include "Color.h"
  26. #include "Drawable.h"
  27. #include "HashMap.h"
  28. #include "HashSet.h"
  29. #include "Mutex.h"
  30. #include "RenderSurface.h"
  31. class DebugRenderer;
  32. class Geometry;
  33. class Drawable;
  34. class Light;
  35. class Material;
  36. class Pass;
  37. class Technique;
  38. class Octree;
  39. class Graphics;
  40. class ResourceCache;
  41. class Skeleton;
  42. class OcclusionBuffer;
  43. class Texture2D;
  44. class TextureCube;
  45. class View;
  46. class Zone;
  47. static const int SHADOW_MIN_PIXELS = 64;
  48. static const int NUM_LIGHT_TYPES = 3;
  49. static const int NUM_SHADOWMAP_RESOLUTIONS = 3;
  50. static const int INSTANCING_BUFFER_DEFAULT_SIZE = 1024;
  51. /// Light vertex shader variations.
  52. enum LightVSVariation
  53. {
  54. LVS_DIR = 0,
  55. LVS_SPOT,
  56. LVS_POINT,
  57. LVS_SPEC,
  58. LVS_SPOTSPEC,
  59. LVS_POINTSPEC,
  60. LVS_SHADOW,
  61. LVS_SPOTSHADOW,
  62. LVS_POINTSHADOW,
  63. LVS_DIRSPECSHADOW,
  64. LVS_SPOTSPECSHADOW,
  65. LVS_POINTSPECSHADOW,
  66. MAX_LIGHT_VS_VARIATIONS
  67. };
  68. /// Per-vertex light vertex shader variations.
  69. enum VertexLightVSVariation
  70. {
  71. VLVS_NOLIGHTS = 0,
  72. VLVS_1LIGHT,
  73. VLVS_2LIGHTS,
  74. VLVS_3LIGHTS,
  75. VLVS_4LIGHTS,
  76. VLVS_5LIGHTS,
  77. VLVS_6LIGHTS,
  78. MAX_VERTEXLIGHT_VS_VARIATIONS
  79. };
  80. /// Light pixel shader variations.
  81. enum LightPSVariation
  82. {
  83. LPS_NONE = 0,
  84. LPS_SPOT,
  85. LPS_POINT,
  86. LPS_POINTMASK,
  87. LPS_SPEC,
  88. LPS_SPOTSPEC,
  89. LPS_POINTSPEC,
  90. LPS_POINTMASKSPEC,
  91. LPS_SHADOW,
  92. LPS_SPOTSHADOW,
  93. LPS_POINTSHADOW,
  94. LPS_POINTMASKSHADOW,
  95. LPS_SHADOWSPEC,
  96. LPS_SPOTSHADOWSPEC,
  97. LPS_POINTSHADOWSPEC,
  98. LPS_POINTMASKSHADOWSPEC,
  99. MAX_LIGHT_PS_VARIATIONS
  100. };
  101. /// Deferred light volume vertex shader variations.
  102. enum DeferredLightVSVariation
  103. {
  104. DLVS_NONE = 0,
  105. DLVS_DIR,
  106. DLVS_ORTHO,
  107. DLVS_ORTHODIR,
  108. MAX_DEFERRED_LIGHT_VS_VARIATIONS
  109. };
  110. /// Deferred light volume pixels shader variations.
  111. enum DeferredLightPSVariation
  112. {
  113. DLPS_NONE = 0,
  114. DLPS_SPOT,
  115. DLPS_POINT,
  116. DLPS_POINTMASK,
  117. DLPS_SPEC,
  118. DLPS_SPOTSPEC,
  119. DLPS_POINTSPEC,
  120. DLPS_POINTMASKSPEC,
  121. DLPS_SHADOW,
  122. DLPS_SPOTSHADOW,
  123. DLPS_POINTSHADOW,
  124. DLPS_POINTMASKSHADOW,
  125. DLPS_SHADOWSPEC,
  126. DLPS_SPOTSHADOWSPEC,
  127. DLPS_POINTSHADOWSPEC,
  128. DLPS_POINTMASKSHADOWSPEC,
  129. DLPS_ORTHO,
  130. DLPS_ORTHOSPOT,
  131. DLPS_ORTHOPOINT,
  132. DLPS_ORTHOPOINTMASK,
  133. DLPS_ORTHOSPEC,
  134. DLPS_ORTHOSPOTSPEC,
  135. DLPS_ORTHOPOINTSPEC,
  136. DLPS_ORTHOPOINTMASKSPEC,
  137. DLPS_ORTHOSHADOW,
  138. DLPS_ORTHOSPOTSHADOW,
  139. DLPS_ORTHOPOINTSHADOW,
  140. DLPS_ORTHOPOINTMASKSHADOW,
  141. DLPS_ORTHOSHADOWSPEC,
  142. DLPS_ORTHOSPOTSHADOWSPEC,
  143. DLPS_ORTHOPOINTSHADOWSPEC,
  144. DLPS_ORTHOPOINTMASKSHADOWSPEC,
  145. MAX_DEFERRED_LIGHT_PS_VARIATIONS
  146. };
  147. /// Deferred rendering edge filter parameters.
  148. struct EdgeFilterParameters
  149. {
  150. /// Construct undefined.
  151. EdgeFilterParameters()
  152. {
  153. }
  154. /// Construct with initial values.
  155. EdgeFilterParameters(float radius, float threshold, float strength) :
  156. radius_(radius),
  157. threshold_(threshold),
  158. strength_(strength)
  159. {
  160. }
  161. //! Validate parameters.
  162. void Validate();
  163. //! Radius for calculating luminance gradient.
  164. float radius_;
  165. //! Luminance difference threshold needed to pass pixel.
  166. float threshold_;
  167. //! Filter strength.
  168. float strength_;
  169. };
  170. /// High-level rendering subsystem. Manages drawing of 3D views.
  171. class Renderer : public Object
  172. {
  173. OBJECT(Object);
  174. public:
  175. /// Construct.
  176. Renderer(Context* context);
  177. /// Destruct.
  178. virtual ~Renderer();
  179. /// %Set number of viewports to render.
  180. void SetNumViewports(unsigned num);
  181. /// %Set a viewport.
  182. void SetViewport(unsigned index, const Viewport& viewport);
  183. /// %Set light prepass rendering on/off.
  184. void SetLightPrepass(bool enable);
  185. /// %Set specular lighting on/off.
  186. void SetSpecularLighting(bool enable);
  187. /// %Set texture anisotropy.
  188. void SetTextureAnisotropy(int level);
  189. /// %Set texture filtering.
  190. void SetTextureFilterMode(TextureFilterMode mode);
  191. /// %Set texture quality level.
  192. void SetTextureQuality(int quality);
  193. /// %Set material quality level.
  194. void SetMaterialQuality(int quality);
  195. /// %Set shadows on/off.
  196. void SetDrawShadows(bool enable);
  197. /// %Set shadow map resolution.
  198. void SetShadowMapSize(int size);
  199. /// %Set shadow quality (amount of samples and bit depth.)
  200. void SetShadowQuality(int quality);
  201. /// %Set reuse of shadow maps. Default is true. If disabled, also transparent geometry can be shadowed.
  202. void SetReuseShadowMaps(bool enable);
  203. /// %Set maximum number of shadow maps created for one resolution. Only has effect if reuse of shadow maps is disabled.
  204. void SetMaxShadowMaps(int shadowMaps);
  205. /// %Set maximum number of directional light shadow map cascades. Affects the size of directional light shadow maps.
  206. void SetMaxShadowCascades(int cascades);
  207. /// %Set light stencil optimization on/off.
  208. void SetLightStencilMasking(bool enable);
  209. /// %Set dynamic instancing on/off.
  210. void SetDynamicInstancing(bool enable);
  211. /// %Set maximum number of triangles per object for instancing.
  212. void SetMaxInstanceTriangles(int triangles);
  213. /// %Set maximum number of occluder trianges.
  214. void SetMaxOccluderTriangles(int triangles);
  215. /// %Set occluder buffer width.
  216. void SetOcclusionBufferSize(int size);
  217. /// %Set required screen size (1.0 = full screen) for occluders.
  218. void SetOccluderSizeThreshold(float screenSize);
  219. /// Return number of viewports.
  220. unsigned GetNumViewports() const { return viewports_.Size(); }
  221. /// Return viewport.
  222. const Viewport& GetViewport(unsigned index) const;
  223. /// Return whether light prepass rendering is enabled.
  224. bool GetLightPrepass() const { return lightPrepass_; }
  225. /// Return whether specular lighting is enabled.
  226. bool GetSpecularLighting() const { return specularLighting_; }
  227. /// Return whether drawing shadows is enabled.
  228. bool GetDrawShadows() const { return drawShadows_; }
  229. /// Return texture anisotropy.
  230. int GetTextureAnisotropy() const { return textureAnisotropy_; }
  231. /// Return texture filtering.
  232. TextureFilterMode GetTextureFilterMode() const { return textureFilterMode_; }
  233. /// Return texture quality level.
  234. int GetTextureQuality() const { return textureQuality_; }
  235. /// Return material quality level.
  236. int GetMaterialQuality() const { return materialQuality_; }
  237. /// Return shadow map resolution.
  238. int GetShadowMapSize() const { return shadowMapSize_; }
  239. /// Return shadow quality.
  240. int GetShadowQuality() const { return shadowQuality_; }
  241. /// Return whether shadow maps are reused.
  242. bool GetReuseShadowMaps() const { return reuseShadowMaps_; }
  243. /// Return maximum number of shadow maps per resolution.
  244. int GetMaxShadowMaps() const { return maxShadowMaps_; }
  245. /// Return maximum number of directional light shadow map cascades.
  246. int GetMaxShadowCascades() const { return maxShadowCascades_; }
  247. /// Return whether light stencil optimization is in use.
  248. bool GetLightStencilMasking() const { return lightStencilMasking_; }
  249. /// Return whether dynamic instancing is in use.
  250. bool GetDynamicInstancing() const { return dynamicInstancing_; }
  251. /// Return maximum number of triangles per object for instancing.
  252. int GetMaxInstanceTriangles() { return maxInstanceTriangles_; }
  253. /// Return maximum number of occluder triangles.
  254. int GetMaxOccluderTriangles() const { return maxOccluderTriangles_; }
  255. /// Return occlusion buffer width.
  256. int GetOcclusionBufferSize() const { return occlusionBufferSize_; }
  257. /// Return occluder screen size threshold.
  258. float GetOccluderSizeThreshold() const { return occluderSizeThreshold_; }
  259. /// Return number of views rendered.
  260. unsigned GetNumViews() const { return numViews_; }
  261. /// Return number of primitives rendered.
  262. unsigned GetNumPrimitives() const { return numPrimitives_; }
  263. /// Return number of batches rendered.
  264. unsigned GetNumBatches() const { return numBatches_; }
  265. /// Return number of geometries rendered.
  266. unsigned GetNumGeometries(bool allViews = false) const;
  267. /// Return number of lights rendered.
  268. unsigned GetNumLights(bool allViews = false) const;
  269. /// Return number of shadow maps rendered.
  270. unsigned GetNumShadowMaps(bool allViews = false) const;
  271. /// Return number of occluders rendered.
  272. unsigned GetNumOccluders(bool allViews = false) const;
  273. /// Return the default zone.
  274. Zone* GetDefaultZone() const { return defaultZone_; }
  275. /// Return the default material.
  276. Material* GetDefaultMaterial() const { return defaultMaterial_; }
  277. /// Return the default range attenuation texture.
  278. Texture2D* GetDefaultLightRamp() const { return defaultLightRamp_; }
  279. /// Return the default spotlight attenuation texture.
  280. Texture2D* GetDefaultLightSpot() const { return defaultLightSpot_; }
  281. /// Return the shadowed pointlight face selection cube map.
  282. TextureCube* GetFaceSelectCubeMap() const { return faceSelectCubeMap_; }
  283. /// Return the shadowed pointlight indirection cube map.
  284. TextureCube* GetIndirectionCubeMap() const { return indirectionCubeMap_; }
  285. /// Return the normal buffer for light pre-pass rendering.
  286. Texture2D* GetNormalBuffer() const { return normalBuffer_; }
  287. /// Return the depth buffer for light pre-pass rendering.
  288. Texture2D* GetDepthBuffer() const { return depthBuffer_; }
  289. /// Return the light accumulation buffer for light pre-pass rendering.
  290. Texture2D* GetLightBuffer() const { return lightBuffer_; }
  291. /// Return the instancing vertex buffer
  292. VertexBuffer* GetInstancingBuffer() const { return dynamicInstancing_ ? instancingBuffer_ : (VertexBuffer*)0; }
  293. /// Return a vertex shader by name.
  294. ShaderVariation* GetVertexShader(const String& name, bool checkExists = false) const;
  295. /// Return a pixel shader by name.
  296. ShaderVariation* GetPixelShader(const String& name, bool checkExists = false) const;
  297. /// Return the stencil vertex shader.
  298. ShaderVariation* GetStencilVS() const { return stencilVS_; }
  299. /// Return the stencil pixel shader.
  300. ShaderVariation* GetStencilPS() const { return stencilPS_; }
  301. /// Return the frame update parameters.
  302. const FrameInfo& GetFrameInfo() { return frame_; }
  303. /// Update for rendering. Called by HandleRenderUpdate().
  304. void Update(float timeStep);
  305. /// Render. Called by Engine.
  306. void Render();
  307. /// Add debug geometry to the debug renderer.
  308. void DrawDebugGeometry(bool depthTest);
  309. /// Add a view. Return true if successful.
  310. bool AddView(RenderSurface* renderTarget, const Viewport& viewport);
  311. /// Return volume geometry for a light.
  312. Geometry* GetLightGeometry(Light* light);
  313. /// Allocate a shadow map. If shadow map reuse is disabled, a different map is returned each time.
  314. Texture2D* GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight);
  315. /// Allocate an occlusion buffer.
  316. OcclusionBuffer* GetOcclusionBuffer(Camera* camera);
  317. /// Allocate a temporary shadow camera and a scene node for it. Is thread-safe.
  318. Camera* GetShadowCamera();
  319. /// Get a shader program.
  320. ShaderVariation* GetShader(const String& name, const String& extension, bool checkExists) const;
  321. /// Choose shaders for a forward rendering batch.
  322. void SetBatchShaders(Batch& batch, Technique* technique, Pass* pass, bool allowShadows = true);
  323. /// Choose shaders for a light volume batch.
  324. void SetLightVolumeShaders(Batch& batch);
  325. /// Ensure sufficient size of the instancing vertex buffer. Return true if successful.
  326. bool ResizeInstancingBuffer(unsigned numInstances);
  327. /// Reset shadow map allocation counts.
  328. void ResetShadowMapAllocations();
  329. private:
  330. /// Initialize when screen mode initially set.
  331. void Initialize();
  332. /// Clear views from previous frame.
  333. void ResetViews();
  334. /// Reload shaders.
  335. void LoadShaders();
  336. /// Reload shaders for a material technique.
  337. void LoadMaterialShaders(Technique* technique);
  338. /// Reload shaders for a material pass.
  339. void LoadPassShaders(Technique* technique, PassType type, bool allowShadows = true);
  340. /// Release shaders used in materials.
  341. void ReleaseMaterialShaders();
  342. /// Reload textures.
  343. void ReloadTextures();
  344. /// Create light volume geometries.
  345. void CreateGeometries();
  346. /// Create instancing vertex buffer.
  347. void CreateInstancingBuffer();
  348. /// Remove all shadow maps. Called when global shadow map resolution or format is changed.
  349. void ResetShadowMaps();
  350. /// Handle screen mode event.
  351. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  352. /// Handle graphics features (re)check event.
  353. void HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData);
  354. /// Handle render update event.
  355. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  356. /// Graphics subsystem.
  357. WeakPtr<Graphics> graphics_;
  358. /// Resource cache subsystem.
  359. WeakPtr<ResourceCache> cache_;
  360. /// Default zone.
  361. SharedPtr<Zone> defaultZone_;
  362. /// Directional light quad geometry.
  363. SharedPtr<Geometry> dirLightGeometry_;
  364. /// Spot light volume geometry.
  365. SharedPtr<Geometry> spotLightGeometry_;
  366. /// Point light volume geometry.
  367. SharedPtr<Geometry> pointLightGeometry_;
  368. /// Instance stream vertex buffer.
  369. SharedPtr<VertexBuffer> instancingBuffer_;
  370. /// Default material.
  371. SharedPtr<Material> defaultMaterial_;
  372. /// Default range attenuation texture.
  373. SharedPtr<Texture2D> defaultLightRamp_;
  374. /// Default spotlight attenuation texture.
  375. SharedPtr<Texture2D> defaultLightSpot_;
  376. /// Face selection cube map for shadowed pointlights.
  377. SharedPtr<TextureCube> faceSelectCubeMap_;
  378. /// Indirection cube map for shadowed pointlights.
  379. SharedPtr<TextureCube> indirectionCubeMap_;
  380. /// Normal buffer for light pre-pass rendering.
  381. SharedPtr<Texture2D> normalBuffer_;
  382. /// Depth buffer for light pre-pass rendering.
  383. SharedPtr<Texture2D> depthBuffer_;
  384. /// Light accumulation buffer for light pre-pass rendering.
  385. SharedPtr<Texture2D> lightBuffer_;
  386. /// Stencil rendering vertex shader.
  387. SharedPtr<ShaderVariation> stencilVS_;
  388. /// Stencil rendering pixel shader.
  389. SharedPtr<ShaderVariation> stencilPS_;
  390. /// Light vertex shaders.
  391. Vector<SharedPtr<ShaderVariation> > lightVS_;
  392. /// Light pixel shaders.
  393. Vector<SharedPtr<ShaderVariation> > lightPS_;
  394. /// Reusable scene nodes with shadow camera components.
  395. Vector<SharedPtr<Node> > shadowCameraNodes_;
  396. /// Reusable occlusion buffers.
  397. Vector<SharedPtr<OcclusionBuffer> > occlusionBuffers_;
  398. /// Shadow maps by resolution.
  399. HashMap<int, Vector<SharedPtr<Texture2D> > > shadowMaps_;
  400. /// Shadow map dummy color buffers by resolution.
  401. HashMap<int, SharedPtr<Texture2D> > colorShadowMaps_;
  402. /// Shadow map allocations by resolution.
  403. HashMap<int, PODVector<Light*> > shadowMapAllocations_;
  404. /// Shadow map stencil buffer, fallback mode only.
  405. SharedPtr<Texture2D> shadowDepthStencil_;
  406. /// Viewports.
  407. Vector<Viewport> viewports_;
  408. /// Views.
  409. Vector<SharedPtr<View> > views_;
  410. /// Octrees that have been updated during the frame.
  411. HashSet<Octree*> updateOctrees_;
  412. /// Techniques for which missing shader error has been displayed.
  413. HashSet<Technique*> shaderErrorDisplayed_;
  414. /// Mutex for shadow camera allocation.
  415. Mutex rendererMutex_;
  416. /// Vertex shader format.
  417. String vsFormat_;
  418. /// Pixel shader format.
  419. String psFormat_;
  420. /// Base directory for shaders.
  421. String shaderPath_;
  422. /// Frame info for rendering.
  423. FrameInfo frame_;
  424. /// Texture anisotropy level.
  425. int textureAnisotropy_;
  426. /// Texture filtering mode.
  427. TextureFilterMode textureFilterMode_;
  428. /// Texture quality level.
  429. int textureQuality_;
  430. /// Material quality level.
  431. int materialQuality_;
  432. /// Shadow map resolution.
  433. int shadowMapSize_;
  434. /// Shadow quality.
  435. int shadowQuality_;
  436. /// Maximum number of shadow maps per resolution.
  437. int maxShadowMaps_;
  438. /// Maximum number of directional light shadow cascades.
  439. int maxShadowCascades_;
  440. /// Maximum triangles per object for instancing.
  441. int maxInstanceTriangles_;
  442. /// Maximum occluder triangles.
  443. int maxOccluderTriangles_;
  444. /// Occlusion buffer width.
  445. int occlusionBufferSize_;
  446. /// Occluder screen size threshold.
  447. float occluderSizeThreshold_;
  448. /// Number of views.
  449. unsigned numViews_;
  450. /// Number of occlusion buffers in use.
  451. unsigned numOcclusionBuffers_;
  452. /// Number of temporary shadow cameras in use.
  453. unsigned numShadowCameras_;
  454. /// Number of primitives (3D geometry only.)
  455. unsigned numPrimitives_;
  456. /// Number of batches (3D geometry only.)
  457. unsigned numBatches_;
  458. /// Frame number on which shaders last changed.
  459. unsigned shadersChangedFrameNumber_;
  460. /// Light prepass mode flag.
  461. bool lightPrepass_;
  462. /// Specular lighting flag.
  463. bool specularLighting_;
  464. /// Draw shadows flag.
  465. bool drawShadows_;
  466. /// Shadow map reuse flag.
  467. bool reuseShadowMaps_;
  468. /// Light stencil optimization flag.
  469. bool lightStencilMasking_;
  470. /// Dynamic instancing flag.
  471. bool dynamicInstancing_;
  472. /// Shaders need reloading flag.
  473. bool shadersDirty_;
  474. /// Initialized flag.
  475. bool initialized_;
  476. };