View.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #include "../Container/HashSet.h"
  5. #include "../Core/Object.h"
  6. #include "../Graphics/Batch.h"
  7. #include "../Graphics/Light.h"
  8. #include "../Graphics/Zone.h"
  9. #include "../Math/Polyhedron.h"
  10. namespace Urho3D
  11. {
  12. class Camera;
  13. class DebugRenderer;
  14. class Light;
  15. class Drawable;
  16. class Graphics;
  17. class OcclusionBuffer;
  18. class Octree;
  19. class Renderer;
  20. class RenderPath;
  21. class RenderSurface;
  22. class Technique;
  23. class Texture;
  24. class Texture2D;
  25. class Viewport;
  26. class Zone;
  27. struct RenderPathCommand;
  28. struct WorkItem;
  29. /// Intermediate light processing result.
  30. struct LightQueryResult
  31. {
  32. /// Light.
  33. Light* light_;
  34. /// Lit geometries.
  35. Vector<Drawable*> litGeometries_;
  36. /// Shadow casters.
  37. Vector<Drawable*> shadowCasters_;
  38. /// Shadow cameras.
  39. Camera* shadowCameras_[MAX_LIGHT_SPLITS];
  40. /// Shadow caster start indices.
  41. i32 shadowCasterBegin_[MAX_LIGHT_SPLITS];
  42. /// Shadow caster end indices.
  43. i32 shadowCasterEnd_[MAX_LIGHT_SPLITS];
  44. /// Combined bounding box of shadow casters in light projection space. Only used for focused spot lights.
  45. BoundingBox shadowCasterBox_[MAX_LIGHT_SPLITS];
  46. /// Shadow camera near splits (directional lights only).
  47. float shadowNearSplits_[MAX_LIGHT_SPLITS];
  48. /// Shadow camera far splits (directional lights only).
  49. float shadowFarSplits_[MAX_LIGHT_SPLITS];
  50. /// Shadow map split count.
  51. i32 numSplits_;
  52. };
  53. /// Scene render pass info.
  54. struct ScenePassInfo
  55. {
  56. /// Pass index.
  57. i32 passIndex_;
  58. /// Allow instancing flag.
  59. bool allowInstancing_;
  60. /// Mark to stencil flag.
  61. bool markToStencil_;
  62. /// Vertex light flag.
  63. bool vertexLights_;
  64. /// Batch queue.
  65. BatchQueue* batchQueue_;
  66. };
  67. /// Per-thread geometry, light and scene range collection structure.
  68. struct PerThreadSceneResult
  69. {
  70. /// Geometry objects.
  71. Vector<Drawable*> geometries_;
  72. /// Lights.
  73. Vector<Light*> lights_;
  74. /// Scene minimum Z value.
  75. float minZ_;
  76. /// Scene maximum Z value.
  77. float maxZ_;
  78. };
  79. inline constexpr i32 MAX_VIEWPORT_TEXTURES = 2;
  80. /// Internal structure for 3D rendering work. Created for each backbuffer and texture viewport, but not for shadow cameras.
  81. class URHO3D_API View : public Object
  82. {
  83. friend void CheckVisibilityWork(const WorkItem* item, i32 threadIndex);
  84. friend void ProcessLightWork(const WorkItem* item, i32 threadIndex);
  85. URHO3D_OBJECT(View, Object);
  86. public:
  87. /// Construct.
  88. explicit View(Context* context);
  89. /// Destruct.
  90. ~View() override = default;
  91. /// Define with rendertarget and viewport. Return true if successful.
  92. bool Define(RenderSurface* renderTarget, Viewport* viewport);
  93. /// Update and cull objects and construct rendering batches.
  94. void Update(const FrameInfo& frame);
  95. /// Render batches.
  96. void Render();
  97. /// Return graphics subsystem.
  98. Graphics* GetGraphics() const;
  99. /// Return renderer subsystem.
  100. Renderer* GetRenderer() const;
  101. /// Return scene.
  102. Scene* GetScene() const { return scene_; }
  103. /// Return octree.
  104. Octree* GetOctree() const { return octree_; }
  105. /// Return viewport camera.
  106. Camera* GetCamera() const { return camera_; }
  107. /// Return culling camera. Normally same as the viewport camera.
  108. Camera* GetCullCamera() const { return cullCamera_; }
  109. /// Return information of the frame being rendered.
  110. const FrameInfo& GetFrameInfo() const { return frame_; }
  111. /// Return the rendertarget. 0 if using the backbuffer.
  112. RenderSurface* GetRenderTarget() const { return renderTarget_; }
  113. /// Return whether should draw debug geometry.
  114. bool GetDrawDebug() const { return drawDebug_; }
  115. /// Return view rectangle.
  116. const IntRect& GetViewRect() const { return viewRect_; }
  117. /// Return view dimensions.
  118. const IntVector2& GetViewSize() const { return viewSize_; }
  119. /// Return geometry objects.
  120. const Vector<Drawable*>& GetGeometries() const { return geometries_; }
  121. /// Return occluder objects.
  122. const Vector<Drawable*>& GetOccluders() const { return occluders_; }
  123. /// Return lights.
  124. const Vector<Light*>& GetLights() const { return lights_; }
  125. /// Return light batch queues.
  126. const Vector<LightBatchQueue>& GetLightQueues() const { return lightQueues_; }
  127. /// Return the last used software occlusion buffer.
  128. OcclusionBuffer* GetOcclusionBuffer() const { return occlusionBuffer_; }
  129. /// Return number of occluders that were actually rendered. Occluders may be rejected if running out of triangles or if behind other occluders.
  130. i32 GetNumActiveOccluders() const { return activeOccluders_; }
  131. /// Return the source view that was already prepared. Used when viewports specify the same culling camera.
  132. View* GetSourceView() const;
  133. /// Set global (per-frame) shader parameters. Called by Batch and internally by View.
  134. void SetGlobalShaderParameters();
  135. /// Set camera-specific shader parameters. Called by Batch and internally by View.
  136. void SetCameraShaderParameters(Camera* camera);
  137. /// Set command's shader parameters if any. Called internally by View.
  138. void SetCommandShaderParameters(const RenderPathCommand& command);
  139. /// Set G-buffer offset and inverse size shader parameters. Called by Batch and internally by View.
  140. void SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect);
  141. /// 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.
  142. void DrawFullscreenQuad(bool setIdentityProjection = false);
  143. /// Get a named texture from the rendertarget list or from the resource cache, to be either used as a rendertarget or texture binding.
  144. Texture* FindNamedTexture(const String& name, bool isRenderTarget, bool isVolumeMap = false);
  145. private:
  146. /// Query the octree for drawable objects.
  147. void GetDrawables();
  148. /// Construct batches from the drawable objects.
  149. void GetBatches();
  150. /// Get lit geometries and shadowcasters for visible lights.
  151. void ProcessLights();
  152. /// Get batches from lit geometries and shadowcasters.
  153. void GetLightBatches();
  154. /// Get unlit batches.
  155. void GetBaseBatches();
  156. /// Update geometries and sort batches.
  157. void UpdateGeometries();
  158. /// Get pixel lit batches for a certain light and drawable.
  159. void GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue);
  160. /// Execute render commands.
  161. void ExecuteRenderPathCommands();
  162. /// Set rendertargets for current render command.
  163. void SetRenderTargets(RenderPathCommand& command);
  164. /// Set textures for current render command. Return whether depth write is allowed (depth-stencil not bound as a texture).
  165. bool SetTextures(RenderPathCommand& command);
  166. /// Perform a quad rendering command.
  167. void RenderQuad(RenderPathCommand& command);
  168. /// Check if a command is enabled and has content to render. To be called only after render update has completed for the frame.
  169. bool IsNecessary(const RenderPathCommand& command);
  170. /// Check if a command reads the destination render target.
  171. bool CheckViewportRead(const RenderPathCommand& command);
  172. /// Check if a command writes into the destination render target.
  173. bool CheckViewportWrite(const RenderPathCommand& command);
  174. /// Check whether a command should use pingponging instead of resolve from destination render target to viewport texture.
  175. bool CheckPingpong(i32 index);
  176. /// Allocate needed screen buffers.
  177. void AllocateScreenBuffers();
  178. /// Blit the viewport from one surface to another.
  179. void BlitFramebuffer(Texture* source, RenderSurface* destination, bool depthWrite);
  180. /// Query for occluders as seen from a camera.
  181. void UpdateOccluders(Vector<Drawable*>& occluders, Camera* camera);
  182. /// Draw occluders to occlusion buffer.
  183. void DrawOccluders(OcclusionBuffer* buffer, const Vector<Drawable*>& occluders);
  184. /// Query for lit geometries and shadow casters for a light.
  185. void ProcessLight(LightQueryResult& query, i32 threadIndex);
  186. /// Process shadow casters' visibilities and build their combined view- or projection-space bounding box.
  187. void ProcessShadowCasters(LightQueryResult& query, const Vector<Drawable*>& drawables, i32 splitIndex);
  188. /// Set up initial shadow camera view(s).
  189. void SetupShadowCameras(LightQueryResult& query);
  190. /// Set up a directional light shadow camera.
  191. void SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit);
  192. /// Finalize shadow camera view after shadow casters and the shadow map are known.
  193. void
  194. FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& shadowCasterBox);
  195. /// Quantize a directional light shadow camera view to eliminate swimming.
  196. void
  197. QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport, const BoundingBox& viewBox);
  198. /// Check visibility of one shadow caster.
  199. bool IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  200. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox);
  201. /// Return the viewport for a shadow map split.
  202. IntRect GetShadowMapViewport(Light* light, int splitIndex, Texture2D* shadowMap);
  203. /// Find and set a new zone for a drawable when it has moved.
  204. void FindZone(Drawable* drawable);
  205. /// Return material technique, considering the drawable's LOD distance.
  206. Technique* GetTechnique(Drawable* drawable, Material* material);
  207. /// Check if material should render an auxiliary view (if it has a camera attached).
  208. void CheckMaterialForAuxView(Material* material);
  209. /// Set shader defines for a batch queue if used.
  210. void SetQueueShaderDefines(BatchQueue& queue, const RenderPathCommand& command);
  211. /// Choose shaders for a batch and add it to queue.
  212. void AddBatchToQueue(BatchQueue& queue, Batch& batch, Technique* tech, bool allowInstancing = true, bool allowShadows = true);
  213. /// Prepare instancing buffer by filling it with all instance transforms.
  214. void PrepareInstancingBuffer();
  215. /// Set up a light volume rendering batch.
  216. void SetupLightVolumeBatch(Batch& batch);
  217. /// Check whether a light queue needs shadow rendering.
  218. bool NeedRenderShadowMap(const LightBatchQueue& queue);
  219. /// Render a shadow map.
  220. void RenderShadowMap(const LightBatchQueue& queue);
  221. /// Return the proper depth-stencil surface to use for a rendertarget.
  222. RenderSurface* GetDepthStencil(RenderSurface* renderTarget);
  223. /// Helper function to get the render surface from a texture. 2D textures will always return the first face only.
  224. RenderSurface* GetRenderSurfaceFromTexture(Texture* texture, CubeMapFace face = FACE_POSITIVE_X);
  225. /// Send a view update or render related event through the Renderer subsystem. The parameters are the same for all of them.
  226. void SendViewEvent(StringHash eventType);
  227. /// Return the drawable's zone, or camera zone if it has override mode enabled.
  228. Zone* GetZone(Drawable* drawable)
  229. {
  230. if (cameraZoneOverride_)
  231. return cameraZone_;
  232. Zone* drawableZone = drawable->GetZone();
  233. return drawableZone ? drawableZone : cameraZone_;
  234. }
  235. /// Return the drawable's light mask, considering also its zone.
  236. unsigned GetLightMask(Drawable* drawable)
  237. {
  238. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  239. }
  240. /// Return the drawable's shadow mask, considering also its zone.
  241. unsigned GetShadowMask(Drawable* drawable)
  242. {
  243. return drawable->GetShadowMask() & GetZone(drawable)->GetShadowMask();
  244. }
  245. /// Return hash code for a vertex light queue.
  246. hash64 GetVertexLightQueueHash(const Vector<Light*>& vertexLights)
  247. {
  248. hash64 hash = 0;
  249. for (Vector<Light*>::ConstIterator i = vertexLights.Begin(); i != vertexLights.End(); ++i)
  250. hash += (hash64)(*i);
  251. return hash;
  252. }
  253. /// Graphics subsystem.
  254. WeakPtr<Graphics> graphics_;
  255. /// Renderer subsystem.
  256. WeakPtr<Renderer> renderer_;
  257. /// Scene to use.
  258. Scene* scene_{};
  259. /// Octree to use.
  260. Octree* octree_{};
  261. /// Viewport (rendering) camera.
  262. Camera* camera_{};
  263. /// Culling camera. Usually same as the viewport camera.
  264. Camera* cullCamera_{};
  265. /// Shared source view. Null if this view is using its own culling.
  266. WeakPtr<View> sourceView_;
  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. /// Last used custom depth render surface.
  282. RenderSurface* lastCustomDepthSurface_{};
  283. /// Texture containing the latest viewport texture.
  284. Texture* currentViewportTexture_{};
  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. /// View aspect ratio.
  294. float aspectRatio_{};
  295. /// Minimum Z value of the visible scene.
  296. float minZ_{};
  297. /// Maximum Z value of the visible scene.
  298. float maxZ_{};
  299. /// Material quality level.
  300. int materialQuality_{};
  301. /// Maximum number of occluder triangles.
  302. int maxOccluderTriangles_{};
  303. /// Minimum number of instances required in a batch group to render as instanced.
  304. int minInstances_{};
  305. /// Highest zone priority currently visible.
  306. int highestZonePriority_{};
  307. /// Geometries updated flag.
  308. bool geometriesUpdated_{};
  309. /// Camera zone's override flag.
  310. bool cameraZoneOverride_{};
  311. /// Draw shadows flag.
  312. bool drawShadows_{};
  313. /// Deferred flag. Inferred from the existence of a light volume command in the renderpath.
  314. bool deferred_{};
  315. /// 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.
  316. bool deferredAmbient_{};
  317. /// Forward light base pass optimization flag. If in use, combine the base pass and first light for all opaque objects.
  318. bool useLitBase_{};
  319. /// Has scene passes flag. If no scene passes, view can be defined without a valid scene or camera to only perform quad rendering.
  320. bool hasScenePasses_{};
  321. /// Whether is using a custom readable depth texture without a stencil channel.
  322. bool noStencil_{};
  323. /// Draw debug geometry flag. Copied from the viewport.
  324. bool drawDebug_{};
  325. /// Renderpath.
  326. RenderPath* renderPath_{};
  327. /// Per-thread octree query results.
  328. Vector<Vector<Drawable*>> tempDrawables_;
  329. /// Per-thread geometries, lights and Z range collection results.
  330. Vector<PerThreadSceneResult> sceneResults_;
  331. /// Visible zones.
  332. Vector<Zone*> zones_;
  333. /// Visible geometry objects.
  334. Vector<Drawable*> geometries_;
  335. /// Geometry objects that will be updated in the main thread.
  336. Vector<Drawable*> nonThreadedGeometries_;
  337. /// Geometry objects that will be updated in worker threads.
  338. Vector<Drawable*> threadedGeometries_;
  339. /// Occluder objects.
  340. Vector<Drawable*> occluders_;
  341. /// Lights.
  342. Vector<Light*> lights_;
  343. /// Number of active occluders.
  344. i32 activeOccluders_{};
  345. /// Drawables that limit their maximum light count.
  346. HashSet<Drawable*> maxLightsDrawables_;
  347. /// Rendertargets defined by the renderpath.
  348. HashMap<StringHash, Texture*> renderTargets_;
  349. /// Intermediate light processing results.
  350. Vector<LightQueryResult> lightQueryResults_;
  351. /// Info for scene render passes defined by the renderpath.
  352. Vector<ScenePassInfo> scenePasses_;
  353. /// Per-pixel light queues.
  354. Vector<LightBatchQueue> lightQueues_;
  355. /// Per-vertex light queues.
  356. HashMap<hash64, LightBatchQueue> vertexLightQueues_;
  357. /// Batch queues by pass index.
  358. HashMap<i32, BatchQueue> batchQueues_;
  359. /// Index of the GBuffer pass.
  360. i32 gBufferPassIndex_{};
  361. /// Index of the opaque forward base pass.
  362. i32 basePassIndex_{};
  363. /// Index of the alpha pass.
  364. i32 alphaPassIndex_{};
  365. /// Index of the forward light pass.
  366. i32 lightPassIndex_{};
  367. /// Index of the litbase pass.
  368. i32 litBasePassIndex_{};
  369. /// Index of the litalpha pass.
  370. i32 litAlphaPassIndex_{};
  371. /// Pointer to the light volume command if any.
  372. const RenderPathCommand* lightVolumeCommand_{};
  373. /// Pointer to the forwardlights command if any.
  374. const RenderPathCommand* forwardLightsCommand_{};
  375. /// Pointer to the current commmand if it contains shader parameters to be set for a render pass.
  376. const RenderPathCommand* passCommand_{};
  377. /// Flag for scene being resolved from the backbuffer.
  378. bool usedResolve_{};
  379. };
  380. }