CmRenderSystem.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #ifndef __RenderSystem_H_
  25. #define __RenderSystem_H_
  26. // Precompiler options
  27. #include "CmPrerequisites.h"
  28. #include <memory>
  29. #include "CmString.h"
  30. #include "CmSamplerState.h"
  31. #include "CmCommon.h"
  32. #include "CmRenderOperation.h"
  33. #include "CmRenderSystemCapabilities.h"
  34. #include "CmRenderTarget.h"
  35. #include "CmRenderTexture.h"
  36. #include "CmGpuProgram.h"
  37. #include "CmPlane.h"
  38. #include "CmModule.h"
  39. #include "boost/function.hpp"
  40. #include "boost/signal.hpp"
  41. namespace CamelotEngine
  42. {
  43. /** \addtogroup Core
  44. * @{
  45. */
  46. /** \addtogroup RenderSystem
  47. * @{
  48. */
  49. typedef multimap<UINT8, RenderTarget * >::type RenderTargetPriorityMap;
  50. class TextureManager;
  51. /** Defines the functionality of a 3D API
  52. @remarks
  53. The RenderSystem class provides a base interface
  54. which abstracts the general functionality of the 3D API
  55. e.g. Direct3D or OpenGL. Whilst a few of the general
  56. methods have implementations, most of this class is
  57. abstract, requiring a subclass based on a specific API
  58. to be constructed to provide the full functionality.
  59. @author
  60. Steven Streeting
  61. @version
  62. 1.0
  63. */
  64. class CM_EXPORT RenderSystem : public Module<RenderSystem>
  65. {
  66. public:
  67. /** Default Constructor.
  68. */
  69. RenderSystem();
  70. /** Destructor.
  71. */
  72. virtual ~RenderSystem();
  73. /** Returns the name of the rendering system.
  74. */
  75. virtual const String& getName(void) const = 0;
  76. /** Attaches the passed render target to the render system.
  77. */
  78. virtual void attachRenderTarget(RenderTarget &target);
  79. /** Detaches the render target from the render system.
  80. @note
  81. If the render target cannot be found, NULL is returned.
  82. */
  83. virtual void detachRenderTarget(RenderTarget& renderTarget);
  84. /** Destroys a render window */
  85. virtual void destroyRenderWindow(RenderWindow* renderWindow);
  86. /** Destroys a render texture */
  87. virtual void destroyRenderTexture(RenderTexture* renderTexture);
  88. /** Destroys a render target of any sort */
  89. virtual void destroyRenderTarget(RenderTarget* renderTarget);
  90. /** Defines whether or now fullscreen render windows wait for the vertical blank before flipping buffers.
  91. @remarks
  92. By default, all rendering windows wait for a vertical blank (when the CRT beam turns off briefly to move
  93. from the bottom right of the screen back to the top left) before flipping the screen buffers. This ensures
  94. that the image you see on the screen is steady. However it restricts the frame rate to the refresh rate of
  95. the monitor, and can slow the frame rate down. You can speed this up by not waiting for the blank, but
  96. this has the downside of introducing 'tearing' artefacts where part of the previous frame is still displayed
  97. as the buffers are switched. Speed vs quality, you choose.
  98. @note
  99. Has NO effect on windowed mode render targets. Only affects fullscreen mode.
  100. @param
  101. enabled If true, the system waits for vertical blanks - quality over speed. If false it doesn't - speed over quality.
  102. */
  103. void setWaitForVerticalBlank(bool enabled);
  104. /** Returns true if the system is synchronising frames with the monitor vertical blank.
  105. */
  106. bool getWaitForVerticalBlank(void) const;
  107. /**
  108. * @brief Sets a sampler state for the specified texture unit.
  109. * @see SamplerState
  110. */
  111. virtual void setSamplerState(UINT16 texUnit, const SamplerState& samplerState) = 0;
  112. /** Turns off a texture unit. */
  113. virtual void disableTextureUnit(UINT16 texUnit);
  114. /** Disables all texture units from the given unit upwards */
  115. virtual void disableTextureUnitsFrom(UINT16 texUnit);
  116. /**
  117. * @brief Sets a blend state used for all active render targets.
  118. * @see BlendState
  119. */
  120. virtual void setBlendState(const BlendState& blendState) = 0;
  121. /**
  122. * @brief Sets a state that controls various rasterizer options.
  123. * @see RasterizerState
  124. */
  125. virtual void setRasterizerState(const RasterizerState& rasterizerState) = 0;
  126. /**
  127. * @brief Sets a state that controls depth & stencil buffer options.
  128. * @see DepthStencilState
  129. */
  130. virtual void setDepthStencilState(const DepthStencilState& depthStencilState) = 0;
  131. /**
  132. * @brief Sets a reference values used for stencil buffer comparisons.
  133. * Actual comparison function and stencil operations are set by setting the StencilState.
  134. *
  135. * @remarks
  136. * The stencil buffer is used to mask out pixels in the render target, allowing
  137. * you to do effects like mirrors, cut-outs, stencil shadows and more. Each of
  138. * your batches of rendering is likely to ignore the stencil buffer,
  139. * update it with new values, or apply it to mask the output of the render.
  140. * The stencil test is:<PRE>
  141. * (Reference Value & Mask) CompareFunction (Stencil Buffer Value & Mask)</PRE>
  142. * The result of this will cause one of 3 actions depending on whether the test fails,
  143. * succeeds but with the depth buffer check still failing, or succeeds with the
  144. * depth buffer check passing too.
  145. */
  146. virtual void setStencilRefValue(UINT32 refValue) = 0;
  147. /**
  148. Sets the texture to bind to a given texture unit.
  149. User processes would not normally call this direct unless rendering
  150. primitives themselves.
  151. @param unit The index of the texture unit to modify. Multitexturing
  152. hardware can support multiple units (see
  153. RenderSystemCapabilites::getNumTextureUnits)
  154. @param enabled Boolean to turn the unit on/off
  155. @param texPtr Pointer to the texture to use.
  156. */
  157. virtual void setTexture(UINT16 unit, bool enabled, const TexturePtr &texPtr) = 0;
  158. /**
  159. * Signifies the beginning of a frame, i.e. the start of rendering on a single viewport. Will occur
  160. * several times per complete frame if multiple viewports exist.
  161. */
  162. virtual void beginFrame(void) = 0;
  163. /**
  164. * Ends rendering of a frame to the current viewport.
  165. */
  166. virtual void endFrame(void) = 0;
  167. /**
  168. Sets the provided viewport as the active one for future
  169. rendering operations. This viewport is aware of it's own
  170. camera and render target. Must be implemented by subclass.
  171. @param target Viewport to render to.
  172. */
  173. virtual void setViewport(const Viewport& vp) = 0;
  174. /** Get the current active viewport for rendering. */
  175. virtual Viewport getViewport(void);
  176. /** Sets the current vertex declaration, ie the source of vertex data. */
  177. virtual void setVertexDeclaration(VertexDeclarationPtr decl) = 0;
  178. /** Sets the current vertex buffer binding state. */
  179. virtual void setVertexBufferBinding(VertexBufferBinding* binding) = 0;
  180. /**
  181. Render something to the active viewport.
  182. Low-level rendering interface to perform rendering
  183. operations. Unlikely to be used directly by client
  184. applications, since the SceneManager and various support
  185. classes will be responsible for calling this method.
  186. Can only be called between _beginScene and _endScene
  187. @param op A rendering operation instance, which contains
  188. details of the operation to be performed.
  189. */
  190. virtual void render(const RenderOperation& op);
  191. /** Gets the capabilities of the render system. */
  192. const RenderSystemCapabilities* getCapabilities(void) const;
  193. /** Returns the driver version.
  194. */
  195. virtual const DriverVersion& getDriverVersion(void) const;
  196. /** Binds a given GpuProgram (but not the parameters).
  197. @remarks Only one GpuProgram of each type can be bound at once, binding another
  198. one will simply replace the existing one.
  199. */
  200. virtual void bindGpuProgram(GpuProgramHandle prg);
  201. /** Bind Gpu program parameters.
  202. @param gptype The type of program to bind the parameters to
  203. @param params The parameters to bind
  204. @param variabilityMask A mask of GpuParamVariability identifying which params need binding
  205. */
  206. virtual void bindGpuProgramParameters(GpuProgramType gptype,
  207. GpuProgramParametersSharedPtr params, UINT16 variabilityMask) = 0;
  208. /** Unbinds GpuPrograms of a given GpuProgramType.
  209. @remarks
  210. This returns the pipeline to fixed-function processing for this type.
  211. */
  212. virtual void unbindGpuProgram(GpuProgramType gptype);
  213. /** Returns whether or not a Gpu program of the given type is currently bound. */
  214. virtual bool isGpuProgramBound(GpuProgramType gptype);
  215. /** Sets the user clipping region.
  216. */
  217. virtual void setClipPlanes(const PlaneList& clipPlanes);
  218. /** Add a user clipping plane. */
  219. virtual void addClipPlane (const Plane& p);
  220. /** Add a user clipping plane. */
  221. virtual void addClipPlane (float A, float B, float C, float D);
  222. /** Clears the user clipping region.
  223. */
  224. virtual void resetClipPlanes();
  225. /** Internal method for swapping all the buffers on all render targets,
  226. if _updateAllRenderTargets was called with a 'false' parameter. */
  227. virtual void swapAllRenderTargetBuffers(bool waitForVsync = true);
  228. /** Sets the 'scissor region' ie the region of the target in which rendering can take place.
  229. @remarks
  230. This method allows you to 'mask off' rendering in all but a given rectangular area
  231. as identified by the parameters to this method.
  232. @note
  233. Not all systems support this method. Check the RenderSystemCapabilities for the
  234. RSC_SCISSOR_TEST capability to see if it is supported.
  235. @param left, top, right, bottom The location of the corners of the rectangle, expressed in
  236. <i>pixels</i>.
  237. */
  238. virtual void setScissorRect(UINT32 left = 0, UINT32 top = 0, UINT32 right = 800, UINT32 bottom = 600) = 0;
  239. /** Clears one or more frame buffers on the active render target.
  240. @param buffers Combination of one or more elements of FrameBufferType
  241. denoting which buffers are to be cleared
  242. @param colour The colour to clear the colour buffer with, if enabled
  243. @param depth The value to initialise the depth buffer with, if enabled
  244. @param stencil The value to initialise the stencil buffer with, if enabled.
  245. */
  246. virtual void clearFrameBuffer(unsigned int buffers,
  247. const Color& color = Color::Black,
  248. float depth = 1.0f, unsigned short stencil = 0) = 0;
  249. /**
  250. * Set current render target to target, enabling its device context if needed
  251. */
  252. virtual void setRenderTarget(RenderTarget* target) = 0;
  253. /************************************************************************/
  254. /* UTILITY METHODS */
  255. /************************************************************************/
  256. /** Get the native VertexElementType for a compact 32-bit colour value
  257. for this rendersystem.
  258. */
  259. virtual VertexElementType getColorVertexElementType(void) const = 0;
  260. /** Converts a uniform projection matrix to suitable for this render system.
  261. @remarks
  262. Because different APIs have different requirements (some incompatible) for the
  263. projection matrix, this method allows each to implement their own correctly and pass
  264. back a generic Camelot matrix for storage in the engine.
  265. */
  266. virtual void convertProjectionMatrix(const Matrix4& matrix,
  267. Matrix4& dest, bool forGpuProgram = false) = 0;
  268. /** Returns the horizontal texel offset value required for mapping
  269. texel origins to pixel origins in this rendersystem.
  270. @remarks
  271. Since rendersystems sometimes disagree on the origin of a texel,
  272. mapping from texels to pixels can sometimes be problematic to
  273. implement generically. This method allows you to retrieve the offset
  274. required to map the origin of a texel to the origin of a pixel in
  275. the horizontal direction.
  276. */
  277. virtual float getHorizontalTexelOffset(void) = 0;
  278. /** Returns the vertical texel offset value required for mapping
  279. texel origins to pixel origins in this rendersystem.
  280. @remarks
  281. Since rendersystems sometimes disagree on the origin of a texel,
  282. mapping from texels to pixels can sometimes be problematic to
  283. implement generically. This method allows you to retrieve the offset
  284. required to map the origin of a texel to the origin of a pixel in
  285. the vertical direction.
  286. */
  287. virtual float getVerticalTexelOffset(void) = 0;
  288. /** Gets the minimum (closest) depth value to be used when rendering
  289. using identity transforms.
  290. @remarks
  291. When using identity transforms you can manually set the depth
  292. of a vertex; however the input values required differ per
  293. rendersystem. This method lets you retrieve the correct value.
  294. @see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection
  295. */
  296. virtual float getMinimumDepthInputValue(void) = 0;
  297. /** Gets the maximum (farthest) depth value to be used when rendering
  298. using identity transforms.
  299. @remarks
  300. When using identity transforms you can manually set the depth
  301. of a vertex; however the input values required differ per
  302. rendersystem. This method lets you retrieve the correct value.
  303. @see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection
  304. */
  305. virtual float getMaximumDepthInputValue(void) = 0;
  306. /************************************************************************/
  307. /* INTERNAL DATA & METHODS */
  308. /************************************************************************/
  309. protected:
  310. friend class RenderSystemManager;
  311. /** The render targets. */
  312. vector<RenderTarget*>::type mRenderTargets;
  313. /** The render targets, ordered by priority. */
  314. RenderTargetPriorityMap mPrioritisedRenderTargets;
  315. /** The Active render target. */
  316. RenderTarget* mActiveRenderTarget;
  317. /** The Active GPU programs and gpu program parameters*/
  318. GpuProgramParametersSharedPtr mActiveVertexGpuProgramParameters;
  319. GpuProgramParametersSharedPtr mActiveGeometryGpuProgramParameters;
  320. GpuProgramParametersSharedPtr mActiveFragmentGpuProgramParameters;
  321. // Active viewport (dest for future rendering operations)
  322. Viewport mActiveViewport;
  323. CullingMode mCullingMode;
  324. bool mVsync;
  325. unsigned int mVSyncInterval;
  326. bool mInvertVertexWinding;
  327. /// Texture units from this upwards are disabled
  328. UINT16 mDisabledTexUnitsFrom;
  329. bool mVertexProgramBound;
  330. bool mGeometryProgramBound;
  331. bool mFragmentProgramBound;
  332. // Recording user clip planes
  333. PlaneList mClipPlanes;
  334. // Indicator that we need to re-set the clip planes on next render call
  335. bool mClipPlanesDirty;
  336. /// Used to store the capabilities of the graphics card
  337. RenderSystemCapabilities* mCurrentCapabilities;
  338. /**
  339. * @brief Call right after creation to properly initialize the RenderSystem;
  340. */
  341. void initialize();
  342. virtual void initialize_internal();
  343. virtual void destroy_internal();
  344. /// Internal method used to set the underlying clip planes when needed
  345. virtual void setClipPlanesImpl(const PlaneList& clipPlanes) = 0;
  346. /** Query the real capabilities of the GPU and driver in the RenderSystem*/
  347. virtual RenderSystemCapabilities* createRenderSystemCapabilities() const = 0;
  348. /** Initialize the render system from the capabilities*/
  349. virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps) = 0;
  350. /** Create a MultiRenderTarget, which is a render target that renders to multiple RenderTextures
  351. at once. Surfaces can be bound and unbound at will.
  352. This fails if mCapabilities->getNumMultiRenderTargets() is smaller than 2.
  353. */
  354. virtual MultiRenderTarget * createMultiRenderTarget(const String & name) = 0;
  355. /** Returns a description of an error code.
  356. */
  357. virtual String getErrorDescription(long errorNumber) const = 0;
  358. DriverVersion mDriverVersion;
  359. /************************************************************************/
  360. /* THREADING */
  361. /************************************************************************/
  362. class RenderWorkerFunc CM_THREAD_WORKER_INHERIT
  363. {
  364. public:
  365. RenderWorkerFunc(RenderSystem* rs);
  366. void operator()();
  367. private:
  368. RenderSystem* mRS;
  369. };
  370. RenderWorkerFunc* mRenderThreadFunc;
  371. bool mRenderThreadShutdown;
  372. CM_THREAD_ID_TYPE mRenderThreadId;
  373. CM_THREAD_SYNCHRONISER(mRenderThreadStartCondition)
  374. CM_MUTEX(mRenderThreadStartMutex)
  375. CM_MUTEX(mCommandQueueMutex)
  376. CM_THREAD_SYNCHRONISER(mCommandReadyCondition)
  377. CM_MUTEX(mCommandNotifyMutex)
  378. CM_THREAD_SYNCHRONISER(mCommandCompleteCondition)
  379. #if CM_THREAD_SUPPORT
  380. CM_THREAD_TYPE* mRenderThread;
  381. #endif
  382. CommandQueue* mCommandQueue;
  383. UINT32 mMaxCommandNotifyId; // ID that will be assigned to the next command with a notifier callback
  384. vector<UINT32>::type mCommandsCompleted; // Completed commands that have notifier callbacks set up
  385. /**
  386. * @brief Initializes a separate render thread. Should only be called once.
  387. */
  388. void initRenderThread();
  389. /**
  390. * @brief Main function of the render thread. Called once thread is started.
  391. */
  392. void runRenderThread();
  393. /**
  394. * @brief Shutdowns the render thread. It will complete all ready commands
  395. * before shutdown.
  396. */
  397. void shutdownRenderThread();
  398. /**
  399. * @brief Throws an exception if current thread isn't the render thread;
  400. */
  401. void throwIfNotRenderThread() const;
  402. /**
  403. * @brief Blocks the calling thread until the command with the specified ID completes.
  404. * Make sure that the specified ID actually exists, otherwise this will block forever.
  405. */
  406. void blockUntilCommandCompleted(UINT32 commandId);
  407. /**
  408. * @brief Callback called by the command list when a specific command finishes executing.
  409. * This is only called on commands that have a special notify on complete flag set.
  410. *
  411. * @param commandId Identifier for the command.
  412. */
  413. void commandCompletedNotify(UINT32 commandId);
  414. public:
  415. /**
  416. * @brief Returns the id of the render thread. If a separate render thread
  417. * is not used, then it returns the id of the thread RenderSystem
  418. * was initialized on.
  419. */
  420. CM_THREAD_ID_TYPE getRenderThreadId() const { return mRenderThreadId; }
  421. /**
  422. * @brief Creates a new render system context that you can use for rendering on
  423. * a non-render thread. You can have as many of these as you wish, the only limitation
  424. * is that you do not use a single instance on more than one thread. Each thread
  425. * requires its own context. The context will be bound to the thread you call this method on.
  426. */
  427. DeferredRenderContextPtr createDeferredContext();
  428. /**
  429. * @brief Queues a new command that will be added to the global command queue. You are allowed to call this from any thread,
  430. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  431. *
  432. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there be many commands queued before it
  433. * and they all need to be executed in order before the current command is reached, which might take a long time.
  434. *
  435. * @see CommandQueue::queueReturn
  436. */
  437. AsyncOp queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete = false);
  438. /**
  439. * @brief Queues a new command that will be added to the global command queue.You are allowed to call this from any thread,
  440. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  441. *
  442. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there be many commands queued before it
  443. * and they all need to be executed in order before the current command is reached, which might take a long time.
  444. * @see CommandQueue::queue
  445. */
  446. void queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete = false);
  447. };
  448. /** @} */
  449. /** @} */
  450. }
  451. #endif