View.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashSet.h"
  24. #include "../Container/List.h"
  25. #include "../Core/Object.h"
  26. #include "../Graphics/Batch.h"
  27. #include "../Graphics/Light.h"
  28. #include "../Graphics/Zone.h"
  29. #include "../Math/Polyhedron.h"
  30. namespace Atomic
  31. {
  32. class Camera;
  33. class DebugRenderer;
  34. class Light;
  35. class Drawable;
  36. class Graphics;
  37. class OcclusionBuffer;
  38. class Octree;
  39. class Renderer;
  40. class RenderPath;
  41. class RenderSurface;
  42. class Technique;
  43. class Texture;
  44. class Texture2D;
  45. class Viewport;
  46. class Zone;
  47. struct RenderPathCommand;
  48. struct WorkItem;
  49. /// Intermediate light processing result.
  50. struct LightQueryResult
  51. {
  52. /// Light.
  53. Light* light_;
  54. /// Lit geometries.
  55. PODVector<Drawable*> litGeometries_;
  56. /// Shadow casters.
  57. PODVector<Drawable*> shadowCasters_;
  58. /// Shadow cameras.
  59. Camera* shadowCameras_[MAX_LIGHT_SPLITS];
  60. /// Shadow caster start indices.
  61. unsigned shadowCasterBegin_[MAX_LIGHT_SPLITS];
  62. /// Shadow caster end indices.
  63. unsigned shadowCasterEnd_[MAX_LIGHT_SPLITS];
  64. /// Combined bounding box of shadow casters in light projection space. Only used for focused spot lights.
  65. BoundingBox shadowCasterBox_[MAX_LIGHT_SPLITS];
  66. /// Shadow camera near splits (directional lights only.)
  67. float shadowNearSplits_[MAX_LIGHT_SPLITS];
  68. /// Shadow camera far splits (directional lights only.)
  69. float shadowFarSplits_[MAX_LIGHT_SPLITS];
  70. /// Shadow map split count.
  71. unsigned numSplits_;
  72. };
  73. /// Scene render pass info.
  74. struct ScenePassInfo
  75. {
  76. /// Pass index.
  77. unsigned passIndex_;
  78. /// Allow instancing flag.
  79. bool allowInstancing_;
  80. /// Mark to stencil flag.
  81. bool markToStencil_;
  82. /// Vertex light flag.
  83. bool vertexLights_;
  84. /// Batch queue.
  85. BatchQueue* batchQueue_;
  86. };
  87. /// Per-thread geometry, light and scene range collection structure.
  88. struct PerThreadSceneResult
  89. {
  90. /// Geometry objects.
  91. PODVector<Drawable*> geometries_;
  92. /// Lights.
  93. PODVector<Light*> lights_;
  94. /// Scene minimum Z value.
  95. float minZ_;
  96. /// Scene maximum Z value.
  97. float maxZ_;
  98. };
  99. static const unsigned MAX_VIEWPORT_TEXTURES = 2;
  100. /// Internal structure for 3D rendering work. Created for each backbuffer and texture viewport, but not for shadow cameras.
  101. class ATOMIC_API View : public Object
  102. {
  103. friend void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex);
  104. friend void ProcessLightWork(const WorkItem* item, unsigned threadIndex);
  105. OBJECT(View);
  106. public:
  107. /// Construct.
  108. View(Context* context);
  109. /// Destruct.
  110. virtual ~View();
  111. /// Define with rendertarget and viewport. Return true if successful.
  112. bool Define(RenderSurface* renderTarget, Viewport* viewport);
  113. /// Update and cull objects and construct rendering batches.
  114. void Update(const FrameInfo& frame);
  115. /// Render batches.
  116. void Render();
  117. /// Return graphics subsystem.
  118. Graphics* GetGraphics() const;
  119. /// Return renderer subsystem.
  120. Renderer* GetRenderer() const;
  121. /// Return scene.
  122. Scene* GetScene() const { return scene_; }
  123. /// Return octree.
  124. Octree* GetOctree() const { return octree_; }
  125. /// Return camera.
  126. Camera* GetCamera() const { return camera_; }
  127. /// Return information of the frame being rendered.
  128. const FrameInfo& GetFrameInfo() const { return frame_; }
  129. /// Return the rendertarget. 0 if using the backbuffer.
  130. RenderSurface* GetRenderTarget() const { return renderTarget_; }
  131. /// Return whether should draw debug geometry.
  132. bool GetDrawDebug() const { return drawDebug_; }
  133. /// Return geometry objects.
  134. const PODVector<Drawable*>& GetGeometries() const { return geometries_; }
  135. /// Return occluder objects.
  136. const PODVector<Drawable*>& GetOccluders() const { return occluders_; }
  137. /// Return lights.
  138. const PODVector<Light*>& GetLights() const { return lights_; }
  139. /// Return light batch queues.
  140. const Vector<LightBatchQueue>& GetLightQueues() const { return lightQueues_; }
  141. /// Return the last used software occlusion buffer.
  142. OcclusionBuffer* GetOcclusionBuffer() const { return occlusionBuffer_; }
  143. /// Set global (per-frame) shader parameters. Called by Batch and internally by View.
  144. void SetGlobalShaderParameters();
  145. /// Set camera-specific shader parameters. Called by Batch and internally by View.
  146. void SetCameraShaderParameters(Camera* camera, bool setProjectionMatrix);
  147. /// Set G-buffer offset and inverse size shader parameters. Called by Batch and internally by View.
  148. void SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect);
  149. private:
  150. /// Query the octree for drawable objects.
  151. void GetDrawables();
  152. /// Construct batches from the drawable objects.
  153. void GetBatches();
  154. /// Get lit geometries and shadowcasters for visible lights.
  155. void ProcessLights();
  156. /// Get batches from lit geometries and shadowcasters.
  157. void GetLightBatches();
  158. /// Get unlit batches.
  159. void GetBaseBatches();
  160. /// Update geometries and sort batches.
  161. void UpdateGeometries();
  162. /// Get pixel lit batches for a certain light and drawable.
  163. void GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue);
  164. /// Execute render commands.
  165. void ExecuteRenderPathCommands();
  166. /// Set rendertargets for current render command.
  167. void SetRenderTargets(RenderPathCommand& command);
  168. /// Set textures for current render command. Return whether depth write is allowed (depth-stencil not bound as a texture.)
  169. bool SetTextures(RenderPathCommand& command);
  170. /// Perform a quad rendering command.
  171. void RenderQuad(RenderPathCommand& command);
  172. /// Check if a command is enabled and has content to render. To be called only after render update has completed for the frame.
  173. bool IsNecessary(const RenderPathCommand& command);
  174. /// Check if a command reads the destination render target.
  175. bool CheckViewportRead(const RenderPathCommand& command);
  176. /// Check if a command writes into the destination render target.
  177. bool CheckViewportWrite(const RenderPathCommand& command);
  178. /// Check whether a command should use pingponging instead of resolve from destination render target to viewport texture.
  179. bool CheckPingpong(unsigned index);
  180. /// Allocate needed screen buffers.
  181. void AllocateScreenBuffers();
  182. /// Blit the viewport from one surface to another.
  183. void BlitFramebuffer(Texture* source, RenderSurface* destination, bool depthWrite);
  184. /// Draw a fullscreen quad. Shaders and renderstates must have been set beforehand.
  185. void DrawFullscreenQuad(bool nearQuad);
  186. /// Query for occluders as seen from a camera.
  187. void UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera);
  188. /// Draw occluders to occlusion buffer.
  189. void DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders);
  190. /// Query for lit geometries and shadow casters for a light.
  191. void ProcessLight(LightQueryResult& query, unsigned threadIndex);
  192. /// Process shadow casters' visibilities and build their combined view- or projection-space bounding box.
  193. void ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex);
  194. /// Set up initial shadow camera view(s).
  195. void SetupShadowCameras(LightQueryResult& query);
  196. /// Set up a directional light shadow camera
  197. void SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit);
  198. /// Finalize shadow camera view after shadow casters and the shadow map are known.
  199. void
  200. FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& shadowCasterBox);
  201. /// Quantize a directional light shadow camera view to eliminate swimming.
  202. void
  203. QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& viewBox);
  204. /// Check visibility of one shadow caster.
  205. bool IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  206. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox);
  207. /// Return the viewport for a shadow map split.
  208. IntRect GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap);
  209. /// Find and set a new zone for a drawable when it has moved.
  210. void FindZone(Drawable* drawable);
  211. /// Return material technique, considering the drawable's LOD distance.
  212. Technique* GetTechnique(Drawable* drawable, Material* material);
  213. /// Check if material should render an auxiliary view (if it has a camera attached.)
  214. void CheckMaterialForAuxView(Material* material);
  215. /// Choose shaders for a batch and add it to queue.
  216. void AddBatchToQueue(BatchQueue& queue, Batch& batch, Technique* tech, bool allowInstancing = true, bool allowShadows = true);
  217. /// Prepare instancing buffer by filling it with all instance transforms.
  218. void PrepareInstancingBuffer();
  219. /// Set up a light volume rendering batch.
  220. void SetupLightVolumeBatch(Batch& batch);
  221. /// Render a shadow map.
  222. void RenderShadowMap(const LightBatchQueue& queue);
  223. /// Return the proper depth-stencil surface to use for a rendertarget.
  224. RenderSurface* GetDepthStencil(RenderSurface* renderTarget);
  225. /// Helper function to get the render surface from a texture. 2D textures will always return the first face only.
  226. RenderSurface* GetRenderSurfaceFromTexture(Texture* texture, CubeMapFace face = FACE_POSITIVE_X);
  227. /// Get a named texture from the rendertarget list or from the resource cache, to be either used as a rendertarget or texture binding.
  228. Texture* FindNamedTexture(const String& name, bool isRenderTarget, bool isVolumeMap = false);
  229. /// Return the drawable's zone, or camera zone if it has override mode enabled.
  230. Zone* GetZone(Drawable* drawable)
  231. {
  232. if (cameraZoneOverride_)
  233. return cameraZone_;
  234. Zone* drawableZone = drawable->GetZone();
  235. return drawableZone ? drawableZone : cameraZone_;
  236. }
  237. /// Return the drawable's light mask, considering also its zone.
  238. unsigned GetLightMask(Drawable* drawable)
  239. {
  240. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  241. }
  242. /// Return the drawable's shadow mask, considering also its zone.
  243. unsigned GetShadowMask(Drawable* drawable)
  244. {
  245. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  246. }
  247. /// Return hash code for a vertex light queue.
  248. unsigned long long GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  249. {
  250. unsigned long long hash = 0;
  251. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  252. hash += (unsigned long long)(*i);
  253. return hash;
  254. }
  255. /// Graphics subsystem.
  256. WeakPtr<Graphics> graphics_;
  257. /// Renderer subsystem.
  258. WeakPtr<Renderer> renderer_;
  259. /// Scene to use.
  260. Scene* scene_;
  261. /// Octree to use.
  262. Octree* octree_;
  263. /// Camera to use.
  264. Camera* camera_;
  265. /// Camera's scene node.
  266. Node* cameraNode_;
  267. /// Zone the camera is inside, or default zone if not assigned.
  268. Zone* cameraZone_;
  269. /// Zone at far clip plane.
  270. Zone* farClipZone_;
  271. /// Occlusion buffer for the main camera.
  272. OcclusionBuffer* occlusionBuffer_;
  273. /// Destination color rendertarget.
  274. RenderSurface* renderTarget_;
  275. /// Substitute rendertarget for deferred rendering. Allocated if necessary.
  276. RenderSurface* substituteRenderTarget_;
  277. /// Texture(s) for sampling the viewport contents. Allocated if necessary.
  278. Texture* viewportTextures_[MAX_VIEWPORT_TEXTURES];
  279. /// Color rendertarget active for the current renderpath command.
  280. RenderSurface* currentRenderTarget_;
  281. /// Texture containing the latest viewport texture.
  282. Texture* currentViewportTexture_;
  283. /// Dummy texture for D3D9 depth only rendering.
  284. Texture* depthOnlyDummyTexture_;
  285. /// Viewport rectangle.
  286. IntRect viewRect_;
  287. /// Viewport size.
  288. IntVector2 viewSize_;
  289. /// Destination rendertarget size.
  290. IntVector2 rtSize_;
  291. /// Information of the frame being rendered.
  292. FrameInfo frame_;
  293. /// Minimum Z value of the visible scene.
  294. float minZ_;
  295. /// Maximum Z value of the visible scene.
  296. float maxZ_;
  297. /// Material quality level.
  298. int materialQuality_;
  299. /// Maximum number of occluder triangles.
  300. int maxOccluderTriangles_;
  301. /// Minimum number of instances required in a batch group to render as instanced.
  302. int minInstances_;
  303. /// Highest zone priority currently visible.
  304. int highestZonePriority_;
  305. /// Camera zone's override flag.
  306. bool cameraZoneOverride_;
  307. /// Draw shadows flag.
  308. bool drawShadows_;
  309. /// Deferred flag. Inferred from the existence of a light volume command in the renderpath.
  310. bool deferred_;
  311. /// Deferred ambient pass flag. This means that the destination rendertarget is being written to at the same time as albedo/normal/depth buffers, and needs to be RGBA on OpenGL.
  312. bool deferredAmbient_;
  313. /// Forward light base pass optimization flag. If in use, combine the base pass and first light for all opaque objects.
  314. bool useLitBase_;
  315. /// Has scene passes flag. If no scene passes, view can be defined without a valid scene or camera to only perform quad rendering.
  316. bool hasScenePasses_;
  317. /// Whether is using a custom readable depth texture without a stencil channel.
  318. bool noStencil_;
  319. /// Draw debug geometry flag. Copied from the viewport.
  320. bool drawDebug_;
  321. /// Renderpath.
  322. RenderPath* renderPath_;
  323. /// Per-thread octree query results.
  324. Vector<PODVector<Drawable*> > tempDrawables_;
  325. /// Per-thread geometries, lights and Z range collection results.
  326. Vector<PerThreadSceneResult> sceneResults_;
  327. /// Visible zones.
  328. PODVector<Zone*> zones_;
  329. /// Visible geometry objects.
  330. PODVector<Drawable*> geometries_;
  331. /// Geometry objects that will be updated in the main thread.
  332. PODVector<Drawable*> nonThreadedGeometries_;
  333. /// Geometry objects that will be updated in worker threads.
  334. PODVector<Drawable*> threadedGeometries_;
  335. /// Occluder objects.
  336. PODVector<Drawable*> occluders_;
  337. /// Lights.
  338. PODVector<Light*> lights_;
  339. /// Drawables that limit their maximum light count.
  340. HashSet<Drawable*> maxLightsDrawables_;
  341. /// Rendertargets defined by the renderpath.
  342. HashMap<StringHash, Texture*> renderTargets_;
  343. /// Intermediate light processing results.
  344. Vector<LightQueryResult> lightQueryResults_;
  345. /// Info for scene render passes defined by the renderpath.
  346. PODVector<ScenePassInfo> scenePasses_;
  347. /// Per-pixel light queues.
  348. Vector<LightBatchQueue> lightQueues_;
  349. /// Per-vertex light queues.
  350. HashMap<unsigned long long, LightBatchQueue> vertexLightQueues_;
  351. /// Batch queues by pass index.
  352. HashMap<unsigned, BatchQueue> batchQueues_;
  353. /// Index of the GBuffer pass.
  354. unsigned gBufferPassIndex_;
  355. /// Index of the opaque forward base pass.
  356. unsigned basePassIndex_;
  357. /// Index of the alpha pass.
  358. unsigned alphaPassIndex_;
  359. /// Index of the forward light pass.
  360. unsigned lightPassIndex_;
  361. /// Index of the litbase pass.
  362. unsigned litBasePassIndex_;
  363. /// Index of the litalpha pass.
  364. unsigned litAlphaPassIndex_;
  365. /// Pointer to the light volume command if any.
  366. const RenderPathCommand* lightVolumeCommand_;
  367. /// Flag for scene being resolved from the backbuffer.
  368. bool usedResolve_;
  369. };
  370. }