View.h 15 KB

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