View.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //
  2. // Copyright (c) 2008-2017 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. ATOMIC_OBJECT(View, Object);
  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 viewport camera.
  126. Camera* GetCamera() const { return camera_; }
  127. /// Return culling camera. Normally same as the viewport camera.
  128. Camera* GetCullCamera() const { return cullCamera_; }
  129. /// Return information of the frame being rendered.
  130. const FrameInfo& GetFrameInfo() const { return frame_; }
  131. /// Return the rendertarget. 0 if using the backbuffer.
  132. RenderSurface* GetRenderTarget() const { return renderTarget_; }
  133. /// Return whether should draw debug geometry.
  134. bool GetDrawDebug() const { return drawDebug_; }
  135. /// Return view rectangle.
  136. const IntRect& GetViewRect() const { return viewRect_; }
  137. /// Return view dimensions.
  138. const IntVector2& GetViewSize() const { return viewSize_; }
  139. /// Return geometry objects.
  140. const PODVector<Drawable*>& GetGeometries() const { return geometries_; }
  141. /// Return occluder objects.
  142. const PODVector<Drawable*>& GetOccluders() const { return occluders_; }
  143. /// Return lights.
  144. const PODVector<Light*>& GetLights() const { return lights_; }
  145. /// Return light batch queues.
  146. const Vector<LightBatchQueue>& GetLightQueues() const { return lightQueues_; }
  147. /// Return the last used software occlusion buffer.
  148. OcclusionBuffer* GetOcclusionBuffer() const { return occlusionBuffer_; }
  149. /// Return number of occluders that were actually rendered. Occluders may be rejected if running out of triangles or if behind other occluders.
  150. unsigned GetNumActiveOccluders() const { return activeOccluders_; }
  151. /// Return the source view that was already prepared. Used when viewports specify the same culling camera.
  152. View* GetSourceView() const;
  153. /// Set global (per-frame) shader parameters. Called by Batch and internally by View.
  154. void SetGlobalShaderParameters();
  155. /// Set camera-specific shader parameters. Called by Batch and internally by View.
  156. void SetCameraShaderParameters(Camera* camera);
  157. /// Set command's shader parameters if any. Called internally by View.
  158. void SetCommandShaderParameters(const RenderPathCommand& command);
  159. /// Set G-buffer offset and inverse size shader parameters. Called by Batch and internally by View.
  160. void SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect);
  161. /// Draw a fullscreen quad. Shaders and renderstates must have been set beforehand. Quad will be drawn to the middle of depth range, similarly to deferred directional lights.
  162. void DrawFullscreenQuad(bool setIdentityProjection = false);
  163. /// Get a named texture from the rendertarget list or from the resource cache, to be either used as a rendertarget or texture binding.
  164. Texture* FindNamedTexture(const String& name, bool isRenderTarget, bool isVolumeMap = false);
  165. private:
  166. /// Query the octree for drawable objects.
  167. void GetDrawables();
  168. /// Construct batches from the drawable objects.
  169. void GetBatches();
  170. /// Get lit geometries and shadowcasters for visible lights.
  171. void ProcessLights();
  172. /// Get batches from lit geometries and shadowcasters.
  173. void GetLightBatches();
  174. /// Get unlit batches.
  175. void GetBaseBatches();
  176. /// Update geometries and sort batches.
  177. void UpdateGeometries();
  178. /// Get pixel lit batches for a certain light and drawable.
  179. void GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue);
  180. /// Execute render commands.
  181. void ExecuteRenderPathCommands();
  182. /// Set rendertargets for current render command.
  183. void SetRenderTargets(RenderPathCommand& command);
  184. /// Set textures for current render command. Return whether depth write is allowed (depth-stencil not bound as a texture.)
  185. bool SetTextures(RenderPathCommand& command);
  186. /// Perform a quad rendering command.
  187. void RenderQuad(RenderPathCommand& command);
  188. /// Check if a command is enabled and has content to render. To be called only after render update has completed for the frame.
  189. bool IsNecessary(const RenderPathCommand& command);
  190. /// Check if a command reads the destination render target.
  191. bool CheckViewportRead(const RenderPathCommand& command);
  192. /// Check if a command writes into the destination render target.
  193. bool CheckViewportWrite(const RenderPathCommand& command);
  194. /// Check whether a command should use pingponging instead of resolve from destination render target to viewport texture.
  195. bool CheckPingpong(unsigned index);
  196. /// Allocate needed screen buffers.
  197. void AllocateScreenBuffers();
  198. /// Blit the viewport from one surface to another.
  199. void BlitFramebuffer(Texture* source, RenderSurface* destination, bool depthWrite);
  200. /// Query for occluders as seen from a camera.
  201. void UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera);
  202. /// Draw occluders to occlusion buffer.
  203. void DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders);
  204. /// Query for lit geometries and shadow casters for a light.
  205. void ProcessLight(LightQueryResult& query, unsigned threadIndex);
  206. /// Process shadow casters' visibilities and build their combined view- or projection-space bounding box.
  207. void ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex);
  208. /// Set up initial shadow camera view(s).
  209. void SetupShadowCameras(LightQueryResult& query);
  210. /// Set up a directional light shadow camera
  211. void SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit);
  212. /// Finalize shadow camera view after shadow casters and the shadow map are known.
  213. void
  214. FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& shadowCasterBox);
  215. /// Quantize a directional light shadow camera view to eliminate swimming.
  216. void
  217. QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& viewBox);
  218. /// Check visibility of one shadow caster.
  219. bool IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  220. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox);
  221. /// Return the viewport for a shadow map split.
  222. IntRect GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap);
  223. /// Find and set a new zone for a drawable when it has moved.
  224. void FindZone(Drawable* drawable);
  225. /// Return material technique, considering the drawable's LOD distance.
  226. Technique* GetTechnique(Drawable* drawable, Material* material);
  227. /// Check if material should render an auxiliary view (if it has a camera attached.)
  228. void CheckMaterialForAuxView(Material* material);
  229. /// Set shader defines for a batch queue if used.
  230. void SetQueueShaderDefines(BatchQueue& queue, const RenderPathCommand& command);
  231. /// Choose shaders for a batch and add it to queue.
  232. void AddBatchToQueue(BatchQueue& queue, Batch& batch, Technique* tech, bool allowInstancing = true, bool allowShadows = true);
  233. /// Prepare instancing buffer by filling it with all instance transforms.
  234. void PrepareInstancingBuffer();
  235. /// Set up a light volume rendering batch.
  236. void SetupLightVolumeBatch(Batch& batch);
  237. /// Check whether a light queue needs shadow rendering.
  238. bool NeedRenderShadowMap(const LightBatchQueue& queue);
  239. /// Render a shadow map.
  240. void RenderShadowMap(const LightBatchQueue& queue);
  241. /// Return the proper depth-stencil surface to use for a rendertarget.
  242. RenderSurface* GetDepthStencil(RenderSurface* renderTarget);
  243. /// Helper function to get the render surface from a texture. 2D textures will always return the first face only.
  244. RenderSurface* GetRenderSurfaceFromTexture(Texture* texture, CubeMapFace face = FACE_POSITIVE_X);
  245. /// Send a view update or render related event through the Renderer subsystem. The parameters are the same for all of them.
  246. void SendViewEvent(StringHash eventType);
  247. /// Return the drawable's zone, or camera zone if it has override mode enabled.
  248. Zone* GetZone(Drawable* drawable)
  249. {
  250. if (cameraZoneOverride_)
  251. return cameraZone_;
  252. Zone* drawableZone = drawable->GetZone();
  253. return drawableZone ? drawableZone : cameraZone_;
  254. }
  255. /// Return the drawable's light mask, considering also its zone.
  256. unsigned GetLightMask(Drawable* drawable)
  257. {
  258. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  259. }
  260. /// Return the drawable's shadow mask, considering also its zone.
  261. unsigned GetShadowMask(Drawable* drawable)
  262. {
  263. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  264. }
  265. /// Return hash code for a vertex light queue.
  266. unsigned long long GetVertexLightQueueHash(const PODVector<Light*>& vertexLights)
  267. {
  268. unsigned long long hash = 0;
  269. for (PODVector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  270. hash += (unsigned long long)(*i);
  271. return hash;
  272. }
  273. /// Graphics subsystem.
  274. WeakPtr<Graphics> graphics_;
  275. /// Renderer subsystem.
  276. WeakPtr<Renderer> renderer_;
  277. /// Scene to use.
  278. Scene* scene_;
  279. /// Octree to use.
  280. Octree* octree_;
  281. /// Viewport (rendering) camera.
  282. Camera* camera_;
  283. /// Culling camera. Usually same as the viewport camera.
  284. Camera* cullCamera_;
  285. /// Shared source view. Null if this view is using its own culling.
  286. WeakPtr<View> sourceView_;
  287. /// Zone the camera is inside, or default zone if not assigned.
  288. Zone* cameraZone_;
  289. /// Zone at far clip plane.
  290. Zone* farClipZone_;
  291. /// Occlusion buffer for the main camera.
  292. OcclusionBuffer* occlusionBuffer_;
  293. /// Destination color rendertarget.
  294. RenderSurface* renderTarget_;
  295. /// Substitute rendertarget for deferred rendering. Allocated if necessary.
  296. RenderSurface* substituteRenderTarget_;
  297. /// Texture(s) for sampling the viewport contents. Allocated if necessary.
  298. Texture* viewportTextures_[MAX_VIEWPORT_TEXTURES];
  299. /// Color rendertarget active for the current renderpath command.
  300. RenderSurface* currentRenderTarget_;
  301. /// Last used custom depth render surface.
  302. RenderSurface* lastCustomDepthSurface_;
  303. /// Texture containing the latest viewport texture.
  304. Texture* currentViewportTexture_;
  305. /// Dummy texture for D3D9 depth only rendering.
  306. Texture* depthOnlyDummyTexture_;
  307. /// Viewport rectangle.
  308. IntRect viewRect_;
  309. /// Viewport size.
  310. IntVector2 viewSize_;
  311. /// Destination rendertarget size.
  312. IntVector2 rtSize_;
  313. /// Information of the frame being rendered.
  314. FrameInfo frame_;
  315. /// View aspect ratio.
  316. float aspectRatio_;
  317. /// Minimum Z value of the visible scene.
  318. float minZ_;
  319. /// Maximum Z value of the visible scene.
  320. float maxZ_;
  321. /// Material quality level.
  322. int materialQuality_;
  323. /// Maximum number of occluder triangles.
  324. int maxOccluderTriangles_;
  325. /// Minimum number of instances required in a batch group to render as instanced.
  326. int minInstances_;
  327. /// Highest zone priority currently visible.
  328. int highestZonePriority_;
  329. /// Geometries updated flag.
  330. bool geometriesUpdated_;
  331. /// Camera zone's override flag.
  332. bool cameraZoneOverride_;
  333. /// Draw shadows flag.
  334. bool drawShadows_;
  335. /// Deferred flag. Inferred from the existence of a light volume command in the renderpath.
  336. bool deferred_;
  337. /// 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.
  338. bool deferredAmbient_;
  339. /// Forward light base pass optimization flag. If in use, combine the base pass and first light for all opaque objects.
  340. bool useLitBase_;
  341. /// Has scene passes flag. If no scene passes, view can be defined without a valid scene or camera to only perform quad rendering.
  342. bool hasScenePasses_;
  343. /// Whether is using a custom readable depth texture without a stencil channel.
  344. bool noStencil_;
  345. /// Draw debug geometry flag. Copied from the viewport.
  346. bool drawDebug_;
  347. /// Renderpath.
  348. RenderPath* renderPath_;
  349. /// Per-thread octree query results.
  350. Vector<PODVector<Drawable*> > tempDrawables_;
  351. /// Per-thread geometries, lights and Z range collection results.
  352. Vector<PerThreadSceneResult> sceneResults_;
  353. /// Visible zones.
  354. PODVector<Zone*> zones_;
  355. /// Visible geometry objects.
  356. PODVector<Drawable*> geometries_;
  357. /// Geometry objects that will be updated in the main thread.
  358. PODVector<Drawable*> nonThreadedGeometries_;
  359. /// Geometry objects that will be updated in worker threads.
  360. PODVector<Drawable*> threadedGeometries_;
  361. /// Occluder objects.
  362. PODVector<Drawable*> occluders_;
  363. /// Lights.
  364. PODVector<Light*> lights_;
  365. /// Number of active occluders.
  366. unsigned activeOccluders_;
  367. /// Drawables that limit their maximum light count.
  368. HashSet<Drawable*> maxLightsDrawables_;
  369. /// Rendertargets defined by the renderpath.
  370. HashMap<StringHash, Texture*> renderTargets_;
  371. /// Intermediate light processing results.
  372. Vector<LightQueryResult> lightQueryResults_;
  373. /// Info for scene render passes defined by the renderpath.
  374. PODVector<ScenePassInfo> scenePasses_;
  375. /// Per-pixel light queues.
  376. Vector<LightBatchQueue> lightQueues_;
  377. /// Per-vertex light queues.
  378. HashMap<unsigned long long, LightBatchQueue> vertexLightQueues_;
  379. /// Batch queues by pass index.
  380. HashMap<unsigned, BatchQueue> batchQueues_;
  381. /// Index of the GBuffer pass.
  382. unsigned gBufferPassIndex_;
  383. /// Index of the opaque forward base pass.
  384. unsigned basePassIndex_;
  385. /// Index of the alpha pass.
  386. unsigned alphaPassIndex_;
  387. /// Index of the forward light pass.
  388. unsigned lightPassIndex_;
  389. /// Index of the litbase pass.
  390. unsigned litBasePassIndex_;
  391. /// Index of the litalpha pass.
  392. unsigned litAlphaPassIndex_;
  393. /// Pointer to the light volume command if any.
  394. const RenderPathCommand* lightVolumeCommand_;
  395. /// Pointer to the forwardlights command if any.
  396. const RenderPathCommand* forwardLightsCommand_;
  397. /// Pointer to the current commmand if it contains shader parameters to be set for a render pass.
  398. const RenderPathCommand* passCommand_;
  399. /// Flag for scene being resolved from the backbuffer.
  400. bool usedResolve_;
  401. };
  402. }