Renderer.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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 "HashSet.h"
  28. #include "Mutex.h"
  29. #include "Viewport.h"
  30. class DebugRenderer;
  31. class Geometry;
  32. class Drawable;
  33. class Light;
  34. class Material;
  35. class Pass;
  36. class Technique;
  37. class Octree;
  38. class Graphics;
  39. class RenderSurface;
  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. /// High-level rendering subsystem. Manages drawing of 3D views.
  148. class Renderer : public Object
  149. {
  150. OBJECT(Object);
  151. public:
  152. /// Construct.
  153. Renderer(Context* context);
  154. /// Destruct.
  155. virtual ~Renderer();
  156. /// %Set number of viewports to render.
  157. void SetNumViewports(unsigned num);
  158. /// %Set a viewport. Return true if successful.
  159. bool SetViewport(unsigned index, Viewport* viewport);
  160. /// %Set rendering mode (forward / light pre-pass / deferred.)
  161. void SetRenderMode(RenderMode mode);
  162. /// %Set specular lighting on/off.
  163. void SetSpecularLighting(bool enable);
  164. /// %Set texture anisotropy.
  165. void SetTextureAnisotropy(int level);
  166. /// %Set texture filtering.
  167. void SetTextureFilterMode(TextureFilterMode mode);
  168. /// %Set texture quality level.
  169. void SetTextureQuality(int quality);
  170. /// %Set material quality level.
  171. void SetMaterialQuality(int quality);
  172. /// %Set shadows on/off.
  173. void SetDrawShadows(bool enable);
  174. /// %Set shadow map resolution.
  175. void SetShadowMapSize(int size);
  176. /// %Set shadow quality (amount of samples and bit depth.)
  177. void SetShadowQuality(int quality);
  178. /// %Set reuse of shadow maps. Default is true. If disabled, also transparent geometry can be shadowed.
  179. void SetReuseShadowMaps(bool enable);
  180. /// %Set maximum number of shadow maps created for one resolution. Only has effect if reuse of shadow maps is disabled.
  181. void SetMaxShadowMaps(int shadowMaps);
  182. /// %Set maximum number of directional light shadow map cascades. Affects the size of directional light shadow maps.
  183. void SetMaxShadowCascades(int cascades);
  184. /// %Set dynamic instancing on/off.
  185. void SetDynamicInstancing(bool enable);
  186. /// %Set maximum number of triangles per object for instancing.
  187. void SetMaxInstanceTriangles(int triangles);
  188. /// %Set maximum number of occluder trianges.
  189. void SetMaxOccluderTriangles(int triangles);
  190. /// %Set occluder buffer width.
  191. void SetOcclusionBufferSize(int size);
  192. /// %Set required screen size (1.0 = full screen) for occluders.
  193. void SetOccluderSizeThreshold(float screenSize);
  194. /// Return number of viewports.
  195. unsigned GetNumViewports() const { return viewports_.Size(); }
  196. /// Return viewport.
  197. Viewport* GetViewport(unsigned index) const;
  198. /// Return rendering mode.
  199. RenderMode GetRenderMode() const { return renderMode_; }
  200. /// Return whether specular lighting is enabled.
  201. bool GetSpecularLighting() const { return specularLighting_; }
  202. /// Return whether drawing shadows is enabled.
  203. bool GetDrawShadows() const { return drawShadows_; }
  204. /// Return texture anisotropy.
  205. int GetTextureAnisotropy() const { return textureAnisotropy_; }
  206. /// Return texture filtering.
  207. TextureFilterMode GetTextureFilterMode() const { return textureFilterMode_; }
  208. /// Return texture quality level.
  209. int GetTextureQuality() const { return textureQuality_; }
  210. /// Return material quality level.
  211. int GetMaterialQuality() const { return materialQuality_; }
  212. /// Return shadow map resolution.
  213. int GetShadowMapSize() const { return shadowMapSize_; }
  214. /// Return shadow quality.
  215. int GetShadowQuality() const { return shadowQuality_; }
  216. /// Return whether shadow maps are reused.
  217. bool GetReuseShadowMaps() const { return reuseShadowMaps_; }
  218. /// Return maximum number of shadow maps per resolution.
  219. int GetMaxShadowMaps() const { return maxShadowMaps_; }
  220. /// Return maximum number of directional light shadow map cascades.
  221. int GetMaxShadowCascades() const { return maxShadowCascades_; }
  222. /// Return whether dynamic instancing is in use.
  223. bool GetDynamicInstancing() const { return dynamicInstancing_; }
  224. /// Return maximum number of triangles per object for instancing.
  225. int GetMaxInstanceTriangles() { return maxInstanceTriangles_; }
  226. /// Return maximum number of occluder triangles.
  227. int GetMaxOccluderTriangles() const { return maxOccluderTriangles_; }
  228. /// Return occlusion buffer width.
  229. int GetOcclusionBufferSize() const { return occlusionBufferSize_; }
  230. /// Return occluder screen size threshold.
  231. float GetOccluderSizeThreshold() const { return occluderSizeThreshold_; }
  232. /// Return number of views rendered.
  233. unsigned GetNumViews() const { return numViews_; }
  234. /// Return number of primitives rendered.
  235. unsigned GetNumPrimitives() const { return numPrimitives_; }
  236. /// Return number of batches rendered.
  237. unsigned GetNumBatches() const { return numBatches_; }
  238. /// Return number of geometries rendered.
  239. unsigned GetNumGeometries(bool allViews = false) const;
  240. /// Return number of lights rendered.
  241. unsigned GetNumLights(bool allViews = false) const;
  242. /// Return number of shadow maps rendered.
  243. unsigned GetNumShadowMaps(bool allViews = false) const;
  244. /// Return number of occluders rendered.
  245. unsigned GetNumOccluders(bool allViews = false) const;
  246. /// Return the default zone.
  247. Zone* GetDefaultZone() const { return defaultZone_; }
  248. /// Return the default material.
  249. Material* GetDefaultMaterial() const { return defaultMaterial_; }
  250. /// Return the default range attenuation texture.
  251. Texture2D* GetDefaultLightRamp() const { return defaultLightRamp_; }
  252. /// Return the default spotlight attenuation texture.
  253. Texture2D* GetDefaultLightSpot() const { return defaultLightSpot_; }
  254. /// Return the shadowed pointlight face selection cube map.
  255. TextureCube* GetFaceSelectCubeMap() const { return faceSelectCubeMap_; }
  256. /// Return the shadowed pointlight indirection cube map.
  257. TextureCube* GetIndirectionCubeMap() const { return indirectionCubeMap_; }
  258. /// Return the instancing vertex buffer
  259. VertexBuffer* GetInstancingBuffer() const { return dynamicInstancing_ ? instancingBuffer_ : (VertexBuffer*)0; }
  260. /// Return a vertex shader by name.
  261. ShaderVariation* GetVertexShader(const String& name, bool checkExists = false) const;
  262. /// Return a pixel shader by name.
  263. ShaderVariation* GetPixelShader(const String& name, bool checkExists = false) const;
  264. /// Return the stencil vertex shader.
  265. ShaderVariation* GetStencilVS() const { return stencilVS_; }
  266. /// Return the stencil pixel shader.
  267. ShaderVariation* GetStencilPS() const { return stencilPS_; }
  268. /// Return the frame update parameters.
  269. const FrameInfo& GetFrameInfo() { return frame_; }
  270. /// Update for rendering. Called by HandleRenderUpdate().
  271. void Update(float timeStep);
  272. /// Render. Called by Engine.
  273. void Render();
  274. /// Add debug geometry to the debug renderer.
  275. void DrawDebugGeometry(bool depthTest);
  276. /// Add a view. Return true if successful.
  277. bool AddView(RenderSurface* renderTarget, Viewport* viewport);
  278. /// Return volume geometry for a light.
  279. Geometry* GetLightGeometry(Light* light);
  280. /// Allocate a shadow map. If shadow map reuse is disabled, a different map is returned each time.
  281. Texture2D* GetShadowMap(Light* light, Camera* camera, unsigned viewWidth, unsigned viewHeight);
  282. /// Allocate a rendertarget or depth-stencil texture for deferred rendering or postprocessing. Should only be called during actual rendering, not before.
  283. Texture2D* GetScreenBuffer(int width, int height, unsigned format, bool filtered = false);
  284. /// Allocate a depth-stencil surface that does not need to be readable. Should only be called during actual rendering, not before.
  285. RenderSurface* GetDepthStencil(int width, int height);
  286. /// Allocate an occlusion buffer.
  287. OcclusionBuffer* GetOcclusionBuffer(Camera* camera);
  288. /// Allocate a temporary shadow camera and a scene node for it. Is thread-safe.
  289. Camera* GetShadowCamera();
  290. /// Get a shader program.
  291. ShaderVariation* GetShader(const String& name, const String& extension, bool checkExists) const;
  292. /// Choose shaders for a forward rendering batch.
  293. void SetBatchShaders(Batch& batch, Technique* tech, bool allowShadows = true);
  294. /// Choose shaders for a light volume batch.
  295. void SetLightVolumeBatchShaders(Batch& batch);
  296. /// %Set cull mode while taking possible projection flipping into account.
  297. void SetCullMode(CullMode mode, Camera* camera);
  298. /// Ensure sufficient size of the instancing vertex buffer. Return true if successful.
  299. bool ResizeInstancingBuffer(unsigned numInstances);
  300. /// Save the screen buffer allocation status. Called by View.
  301. void SaveScreenBufferAllocations();
  302. /// Restore the screen buffer allocation status. Called by View.
  303. void RestoreScreenBufferAllocations();
  304. /// Optimize a light by scissor rectangle.
  305. void OptimizeLightByScissor(Light* light, Camera* camera);
  306. /// Optimize a light by marking it to the stencil buffer and setting a stencil test.
  307. void OptimizeLightByStencil(Light* light, Camera* camera);
  308. /// Return a scissor rectangle for a light.
  309. const Rect& GetLightScissor(Light* light, Camera* camera);
  310. private:
  311. /// Initialize when screen mode initially set.
  312. void Initialize();
  313. /// Clear views from previous frame.
  314. void ResetViews();
  315. /// Reload shaders.
  316. void LoadShaders();
  317. /// Reload shaders for a material technique.
  318. void LoadMaterialShaders(Technique* tech);
  319. /// Reload shaders for a material pass.
  320. void LoadPassShaders(Technique* tech, PassType type, bool allowShadows = true);
  321. /// Release shaders used in materials.
  322. void ReleaseMaterialShaders();
  323. /// Reload textures.
  324. void ReloadTextures();
  325. /// Create light volume geometries.
  326. void CreateGeometries();
  327. /// Create instancing vertex buffer.
  328. void CreateInstancingBuffer();
  329. /// Prepare for rendering of a new view.
  330. void PrepareViewRender();
  331. /// Remove unused occlusion and screen buffers.
  332. void RemoveUnusedBuffers();
  333. /// Reset shadow map allocation counts.
  334. void ResetShadowMapAllocations();
  335. /// Reset screem buffer allocation counts.
  336. void ResetScreenBufferAllocations();
  337. /// Remove all shadow maps. Called when global shadow map resolution or format is changed.
  338. void ResetShadowMaps();
  339. /// Remove all occlusion and screen buffers.
  340. void ResetBuffers();
  341. /// Handle screen mode event.
  342. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  343. /// Handle graphics features (re)check event.
  344. void HandleGraphicsFeatures(StringHash eventType, VariantMap& eventData);
  345. /// Handle render update event.
  346. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  347. /// Graphics subsystem.
  348. WeakPtr<Graphics> graphics_;
  349. /// Resource cache subsystem.
  350. WeakPtr<ResourceCache> cache_;
  351. /// Default zone.
  352. SharedPtr<Zone> defaultZone_;
  353. /// Directional light quad geometry.
  354. SharedPtr<Geometry> dirLightGeometry_;
  355. /// Spot light volume geometry.
  356. SharedPtr<Geometry> spotLightGeometry_;
  357. /// Point light volume geometry.
  358. SharedPtr<Geometry> pointLightGeometry_;
  359. /// Instance stream vertex buffer.
  360. SharedPtr<VertexBuffer> instancingBuffer_;
  361. /// Default material.
  362. SharedPtr<Material> defaultMaterial_;
  363. /// Default range attenuation texture.
  364. SharedPtr<Texture2D> defaultLightRamp_;
  365. /// Default spotlight attenuation texture.
  366. SharedPtr<Texture2D> defaultLightSpot_;
  367. /// Face selection cube map for shadowed pointlights.
  368. SharedPtr<TextureCube> faceSelectCubeMap_;
  369. /// Indirection cube map for shadowed pointlights.
  370. SharedPtr<TextureCube> indirectionCubeMap_;
  371. /// Stencil rendering vertex shader.
  372. SharedPtr<ShaderVariation> stencilVS_;
  373. /// Stencil rendering pixel shader.
  374. SharedPtr<ShaderVariation> stencilPS_;
  375. /// Light vertex shaders.
  376. Vector<SharedPtr<ShaderVariation> > lightVS_;
  377. /// Light pixel shaders.
  378. Vector<SharedPtr<ShaderVariation> > lightPS_;
  379. /// Reusable scene nodes with shadow camera components.
  380. Vector<SharedPtr<Node> > shadowCameraNodes_;
  381. /// Reusable occlusion buffers.
  382. Vector<SharedPtr<OcclusionBuffer> > occlusionBuffers_;
  383. /// Shadow maps by resolution.
  384. HashMap<int, Vector<SharedPtr<Texture2D> > > shadowMaps_;
  385. /// Shadow map dummy color buffers by resolution.
  386. HashMap<int, SharedPtr<Texture2D> > colorShadowMaps_;
  387. /// Shadow map allocations by resolution.
  388. HashMap<int, PODVector<Light*> > shadowMapAllocations_;
  389. /// Screen buffers by resolution and format.
  390. HashMap<long long, Vector<SharedPtr<Texture2D> > > screenBuffers_;
  391. /// Current screen buffer allocations by resolution and format.
  392. HashMap<long long, unsigned> screenBufferAllocations_;
  393. /// Saved status of screen buffer allocations for restoring.
  394. HashMap<long long, unsigned> savedScreenBufferAllocations_;
  395. /// Cache for light scissor queries.
  396. HashMap<Pair<Light*, Camera*>, Rect> lightScissorCache_;
  397. /// Viewports.
  398. Vector<SharedPtr<Viewport> > viewports_;
  399. /// Views.
  400. Vector<SharedPtr<View> > views_;
  401. /// Octrees that have been updated during the frame.
  402. HashSet<Octree*> updatedOctrees_;
  403. /// Techniques for which missing shader error has been displayed.
  404. HashSet<Technique*> shaderErrorDisplayed_;
  405. /// Mutex for shadow camera allocation.
  406. Mutex rendererMutex_;
  407. /// Vertex shader format.
  408. String vsFormat_;
  409. /// Pixel shader format.
  410. String psFormat_;
  411. /// Base directory for shaders.
  412. String shaderPath_;
  413. /// Frame info for rendering.
  414. FrameInfo frame_;
  415. /// Rendering mode.
  416. RenderMode renderMode_;
  417. /// Texture anisotropy level.
  418. int textureAnisotropy_;
  419. /// Texture filtering mode.
  420. TextureFilterMode textureFilterMode_;
  421. /// Texture quality level.
  422. int textureQuality_;
  423. /// Material quality level.
  424. int materialQuality_;
  425. /// Shadow map resolution.
  426. int shadowMapSize_;
  427. /// Shadow quality.
  428. int shadowQuality_;
  429. /// Maximum number of shadow maps per resolution.
  430. int maxShadowMaps_;
  431. /// Maximum number of directional light shadow cascades.
  432. int maxShadowCascades_;
  433. /// Maximum triangles per object for instancing.
  434. int maxInstanceTriangles_;
  435. /// Maximum occluder triangles.
  436. int maxOccluderTriangles_;
  437. /// Occlusion buffer width.
  438. int occlusionBufferSize_;
  439. /// Occluder screen size threshold.
  440. float occluderSizeThreshold_;
  441. /// Number of views.
  442. unsigned numViews_;
  443. /// Number of occlusion buffers in use.
  444. unsigned numOcclusionBuffers_;
  445. /// Number of temporary shadow cameras in use.
  446. unsigned numShadowCameras_;
  447. /// Number of primitives (3D geometry only.)
  448. unsigned numPrimitives_;
  449. /// Number of batches (3D geometry only.)
  450. unsigned numBatches_;
  451. /// Frame number on which shaders last changed.
  452. unsigned shadersChangedFrameNumber_;
  453. /// Current stencil value for light optimization.
  454. unsigned char lightStencilValue_;
  455. /// Specular lighting flag.
  456. bool specularLighting_;
  457. /// Draw shadows flag.
  458. bool drawShadows_;
  459. /// Shadow map reuse flag.
  460. bool reuseShadowMaps_;
  461. /// Dynamic instancing flag.
  462. bool dynamicInstancing_;
  463. /// Shaders need reloading flag.
  464. bool shadersDirty_;
  465. /// Initialized flag.
  466. bool initialized_;
  467. };