View.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 "../Graphics/Batch.h"
  24. #include "../Container/HashSet.h"
  25. #include "../Graphics/Light.h"
  26. #include "../Container/List.h"
  27. #include "../Core/Object.h"
  28. #include "../Math/Polyhedron.h"
  29. #include "../Graphics/Zone.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 Texture2D;
  44. class Viewport;
  45. class Zone;
  46. struct RenderPathCommand;
  47. struct WorkItem;
  48. /// Intermediate light processing result.
  49. struct LightQueryResult
  50. {
  51. /// Light.
  52. Light* light_;
  53. /// Lit geometries.
  54. PODVector<Drawable*> litGeometries_;
  55. /// Shadow casters.
  56. PODVector<Drawable*> shadowCasters_;
  57. /// Shadow cameras.
  58. Camera* shadowCameras_[MAX_LIGHT_SPLITS];
  59. /// Shadow caster start indices.
  60. unsigned shadowCasterBegin_[MAX_LIGHT_SPLITS];
  61. /// Shadow caster end indices.
  62. unsigned shadowCasterEnd_[MAX_LIGHT_SPLITS];
  63. /// Combined bounding box of shadow casters in light view or projection space.
  64. BoundingBox shadowCasterBox_[MAX_LIGHT_SPLITS];
  65. /// Shadow camera near splits (directional lights only.)
  66. float shadowNearSplits_[MAX_LIGHT_SPLITS];
  67. /// Shadow camera far splits (directional lights only.)
  68. float shadowFarSplits_[MAX_LIGHT_SPLITS];
  69. /// Shadow map split count.
  70. unsigned numSplits_;
  71. };
  72. /// Scene render pass info.
  73. struct ScenePassInfo
  74. {
  75. /// Pass name hash.
  76. StringHash pass_;
  77. /// Allow instancing flag.
  78. bool allowInstancing_;
  79. /// Mark to stencil flag.
  80. bool markToStencil_;
  81. /// Light scissor optimization flag.
  82. bool useScissor_;
  83. /// Vertex light flag.
  84. bool vertexLights_;
  85. /// Batch queue.
  86. BatchQueue* batchQueue_;
  87. };
  88. /// Per-thread geometry, light and scene range collection structure.
  89. struct PerThreadSceneResult
  90. {
  91. /// Geometry objects.
  92. PODVector<Drawable*> geometries_;
  93. /// Lights.
  94. PODVector<Light*> lights_;
  95. /// Scene minimum Z value.
  96. float minZ_;
  97. /// Scene maximum Z value.
  98. float maxZ_;
  99. };
  100. static const unsigned MAX_VIEWPORT_TEXTURES = 2;
  101. /// Internal structure for 3D rendering work. Created for each backbuffer and texture viewport, but not for shadow cameras.
  102. class ATOMIC_API View : public Object
  103. {
  104. friend void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex);
  105. friend void ProcessLightWork(const WorkItem* item, unsigned threadIndex);
  106. OBJECT(View);
  107. public:
  108. /// Construct.
  109. View(Context* context);
  110. /// Destruct.
  111. virtual ~View();
  112. /// Define with rendertarget and viewport. Return true if successful.
  113. bool Define(RenderSurface* renderTarget, Viewport* viewport);
  114. /// Update and cull objects and construct rendering batches.
  115. void Update(const FrameInfo& frame);
  116. /// Render batches.
  117. void Render();
  118. /// Return graphics subsystem.
  119. Graphics* GetGraphics() const;
  120. /// Return renderer subsystem.
  121. Renderer* GetRenderer() const;
  122. /// Return scene.
  123. Scene* GetScene() const { return scene_; }
  124. /// Return octree.
  125. Octree* GetOctree() const { return octree_; }
  126. /// Return camera.
  127. Camera* GetCamera() const { return camera_; }
  128. /// Return information of the frame being rendered.
  129. const FrameInfo& GetFrameInfo() const { return frame_; }
  130. /// Return the rendertarget. 0 if using the backbuffer.
  131. RenderSurface* GetRenderTarget() const { return renderTarget_; }
  132. /// Return whether should draw debug geometry.
  133. bool GetDrawDebug() const { return drawDebug_; }
  134. /// Return geometry objects.
  135. const PODVector<Drawable*>& GetGeometries() const { return geometries_; }
  136. /// Return occluder objects.
  137. const PODVector<Drawable*>& GetOccluders() const { return occluders_; }
  138. /// Return lights.
  139. const PODVector<Light*>& GetLights() const { return lights_; }
  140. /// Return light batch queues.
  141. const Vector<LightBatchQueue>& GetLightQueues() const { return lightQueues_; }
  142. /// Set global (per-frame) shader parameters. Called by Batch and internally by View.
  143. void SetGlobalShaderParameters();
  144. /// Set camera-specific shader parameters. Called by Batch and internally by View.
  145. void SetCameraShaderParameters(Camera* camera, bool setProjectionMatrix);
  146. /// Set G-buffer offset and inverse size shader parameters. Called by Batch and internally by View.
  147. void SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect);
  148. private:
  149. /// Query the octree for drawable objects.
  150. void GetDrawables();
  151. /// Construct batches from the drawable objects.
  152. void GetBatches();
  153. /// Update geometries and sort batches.
  154. void UpdateGeometries();
  155. /// Get pixel lit batches for a certain light and drawable.
  156. void GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue);
  157. /// Execute render commands.
  158. void ExecuteRenderPathCommands();
  159. /// Set rendertargets for current render command.
  160. void SetRenderTargets(RenderPathCommand& command);
  161. /// Set textures for current render command. Return whether depth write is allowed (depth-stencil not bound as a texture.)
  162. bool SetTextures(RenderPathCommand& command);
  163. /// Perform a quad rendering command.
  164. void RenderQuad(RenderPathCommand& command);
  165. /// Check if a command is enabled and has content to render. To be called only after render update has completed for the frame.
  166. bool IsNecessary(const RenderPathCommand& command);
  167. /// Check if a command reads the destination render target.
  168. bool CheckViewportRead(const RenderPathCommand& command);
  169. /// Check if a command writes into the destination render target.
  170. bool CheckViewportWrite(const RenderPathCommand& command);
  171. /// Check whether a command should use pingponging instead of resolve from destination render target to viewport texture.
  172. bool CheckPingpong(unsigned index);
  173. /// Allocate needed screen buffers.
  174. void AllocateScreenBuffers();
  175. /// Blit the viewport from one surface to another.
  176. void BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite);
  177. /// Draw a fullscreen quad. Shaders and renderstates must have been set beforehand.
  178. void DrawFullscreenQuad(bool nearQuad);
  179. /// Query for occluders as seen from a camera.
  180. void UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera);
  181. /// Draw occluders to occlusion buffer.
  182. void DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders);
  183. /// Query for lit geometries and shadow casters for a light.
  184. void ProcessLight(LightQueryResult& query, unsigned threadIndex);
  185. /// Process shadow casters' visibilities and build their combined view- or projection-space bounding box.
  186. void ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex);
  187. /// Set up initial shadow camera view(s).
  188. void SetupShadowCameras(LightQueryResult& query);
  189. /// Set up a directional light shadow camera
  190. void SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit);
  191. /// Finalize shadow camera view after shadow casters and the shadow map are known.
  192. void FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& shadowCasterBox);
  193. /// Quantize a directional light shadow camera view to eliminate swimming.
  194. void QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& viewBox);
  195. /// Check visibility of one shadow caster.
  196. bool IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView, const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox);
  197. /// Return the viewport for a shadow map split.
  198. IntRect GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap);
  199. /// Find and set a new zone for a drawable when it has moved.
  200. void FindZone(Drawable* drawable);
  201. /// Return material technique, considering the drawable's LOD distance.
  202. Technique* GetTechnique(Drawable* drawable, Material* material);
  203. /// Check if material should render an auxiliary view (if it has a camera attached.)
  204. void CheckMaterialForAuxView(Material* material);
  205. /// Choose shaders for a batch and add it to queue.
  206. void AddBatchToQueue(BatchQueue& queue, Batch& batch, Technique* tech, bool allowInstancing = true, bool allowShadows = true);
  207. /// Prepare instancing buffer by filling it with all instance transforms.
  208. void PrepareInstancingBuffer();
  209. /// Set up a light volume rendering batch.
  210. void SetupLightVolumeBatch(Batch& batch);
  211. /// Render a shadow map.
  212. void RenderShadowMap(const LightBatchQueue& queue);
  213. /// Return the proper depth-stencil surface to use for a rendertarget.
  214. RenderSurface* GetDepthStencil(RenderSurface* renderTarget);
  215. /// Return the drawable's zone, or camera zone if it has override mode enabled.
  216. Zone* GetZone(Drawable* drawable)
  217. {
  218. if (cameraZoneOverride_)
  219. return cameraZone_;
  220. Zone* drawableZone = drawable->GetZone();
  221. return drawableZone ? drawableZone : cameraZone_;
  222. }
  223. /// Return the drawable's light mask, considering also its zone.
  224. unsigned GetLightMask(Drawable* drawable)
  225. {
  226. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  227. }
  228. /// Return the drawable's shadow mask, considering also its zone.
  229. unsigned GetShadowMask(Drawable* drawable)
  230. {
  231. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  232. }
  233. /// Return hash code for a vertex light queue.
  234. unsigned long long GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  235. {
  236. unsigned long long hash = 0;
  237. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  238. hash += (unsigned long long)(*i);
  239. return hash;
  240. }
  241. /// Graphics subsystem.
  242. WeakPtr<Graphics> graphics_;
  243. /// Renderer subsystem.
  244. WeakPtr<Renderer> renderer_;
  245. /// Scene to use.
  246. Scene* scene_;
  247. /// Octree to use.
  248. Octree* octree_;
  249. /// Camera to use.
  250. Camera* camera_;
  251. /// Camera's scene node.
  252. Node* cameraNode_;
  253. /// Zone the camera is inside, or default zone if not assigned.
  254. Zone* cameraZone_;
  255. /// Zone at far clip plane.
  256. Zone* farClipZone_;
  257. /// Occlusion buffer for the main camera.
  258. OcclusionBuffer* occlusionBuffer_;
  259. /// Destination color rendertarget.
  260. RenderSurface* renderTarget_;
  261. /// Substitute rendertarget for deferred rendering. Allocated if necessary.
  262. RenderSurface* substituteRenderTarget_;
  263. /// Texture(s) for sampling the viewport contents. Allocated if necessary.
  264. Texture2D* viewportTextures_[MAX_VIEWPORT_TEXTURES];
  265. /// Color rendertarget active for the current renderpath command.
  266. RenderSurface* currentRenderTarget_;
  267. /// Texture containing the latest viewport texture.
  268. Texture2D* currentViewportTexture_;
  269. /// Dummy texture for D3D9 depth only rendering.
  270. Texture2D* depthOnlyDummyTexture_;
  271. /// Viewport rectangle.
  272. IntRect viewRect_;
  273. /// Viewport size.
  274. IntVector2 viewSize_;
  275. /// Destination rendertarget size.
  276. IntVector2 rtSize_;
  277. /// Information of the frame being rendered.
  278. FrameInfo frame_;
  279. /// Minimum Z value of the visible scene.
  280. float minZ_;
  281. /// Maximum Z value of the visible scene.
  282. float maxZ_;
  283. /// Material quality level.
  284. int materialQuality_;
  285. /// Maximum number of occluder triangles.
  286. int maxOccluderTriangles_;
  287. /// Minimum number of instances required in a batch group to render as instanced.
  288. int minInstances_;
  289. /// Highest zone priority currently visible.
  290. int highestZonePriority_;
  291. /// Camera zone's override flag.
  292. bool cameraZoneOverride_;
  293. /// Draw shadows flag.
  294. bool drawShadows_;
  295. /// Deferred flag. Inferred from the existence of a light volume command in the renderpath.
  296. bool deferred_;
  297. /// 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.
  298. bool deferredAmbient_;
  299. /// Forward light base pass optimization flag. If in use, combine the base pass and first light for all opaque objects.
  300. bool useLitBase_;
  301. /// Has scene passes flag. If no scene passes, view can be defined without a valid scene or camera to only perform quad rendering.
  302. bool hasScenePasses_;
  303. /// Whether is using a custom readable depth texture without a stencil channel.
  304. bool noStencil_;
  305. /// Draw debug geometry flag. Copied from the viewport.
  306. bool drawDebug_;
  307. /// Renderpath.
  308. RenderPath* renderPath_;
  309. /// Per-thread octree query results.
  310. Vector<PODVector<Drawable*> > tempDrawables_;
  311. /// Per-thread geometries, lights and Z range collection results.
  312. Vector<PerThreadSceneResult> sceneResults_;
  313. /// Visible zones.
  314. PODVector<Zone*> zones_;
  315. /// Visible geometry objects.
  316. PODVector<Drawable*> geometries_;
  317. /// Geometry objects that will be updated in the main thread.
  318. PODVector<Drawable*> nonThreadedGeometries_;
  319. /// Geometry objects that will be updated in worker threads.
  320. PODVector<Drawable*> threadedGeometries_;
  321. /// Occluder objects.
  322. PODVector<Drawable*> occluders_;
  323. /// Lights.
  324. PODVector<Light*> lights_;
  325. /// Drawables that limit their maximum light count.
  326. HashSet<Drawable*> maxLightsDrawables_;
  327. /// Rendertargets defined by the renderpath.
  328. HashMap<StringHash, Texture2D*> renderTargets_;
  329. /// Intermediate light processing results.
  330. Vector<LightQueryResult> lightQueryResults_;
  331. /// Info for scene render passes defined by the renderpath.
  332. Vector<ScenePassInfo> scenePasses_;
  333. /// Per-pixel light queues.
  334. Vector<LightBatchQueue> lightQueues_;
  335. /// Per-vertex light queues.
  336. HashMap<unsigned long long, LightBatchQueue> vertexLightQueues_;
  337. /// Batch queues.
  338. HashMap<StringHash, BatchQueue> batchQueues_;
  339. /// Hash of the GBuffer pass, or null if none.
  340. StringHash gBufferPassName_;
  341. /// Hash of the opaque forward base pass.
  342. StringHash basePassName_;
  343. /// Hash of the alpha pass.
  344. StringHash alphaPassName_;
  345. /// Hash of the forward light pass.
  346. StringHash lightPassName_;
  347. /// Hash of the litbase pass.
  348. StringHash litBasePassName_;
  349. /// Hash of the litalpha pass.
  350. StringHash litAlphaPassName_;
  351. /// Pointer to the light volume command if any.
  352. const RenderPathCommand* lightVolumeCommand_;
  353. };
  354. }