gfxDevice.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _GFXDEVICE_H_
  23. #define _GFXDEVICE_H_
  24. #ifndef _GFXADAPTER_H_
  25. #include "gfx/gfxAdapter.h"
  26. #endif
  27. #ifndef _GFXTARGET_H_
  28. #include "gfx/gfxTarget.h"
  29. #endif
  30. #ifndef _GFXVERTEXBUFFER_H_
  31. #include "gfx/gfxVertexBuffer.h"
  32. #endif
  33. #ifndef _GFXSTATEBLOCK_H_
  34. #include "gfx/gfxStateBlock.h"
  35. #endif
  36. #ifndef _GFXSHADER_H_
  37. #include "gfx/gfxShader.h"
  38. #endif
  39. #ifndef _GFXCUBEMAP_H_
  40. #include "gfx/gfxCubemap.h"
  41. #endif
  42. #ifndef _TDICTIONARY_H_
  43. #include "core/util/tDictionary.h"
  44. #endif
  45. #ifndef _TSIGNAL_H_
  46. #include "core/util/tSignal.h"
  47. #endif
  48. #ifndef _GFXDEVICESTATISTICS_H_
  49. #include "gfx/gfxDeviceStatistics.h"
  50. #endif
  51. #ifndef _MATHUTIL_FRUSTUM_H_
  52. #include "math/util/frustum.h"
  53. #endif
  54. class FontRenderBatcher;
  55. class GFont;
  56. class GFXCardProfiler;
  57. class GFXDrawUtil;
  58. class GFXFence;
  59. class GFXOcclusionQuery;
  60. class GFXPrimitiveBuffer;
  61. class GFXShader;
  62. class GFXStateBlock;
  63. class GFXShaderConstBuffer;
  64. class GFXTextureManager;
  65. // Global macro
  66. #define GFX GFXDevice::get()
  67. #define MAX_MRT_TARGETS 4
  68. //-----------------------------------------------------------------------------
  69. /// GFXDevice is the TSE graphics interface layer. This allows the TSE to
  70. /// do many things, such as use multiple render devices for multi-head systems,
  71. /// and allow a game to render in DirectX 9, OpenGL or any other API which has
  72. /// a GFX implementation seamlessly. There are many concepts in GFX device which
  73. /// may not be familiar to you, especially if you have not used DirectX.
  74. /// @n
  75. /// <b>Buffers</b>
  76. /// There are three types of buffers in GFX: vertex, index and primitive. Please
  77. /// note that index buffers are not accessable outside the GFX layer, they are wrapped
  78. /// by primitive buffers. Primitive buffers will be explained in detail later.
  79. /// Buffers are allocated and deallocated using their associated allocXBuffer and
  80. /// freeXBuffer methods on the device. When a buffer is allocated you pass in a
  81. /// pointer to, depending on the buffer, a vertex type pointer or a U16 pointer.
  82. /// During allocation, this pointer is set to the address of where you should
  83. /// copy in the information for this buffer. You must the tell the GFXDevice
  84. /// that the information is in, and it should prepare the buffer for use by calling
  85. /// the prepare method on it. Dynamic vertex buffer example:
  86. /// @code
  87. /// GFXVertexP *verts; // Making a buffer containing verticies with only position
  88. ///
  89. /// // Allocate a dynamic vertex buffer to hold 3 vertices and use *verts as the location to copy information into
  90. /// GFXVertexBufferHandle vb = GFX->allocVertexBuffer( 3, &verts, true );
  91. ///
  92. /// // Now set the information, we're making a triangle
  93. /// verts[0].point = Point3F( 200.f, 200.f, 0.f );
  94. /// verts[1].point = Point3F( 200.f, 400.f, 0.f );
  95. /// verts[2].point = Point3F( 400.f, 200.f, 0.f );
  96. ///
  97. /// // Tell GFX that the information is in and it should be made ready for use
  98. /// // Note that nothing is done with verts, this should not and MUST NOT be deleted
  99. /// // stored, or otherwise used after prepare is called.
  100. /// GFX->prepare( vb );
  101. ///
  102. /// // Because this is a dynamic vertex buffer, it is only assured to be valid until someone
  103. /// // else allocates a dynamic vertex buffer, so we will render it now
  104. /// GFX->setVertexBuffer( vb );
  105. /// GFX->drawPrimitive( GFXTriangleStrip, 0, 1 );
  106. ///
  107. /// // Now because this is a dynamic vertex buffer it MUST NOT BE FREED you are only
  108. /// // given a handle to a vertex buffer which belongs to the device
  109. /// @endcode
  110. ///
  111. /// To use a static vertex buffer, it is very similar, this is an example using a
  112. /// static primitive buffer:
  113. /// @n
  114. /// This takes place inside a constructor for a class which has a member variable
  115. /// called mPB which is the primitive buffer for the class instance.
  116. /// @code
  117. /// U16 *idx; // This is going to be where to write indices
  118. /// GFXPrimitiveInfo *primitiveInfo; // This will be where to write primitive information
  119. ///
  120. /// // Allocate a primitive buffer with 4 indices, and 1 primitive described for use
  121. /// mPB = GFX->allocPrimitiveBuffer( 4, &idx, 1, &primitiveInfo );
  122. ///
  123. /// // Write the index information, this is going to be for the outline of a triangle using
  124. /// // a line strip
  125. /// idx[0] = 0;
  126. /// idx[1] = 1;
  127. /// idx[2] = 2;
  128. /// idx[3] = 0;
  129. ///
  130. /// // Write the information for the primitive
  131. /// primitiveInfo->indexStart = 0; // Starting with index 0
  132. /// primitiveInfo->minVertex = 0; // The minimum vertex index is 0
  133. /// primitiveInfo->maxVertex = 3; // The maximum vertex index is 3
  134. /// primitiveInfo->primitiveCount = 3; // There are 3 lines we are drawing
  135. /// primitiveInfo->type = GFXLineStrip; // This primitive info describes a line strip
  136. /// @endcode
  137. /// The following code takes place in the destructor for the same class
  138. /// @code
  139. /// // Because this is a static buffer it's our responsibility to free it when we are done
  140. /// GFX->freePrimitiveBuffer( mPB );
  141. /// @endcode
  142. /// This last bit takes place in the rendering function for the class
  143. /// @code
  144. /// // You need to set a vertex buffer as well, primitive buffers contain indexing
  145. /// // information, not vertex information. This is so you could have, say, a static
  146. /// // vertex buffer, and a dynamic primitive buffer.
  147. ///
  148. /// // This sets the primitive buffer to the static buffer we allocated in the constructor
  149. /// GFX->setPrimitiveBuffer( mPB );
  150. ///
  151. /// // Draw the first primitive contained in the set primitive buffer, our primitive buffer
  152. /// // has only one primitive, so we could also technically call GFX->drawPrimitives(); and
  153. /// // get the same result.
  154. /// GFX->drawPrimitive( 0 );
  155. /// @endcode
  156. /// If you need any more examples on how to use these buffers please see the rest of the engine.
  157. /// @n
  158. /// <b>Primitive Buffers</b>
  159. /// @n
  160. /// Primitive buffers wrap and extend the concept of index buffers. The purpose of a primitive
  161. /// buffer is to let objects store all information they have to render their primitives in
  162. /// a central place. Say that a shape is made up of triangle strips and triangle fans, it would
  163. /// still have only one primitive buffer which contained primitive information for each strip
  164. /// and fan. It could then draw itself with one call.
  165. ///
  166. /// TO BE FINISHED LATER
  167. class GFXDevice
  168. {
  169. private:
  170. friend class GFXInit;
  171. friend class GFXPrimitiveBufferHandle;
  172. friend class GFXVertexBufferHandleBase;
  173. friend class GFXTextureObject;
  174. friend class GFXTexHandle;
  175. friend class GFXVertexFormat;
  176. friend class GFXTestFullscreenToggle;
  177. friend class TestGFXTextureCube;
  178. friend class TestGFXRenderTargetCube;
  179. friend class TestGFXRenderTargetStack;
  180. friend class GFXResource;
  181. friend class LightMatInstance; // For stencil interface
  182. //--------------------------------------------------------------------------
  183. // Static GFX interface
  184. //--------------------------------------------------------------------------
  185. public:
  186. enum GFXDeviceEventType
  187. {
  188. /// The device has been created, but not initialized
  189. deCreate,
  190. /// The device has been initialized
  191. deInit,
  192. /// The device is about to be destroyed.
  193. deDestroy,
  194. /// The device has started rendering a frame
  195. deStartOfFrame,
  196. /// The device is about to finish rendering a frame
  197. deEndOfFrame,
  198. /// The device has started rendering a frame's field (such as for side-by-side rendering)
  199. deStartOfField,
  200. /// The device is about to finish rendering a frame's field
  201. deEndOfField,
  202. };
  203. typedef Signal <bool (GFXDeviceEventType)> DeviceEventSignal;
  204. static DeviceEventSignal& getDeviceEventSignal();
  205. static GFXDevice *get() { return smGFXDevice; }
  206. static void initConsole();
  207. static bool destroy();
  208. static bool devicePresent() { return (smGFXDevice && smGFXDevice->getAdapterType() != NullDevice); }
  209. private:
  210. /// @name Device management variables
  211. /// @{
  212. static GFXDevice * smGFXDevice; ///< Global GFXDevice
  213. /// @}
  214. //--------------------------------------------------------------------------
  215. // Core GFX interface
  216. //--------------------------------------------------------------------------
  217. public:
  218. enum GFXDeviceRenderStyles
  219. {
  220. RS_Standard = 0,
  221. RS_StereoSideBySide = (1<<0),
  222. };
  223. private:
  224. /// Adapter for this device.
  225. GFXAdapter mAdapter;
  226. protected:
  227. /// List of valid video modes for this device.
  228. Vector<GFXVideoMode> mVideoModes;
  229. /// The CardProfiler for this device.
  230. GFXCardProfiler *mCardProfiler;
  231. /// Head of the resource list.
  232. ///
  233. /// @see GFXResource
  234. GFXResource *mResourceListHead;
  235. /// Set once the device is active.
  236. bool mCanCurrentlyRender;
  237. /// Set if we're in a mode where we want rendering to occur.
  238. bool mAllowRender;
  239. /// The style of rendering that is to be performed, based on GFXDeviceRenderStyles
  240. U32 mCurrentRenderStyle;
  241. /// The current projection offset. May be used during side-by-side rendering, for example.
  242. Point2F mCurrentProjectionOffset;
  243. /// Eye offset used when using a stereo rendering style
  244. Point3F mStereoEyeOffset;
  245. /// This will allow querying to see if a device is initialized and ready to
  246. /// have operations performed on it.
  247. bool mInitialized;
  248. /// This is called before this, or any other device, is deleted in the global destroy()
  249. /// method. It allows the device to clean up anything while everything is still valid.
  250. virtual void preDestroy();
  251. /// Set the adapter that this device is using. For use by GFXInit::createDevice only.
  252. virtual void setAdapter(const GFXAdapter& adapter) { mAdapter = adapter; }
  253. /// Notify GFXDevice that we are initialized
  254. virtual void deviceInited();
  255. public:
  256. GFXDevice();
  257. virtual ~GFXDevice();
  258. /// Initialize this GFXDevice, optionally specifying a platform window to
  259. /// bind to.
  260. virtual void init( const GFXVideoMode &mode, PlatformWindow *window = NULL ) = 0;
  261. /// Returns true if the scene has begun and its
  262. /// safe to make rendering calls.
  263. /// @see beginScene
  264. /// @see endScene
  265. bool canCurrentlyRender() const { return mCanCurrentlyRender; }
  266. void setAllowRender( bool render ) { mAllowRender = render; }
  267. inline bool allowRender() const { return mAllowRender; }
  268. /// Retrieve the current rendering style based on GFXDeviceRenderStyles
  269. U32 getCurrentRenderStyle() const { return mCurrentRenderStyle; }
  270. /// Set the current rendering style, based on GFXDeviceRenderStyles
  271. void setCurrentRenderStyle(U32 style) { mCurrentRenderStyle = style; }
  272. /// Set the current projection offset used during stereo rendering
  273. const Point2F& getCurrentProjectionOffset() { return mCurrentProjectionOffset; }
  274. /// Get the current projection offset used during stereo rendering
  275. void setCurrentProjectionOffset(const Point2F& offset) { mCurrentProjectionOffset = offset; }
  276. /// Get the current eye offset used during stereo rendering
  277. const Point3F& getStereoEyeOffset() { return mStereoEyeOffset; }
  278. /// Set the current eye offset used during stereo rendering
  279. void setStereoEyeOffset(const Point3F& offset) { mStereoEyeOffset = offset; }
  280. GFXCardProfiler* getCardProfiler() const { return mCardProfiler; }
  281. /// Returns active graphics adapter type.
  282. virtual GFXAdapterType getAdapterType()=0;
  283. /// Returns the Adapter that was used to create this device
  284. virtual const GFXAdapter& getAdapter() { return mAdapter; }
  285. /// @}
  286. /// @name Debug Methods
  287. /// @{
  288. virtual void enterDebugEvent(ColorI color, const char *name) = 0;
  289. virtual void leaveDebugEvent() = 0;
  290. virtual void setDebugMarker(ColorI color, const char *name) = 0;
  291. /// @}
  292. /// @name Resource debug methods
  293. /// @{
  294. /// Lists how many of each GFX resource (e.g. textures, texture targets, shaders, etc.) GFX is aware of
  295. /// @param unflaggedOnly If true, this method only counts unflagged resources
  296. virtual void listResources(bool unflaggedOnly);
  297. /// Flags all resources GFX is currently aware of
  298. virtual void flagCurrentResources();
  299. /// Clears the flag on all resources GFX is currently aware of
  300. virtual void clearResourceFlags();
  301. /// Dumps a description of the specified resource types to the console
  302. /// @param resNames A string of space separated class names (e.g. "GFXTextureObject GFXTextureTarget GFXShader")
  303. /// to describe to the console
  304. /// @param file A path to the file to write the descriptions to. If it is NULL or "", descriptions are
  305. /// written to the console.
  306. /// @param unflaggedOnly If true, this method only counts unflagged resources
  307. /// @note resNames is case sensitive because there is no dStristr function.
  308. virtual void describeResources(const char* resName, const char* file, bool unflaggedOnly);
  309. /// Returns the current GFXDeviceStatistics, stats are cleared every ::beginScene call.
  310. GFXDeviceStatistics* getDeviceStatistics() { return &mDeviceStatistics; }
  311. protected:
  312. GFXDeviceStatistics mDeviceStatistics;
  313. /// This is a helper method for describeResourcesToFile. It walks through the
  314. /// GFXResource list and sorts it by item type, putting the resources into the proper vector.
  315. /// @see describeResources
  316. virtual void fillResourceVectors(const char* resNames, bool unflaggedOnly, Vector<GFXResource*> &textureObjects,
  317. Vector<GFXResource*> &textureTargets, Vector<GFXResource*> &windowTargets, Vector<GFXResource*> &vertexBuffers,
  318. Vector<GFXResource*> &primitiveBuffers, Vector<GFXResource*> &fences, Vector<GFXResource*> &cubemaps,
  319. Vector<GFXResource*> &shaders, Vector<GFXResource*> &stateblocks);
  320. public:
  321. /// @}
  322. /// @name Video Mode Functions
  323. /// @{
  324. /// Enumerates the supported video modes of the device
  325. virtual void enumerateVideoModes() = 0;
  326. /// Returns the video mode list.
  327. /// @see GFXVideoMode
  328. const Vector<GFXVideoMode>* const getVideoModeList() const { return &mVideoModes; }
  329. /// Returns the first format from the list which meets all
  330. /// the criteria of the texture profile and query options.
  331. virtual GFXFormat selectSupportedFormat(GFXTextureProfile *profile,
  332. const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter) = 0;
  333. /// @}
  334. //-----------------------------------------------------------------------------
  335. protected:
  336. /// @name State tracking variables
  337. /// @{
  338. /// Set if ANY state is dirty, including matrices or primitive buffers.
  339. bool mStateDirty;
  340. enum TexDirtyType
  341. {
  342. GFXTDT_Normal,
  343. GFXTDT_Cube
  344. };
  345. GFXTexHandle mCurrentTexture[TEXTURE_STAGE_COUNT];
  346. GFXTexHandle mNewTexture[TEXTURE_STAGE_COUNT];
  347. GFXCubemapHandle mCurrentCubemap[TEXTURE_STAGE_COUNT];
  348. GFXCubemapHandle mNewCubemap[TEXTURE_STAGE_COUNT];
  349. TexDirtyType mTexType[TEXTURE_STAGE_COUNT];
  350. bool mTextureDirty[TEXTURE_STAGE_COUNT];
  351. bool mTexturesDirty;
  352. // This maps a GFXStateBlockDesc hash value to a GFXStateBlockRef
  353. typedef Map<U32, GFXStateBlockRef> StateBlockMap;
  354. StateBlockMap mCurrentStateBlocks;
  355. // This tracks whether or not our state block is dirty.
  356. bool mStateBlockDirty;
  357. GFXStateBlockRef mCurrentStateBlock;
  358. GFXStateBlockRef mNewStateBlock;
  359. GFXShaderConstBuffer *mCurrentShaderConstBuffer;
  360. /// A global forced wireframe mode.
  361. static bool smWireframe;
  362. /// The global vsync state.
  363. static bool smDisableVSync;
  364. /// The forced shader model version if non-zero.
  365. static F32 smForcedPixVersion;
  366. /// Disable all hardware occlusion queries causing
  367. /// them to return only the visibile state.
  368. static bool smDisableOcclusionQuery;
  369. /// @}
  370. /// @name Light Tracking
  371. /// @{
  372. GFXLightInfo mCurrentLight[LIGHT_STAGE_COUNT];
  373. bool mCurrentLightEnable[LIGHT_STAGE_COUNT];
  374. bool mLightDirty[LIGHT_STAGE_COUNT];
  375. bool mLightsDirty;
  376. ColorF mGlobalAmbientColor;
  377. bool mGlobalAmbientColorDirty;
  378. /// @}
  379. /// @name Fixed function material tracking
  380. /// @{
  381. GFXLightMaterial mCurrentLightMaterial;
  382. bool mLightMaterialDirty;
  383. /// @}
  384. /// @name Bitmap modulation and color stack
  385. /// @{
  386. ///
  387. /// @}
  388. /// @see getDeviceSwizzle32
  389. Swizzle<U8, 4> *mDeviceSwizzle32;
  390. /// @see getDeviceSwizzle24
  391. Swizzle<U8, 3> *mDeviceSwizzle24;
  392. //-----------------------------------------------------------------------------
  393. /// @name Matrix managing variables
  394. /// @{
  395. ///
  396. MatrixF mWorldMatrix[WORLD_STACK_MAX];
  397. bool mWorldMatrixDirty;
  398. S32 mWorldStackSize;
  399. MatrixF mProjectionMatrix;
  400. bool mProjectionMatrixDirty;
  401. MatrixF mViewMatrix;
  402. bool mViewMatrixDirty;
  403. MatrixF mTextureMatrix[TEXTURE_STAGE_COUNT];
  404. bool mTextureMatrixDirty[TEXTURE_STAGE_COUNT];
  405. bool mTextureMatrixCheckDirty;
  406. /// @}
  407. /// @name Current frustum planes
  408. /// @{
  409. ///
  410. Frustum mFrustum;
  411. //-----------------------------------------------------------------------------
  412. /// @name Stateblock functions
  413. /// @{
  414. /// Called by GFXDevice to create a device specific stateblock
  415. virtual GFXStateBlockRef createStateBlockInternal(const GFXStateBlockDesc& desc) = 0;
  416. /// Called by GFXDevice to actually set a stateblock.
  417. /// @param force If true, set all states
  418. virtual void setStateBlockInternal(GFXStateBlock* block, bool force) = 0;
  419. /// @}
  420. /// Called by base GFXDevice to actually set a const buffer
  421. virtual void setShaderConstBufferInternal(GFXShaderConstBuffer* buffer) = 0;
  422. virtual void setTextureInternal(U32 textureUnit, const GFXTextureObject*texture) = 0;
  423. virtual void setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable) = 0;
  424. virtual void setGlobalAmbientInternal(ColorF color) = 0;
  425. virtual void setLightMaterialInternal(const GFXLightMaterial mat) = 0;
  426. virtual bool beginSceneInternal() = 0;
  427. virtual void endSceneInternal() = 0;
  428. /// @name State Initialization.
  429. /// @{
  430. /// State initialization. This MUST BE CALLED in setVideoMode after the device
  431. /// is created.
  432. virtual void initStates() = 0;
  433. /// @}
  434. //-----------------------------------------------------------------------------
  435. /// This function must be implemented differently per
  436. /// API and it should set ONLY the current matrix.
  437. /// For example, in OpenGL, there should be NO matrix stack
  438. /// activity, all the stack stuff is managed in the GFX layer.
  439. ///
  440. /// OpenGL does not have separate world and
  441. /// view matrices. It has ModelView which is world * view.
  442. /// You must take this into consideration.
  443. ///
  444. /// @param mtype Which matrix to set, world/view/projection
  445. /// @param mat Matrix to assign
  446. virtual void setMatrix( GFXMatrixType mtype, const MatrixF &mat ) = 0;
  447. //-----------------------------------------------------------------------------
  448. protected:
  449. /// @name Buffer Allocation
  450. /// These methods are implemented per-device and are called by the GFX layer
  451. /// when a user calls an alloc
  452. ///
  453. /// @note Primitive Buffers are NOT implemented per device, they wrap index buffers
  454. /// @{
  455. /// This allocates a vertex buffer and returns a pointer to the allocated buffer.
  456. /// This function should not be called directly - rather it should be used by
  457. /// the GFXVertexBufferHandle class.
  458. virtual GFXVertexBuffer *allocVertexBuffer( U32 numVerts,
  459. const GFXVertexFormat *vertexFormat,
  460. U32 vertSize,
  461. GFXBufferType bufferType ) = 0;
  462. /// Called from GFXVertexFormat to allocate the hardware
  463. /// specific vertex declaration for rendering.
  464. virtual GFXVertexDecl* allocVertexDecl( const GFXVertexFormat *vertexFormat ) = 0;
  465. /// Sets the current vertex declaration on the device.
  466. virtual void setVertexDecl( const GFXVertexDecl *decl ) = 0;
  467. /// Sets the vertex buffer on the device.
  468. virtual void setVertexStream( U32 stream, GFXVertexBuffer *buffer ) = 0;
  469. /// Set the vertex stream frequency on the device.
  470. virtual void setVertexStreamFrequency( U32 stream, U32 frequency ) = 0;
  471. /// The maximum number of supported vertex streams which
  472. /// may be more than the device supports.
  473. static const U32 VERTEX_STREAM_COUNT = 4;
  474. StrongRefPtr<GFXVertexBuffer> mCurrentVertexBuffer[VERTEX_STREAM_COUNT];
  475. bool mVertexBufferDirty[VERTEX_STREAM_COUNT];
  476. U32 mVertexBufferFrequency[VERTEX_STREAM_COUNT];
  477. bool mVertexBufferFrequencyDirty[VERTEX_STREAM_COUNT];
  478. const GFXVertexDecl *mCurrVertexDecl;
  479. bool mVertexDeclDirty;
  480. StrongRefPtr<GFXPrimitiveBuffer> mCurrentPrimitiveBuffer;
  481. bool mPrimitiveBufferDirty;
  482. /// This allocates a primitive buffer and returns a pointer to the allocated buffer.
  483. /// A primitive buffer's type argument refers to the index data - the primitive data will
  484. /// always be preserved from call to call.
  485. ///
  486. /// @note All index buffers use unsigned 16-bit indices.
  487. virtual GFXPrimitiveBuffer *allocPrimitiveBuffer( U32 numIndices,
  488. U32 numPrimitives,
  489. GFXBufferType bufferType ) = 0;
  490. /// @}
  491. //---------------------------------------
  492. // SFX buffer
  493. //---------------------------------------
  494. protected:
  495. GFXTexHandle mFrontBuffer[2];
  496. U32 mCurrentFrontBufferIdx;
  497. //---------------------------------------
  498. // Render target related
  499. //---------------------------------------
  500. /// A stack of previously active render targets.
  501. Vector<GFXTargetRef> mRTStack;
  502. /// The current render target which may or may not
  503. /// not be yet activated.
  504. /// @see mRTDirty
  505. GFXTargetRef mCurrentRT;
  506. /// This tracks a previously activated render target
  507. /// which need to be deactivated.
  508. GFXTargetRef mRTDeactivate;
  509. /// This is set when the current and/or deactivate render
  510. /// targets have changed and the device need to update
  511. /// its state on the next draw/clear.
  512. bool mRTDirty;
  513. /// Updates the render targets and viewport in a device
  514. /// specific manner when they are dirty.
  515. virtual void _updateRenderTargets() = 0;
  516. /// The current viewport rect.
  517. RectI mViewport;
  518. /// If true the viewport has been changed and
  519. /// it must be updated on the next draw/clear.
  520. bool mViewportDirty;
  521. public:
  522. /// @name Texture functions
  523. /// @{
  524. protected:
  525. GFXTextureManager * mTextureManager;
  526. public:
  527. virtual GFXCubemap * createCubemap() = 0;
  528. inline GFXTextureManager *getTextureManager()
  529. {
  530. return mTextureManager;
  531. }
  532. ///@}
  533. /// Swizzle to convert 32bpp bitmaps from RGBA to the native device format.
  534. const Swizzle<U8, 4> *getDeviceSwizzle32() const
  535. {
  536. return mDeviceSwizzle32;
  537. }
  538. /// Swizzle to convert 24bpp bitmaps from RGB to the native device format.
  539. const Swizzle<U8, 3> *getDeviceSwizzle24() const
  540. {
  541. return mDeviceSwizzle24;
  542. }
  543. /// @name Render Target functions
  544. /// @{
  545. /// Allocate a target for doing render to texture operations, with no
  546. /// depth/stencil buffer.
  547. virtual GFXTextureTarget *allocRenderToTextureTarget()=0;
  548. /// Allocate a target for a given window.
  549. virtual GFXWindowTarget *allocWindowTarget(PlatformWindow *window)=0;
  550. /// Store the current render target to restore later.
  551. void pushActiveRenderTarget();
  552. /// Restore the previous render target.
  553. void popActiveRenderTarget();
  554. /// Assign a new active render target.
  555. void setActiveRenderTarget( GFXTarget *target, bool updateViewport=true );
  556. /// Returns the current active render target.
  557. inline GFXTarget* getActiveRenderTarget() { return mCurrentRT; }
  558. ///@}
  559. /// @name Shader functions
  560. /// @{
  561. virtual F32 getPixelShaderVersion() const = 0;
  562. virtual void setPixelShaderVersion( F32 version ) = 0;
  563. /// Returns the number of texture samplers that can be used in a shader rendering pass
  564. virtual U32 getNumSamplers() const = 0;
  565. /// Returns the number of simultaneous render targets supported by the device.
  566. virtual U32 getNumRenderTargets() const = 0;
  567. virtual void setShader( GFXShader *shader ) {}
  568. virtual void disableShaders() {}
  569. /// Set the buffer! (Actual set happens on the next draw call, just like textures, state blocks, etc)
  570. void setShaderConstBuffer(GFXShaderConstBuffer* buffer);
  571. /// Creates a new empty shader which must be initialized
  572. /// and deleted by the caller.
  573. /// @see GFXShader::init
  574. virtual GFXShader* createShader() = 0;
  575. /// @}
  576. //-----------------------------------------------------------------------------
  577. /// @name Rendering methods
  578. /// @{
  579. ///
  580. virtual void clear( U32 flags, ColorI color, F32 z, U32 stencil ) = 0;
  581. virtual bool beginScene();
  582. virtual void endScene();
  583. virtual void beginField();
  584. virtual void endField();
  585. virtual GFXTexHandle & getFrontBuffer(){ return mFrontBuffer[mCurrentFrontBufferIdx]; }
  586. void setPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
  587. /// Sets the vertex buffer.
  588. ///
  589. /// When setting the stream 0 vertex buffer it will automatically
  590. /// set its associated vertex format as the active format.
  591. ///
  592. /// @param buffer The vertex buffer or NULL to clear the buffer.
  593. /// @param stream The stream index of the vertex source stream to place the buffer.
  594. /// @param frequency The stream frequency of the vertex buffer.
  595. void setVertexBuffer( GFXVertexBuffer *buffer, U32 stream = 0, U32 frequency = 0 );
  596. /// Sets the current vertex format.
  597. ///
  598. /// This should only be used if the vertex format of the stream 0 vertex
  599. /// buffer is different from the one associated to it. Typically this
  600. /// is used when rendering from multiple vertex streams.
  601. ///
  602. void setVertexFormat( const GFXVertexFormat *vertexFormat );
  603. virtual void drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount ) = 0;
  604. /// The parameters to drawIndexedPrimitive are somewhat complicated. From a raw-data stand point
  605. /// they evaluate to something like the following:
  606. /// @code
  607. /// U16 indicies[] = { 0, 1, 2, 1, 0, 0, 2 };
  608. /// Point3F verts[] = { Point3F( 0.0f, 0.0f, 0.0f ), Point3F( 0.0f, 1.0f, 0.0f ), Point3F( 0.0f, 0.0f, 1.0f ) };
  609. ///
  610. /// GFX->drawIndexedPrimitive( GFXLineList, // Drawing a list of lines, each line is two verts
  611. /// 0, // vertex 0 will be referenced so minIndex = 0
  612. /// 3, // 3 verticies will be used for this draw call
  613. /// 1, // We want index 1 to be the first index used, so indicies 1-6 will be used
  614. /// 3 // Drawing 3 LineList primitives, meaning 6 verts will be drawn
  615. /// );
  616. ///
  617. /// U16 *idxPtr = &indicies[1]; // 1 = startIndex, so the pointer is offset such that:
  618. /// // idxPtr[0] is the same as indicies[1]
  619. ///
  620. /// U32 numVertsToDrawFromBuffer = primitiveCount * 2; // 2 verts define a line in the GFXLineList primitive type (6)
  621. /// @endcode
  622. ///
  623. /// @param primType Type of primitive to draw
  624. ///
  625. /// @param startVertex This defines index zero. Its the offset from the start of
  626. /// the vertex buffer to the first vertex.
  627. ///
  628. /// @param minIndex The smallest index into the vertex stream which will be used for this draw call.
  629. /// This is a zero based index relative to startVertex. It is strictly a performance
  630. /// hint for implementations. No vertex below minIndex will be referenced by this draw
  631. /// call. For device implementors, this should _not_ be used to offset the vertex buffer,
  632. /// or index buffer.
  633. ///
  634. /// @param numVerts The number of verticies which will be referenced in this draw call. This is not
  635. /// the number of verticies which will be drawn. That is a function of 'primType' and
  636. /// 'primitiveCount'.
  637. ///
  638. /// @param startIndex An offset from the start of the index buffer to specify where to start. If
  639. /// 'idxBuffer' is a pointer to an array of integers, this could be written as
  640. /// int *offsetIdx = idxBuffer + startIndex;
  641. ///
  642. /// @param primitiveCount The number of primitives of type 'primType' to draw.
  643. ///
  644. virtual void drawIndexedPrimitive( GFXPrimitiveType primType,
  645. U32 startVertex,
  646. U32 minIndex,
  647. U32 numVerts,
  648. U32 startIndex,
  649. U32 primitiveCount ) = 0;
  650. void drawPrimitive( const GFXPrimitive &prim );
  651. void drawPrimitive( U32 primitiveIndex );
  652. void drawPrimitives();
  653. void drawPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
  654. /// @}
  655. //-----------------------------------------------------------------------------
  656. /// Allocate a fence. The API specific implementation of GFXDevice is responsible
  657. /// to make sure that the proper type is used. GFXGeneralFence should work in
  658. /// all cases.
  659. virtual GFXFence *createFence() = 0;
  660. /// Returns a hardware occlusion query object or NULL
  661. /// if this device does not support them.
  662. virtual GFXOcclusionQuery* createOcclusionQuery() { return NULL; }
  663. /// @name Light Settings
  664. /// NONE of these should be overridden by API implementations
  665. /// because of the state caching stuff.
  666. /// @{
  667. void setLight(U32 stage, GFXLightInfo* light);
  668. void setLightMaterial(GFXLightMaterial mat);
  669. void setGlobalAmbientColor(ColorF color);
  670. /// @}
  671. /// @name Texture State Settings
  672. /// NONE of these should be overridden by API implementations
  673. /// because of the state caching stuff.
  674. /// @{
  675. ///
  676. void setTexture(U32 stage, GFXTextureObject*texture);
  677. void setCubeTexture( U32 stage, GFXCubemap *cubemap );
  678. inline GFXTextureObject* getCurrentTexture( U32 stage ) { return mCurrentTexture[stage]; }
  679. /// @}
  680. /// @name State Block Interface
  681. /// @{
  682. /// Creates a state block object based on the desc passed in. This object
  683. /// represents an immutable state.
  684. virtual GFXStateBlockRef createStateBlock( const GFXStateBlockDesc &desc );
  685. /// Sets the current stateblock (actually activated in ::updateStates)
  686. virtual void setStateBlock( GFXStateBlock *block );
  687. /// This sets a stateblock directly from the description
  688. /// structure. Its acceptable to use this for debug rendering
  689. /// and other low frequency rendering tasks.
  690. virtual void setStateBlockByDesc( const GFXStateBlockDesc &desc );
  691. /// @}
  692. /// @name General state interface
  693. /// @{
  694. /// Sets the dirty Render/Texture/Sampler states from the caching system
  695. void updateStates(bool forceSetAll = false);
  696. /// Returns the forced global wireframe state.
  697. static bool getWireframe() { return smWireframe; }
  698. /// Returns true if the occlusion query is disabled.
  699. static bool getDisableOcclusionQuery() { return smDisableOcclusionQuery; }
  700. /// @}
  701. //-----------------------------------------------------------------------------
  702. /// @name Matrix interface
  703. /// @{
  704. /// Sets the top of the world matrix stack
  705. /// @param newWorld New world matrix to set
  706. void setWorldMatrix( const MatrixF &newWorld );
  707. /// Gets the matrix on the top of the world matrix stack
  708. inline const MatrixF &getWorldMatrix() const { return mWorldMatrix[mWorldStackSize]; }
  709. /// Pushes the world matrix stack and copies the current top
  710. /// matrix to the new top of the stack
  711. void pushWorldMatrix();
  712. /// Pops the world matrix stack
  713. void popWorldMatrix();
  714. /// Sets the projection matrix
  715. /// @param newProj New projection matrix to set
  716. void setProjectionMatrix( const MatrixF &newProj );
  717. /// Gets the projection matrix
  718. inline const MatrixF &getProjectionMatrix() const { return mProjectionMatrix; }
  719. /// Sets the view matrix
  720. /// @param newView New view matrix to set
  721. void setViewMatrix( const MatrixF &newView );
  722. /// Gets the view matrix
  723. inline const MatrixF &getViewMatrix() const { return mViewMatrix; }
  724. /// Multiplies the matrix at the top of the world matrix stack by a matrix
  725. /// and replaces the top of the matrix stack with the result
  726. /// @param mat Matrix to multiply
  727. void multWorld( const MatrixF &mat );
  728. /// Set texture matrix for a sampler
  729. void setTextureMatrix( const U32 stage, const MatrixF &texMat );
  730. /// Set an area of the target to render to.
  731. void setViewport( const RectI &rect );
  732. /// Get the current area of the target we will render to.
  733. const RectI &getViewport() const { return mViewport; }
  734. virtual void setClipRect( const RectI &rect ) = 0;
  735. virtual const RectI &getClipRect() const = 0;
  736. /// Set the projection frustum.
  737. ///
  738. /// @see MathUtils::makeFrustum()
  739. virtual void setFrustum( F32 left, F32 right,
  740. F32 bottom, F32 top,
  741. F32 nearPlane, F32 farPlane,
  742. bool bRotate = true);
  743. ///
  744. virtual void setFrustum( const Frustum& frust,
  745. bool bRotate = true );
  746. /// Get the projection frustum.
  747. void getFrustum( F32 *left,
  748. F32 *right,
  749. F32 *bottom,
  750. F32 *top,
  751. F32 *nearPlane,
  752. F32 *farPlane,
  753. bool *isOrtho ) const;
  754. /// Get the projection frustum.
  755. const Frustum& getFrustum() const { return mFrustum; }
  756. /// This will construct and apply an orthographic projection matrix with the provided parameters
  757. /// @param doRotate If set to true, the resulting matrix will be rotated PI/2 around the X axis
  758. // for support in tsShapeInstance. You probably want to leave this as 'false'.
  759. void setOrtho(F32 left, F32 right, F32 bottom, F32 top, F32 nearPlane, F32 farPlane, bool doRotate = false);
  760. /// Return true if the current frustum uses orthographic projection rather than perspective projection.
  761. bool isFrustumOrtho() const { return mFrustum.isOrtho(); }
  762. /// @}
  763. /// Returns the scale for converting world space
  764. /// units to screen space units... aka pixels.
  765. ///
  766. /// This is the true scale which is best used for GUI
  767. /// drawing. For doing lod calculations you should be
  768. /// using the functions in SceneState which is adjusted
  769. /// for special cases like shadows and reflections.
  770. ///
  771. /// @see SceneState::getWorldToScreenScale()
  772. /// @see SceneState::projectRadius()
  773. ///
  774. Point2F getWorldToScreenScale() const;
  775. public:
  776. enum GenericShaderType
  777. {
  778. GSColor = 0,
  779. GSTexture,
  780. GSModColorTexture,
  781. GSAddColorTexture,
  782. GSTargetRestore,
  783. GS_COUNT
  784. };
  785. /// This is a helper function to set a default shader for rendering GUI elements
  786. /// on systems which do not support fixed-function operations as well as for
  787. /// things which need just generic position/texture/color shaders
  788. ///
  789. /// @param type Type of generic shader, add your own if you need
  790. virtual void setupGenericShaders( GenericShaderType type = GSColor ) {};
  791. /// Get the fill convention for this device
  792. virtual F32 getFillConventionOffset() const = 0;
  793. virtual U32 getMaxDynamicVerts() = 0;
  794. virtual U32 getMaxDynamicIndices() = 0;
  795. virtual void doParanoidStateCheck(){};
  796. /// Get access to this device's drawing utility class.
  797. GFXDrawUtil *getDrawUtil();
  798. #ifndef TORQUE_SHIPPING
  799. /// This is a method designed for debugging. It will allow you to dump the states
  800. /// in the render manager out to a file so that it can be diffed and examined.
  801. void dumpStates( const char *fileName ) const;
  802. #else
  803. void dumpStates( const char *fileName ) const {};
  804. #endif
  805. protected:
  806. GFXDrawUtil *mDrawer;
  807. };
  808. //-----------------------------------------------------------------------------
  809. // Matrix interface
  810. inline void GFXDevice::setWorldMatrix( const MatrixF &newWorld )
  811. {
  812. mWorldMatrixDirty = true;
  813. mStateDirty = true;
  814. mWorldMatrix[mWorldStackSize] = newWorld;
  815. }
  816. inline void GFXDevice::pushWorldMatrix()
  817. {
  818. mWorldMatrixDirty = true;
  819. mStateDirty = true;
  820. mWorldStackSize++;
  821. AssertFatal( mWorldStackSize < WORLD_STACK_MAX, "GFX: Exceeded world matrix stack size" );
  822. mWorldMatrix[mWorldStackSize] = mWorldMatrix[mWorldStackSize - 1];
  823. }
  824. inline void GFXDevice::popWorldMatrix()
  825. {
  826. mWorldMatrixDirty = true;
  827. mStateDirty = true;
  828. mWorldStackSize--;
  829. AssertFatal( mWorldStackSize >= 0, "GFX: Negative WorldStackSize!" );
  830. }
  831. inline void GFXDevice::multWorld( const MatrixF &mat )
  832. {
  833. mWorldMatrixDirty = true;
  834. mStateDirty = true;
  835. mWorldMatrix[mWorldStackSize].mul(mat);
  836. }
  837. inline void GFXDevice::setProjectionMatrix( const MatrixF &newProj )
  838. {
  839. mProjectionMatrixDirty = true;
  840. mStateDirty = true;
  841. mProjectionMatrix = newProj;
  842. }
  843. inline void GFXDevice::setViewMatrix( const MatrixF &newView )
  844. {
  845. mStateDirty = true;
  846. mViewMatrixDirty = true;
  847. mViewMatrix = newView;
  848. }
  849. inline void GFXDevice::setTextureMatrix( const U32 stage, const MatrixF &texMat )
  850. {
  851. AssertFatal( stage < TEXTURE_STAGE_COUNT, "Out of range texture sampler" );
  852. mStateDirty = true;
  853. mTextureMatrixDirty[stage] = true;
  854. mTextureMatrix[stage] = texMat;
  855. mTextureMatrixCheckDirty = true;
  856. }
  857. //-----------------------------------------------------------------------------
  858. // Buffer management
  859. inline void GFXDevice::setVertexBuffer( GFXVertexBuffer *buffer, U32 stream, U32 frequency )
  860. {
  861. AssertFatal( stream < VERTEX_STREAM_COUNT, "GFXDevice::setVertexBuffer - Bad stream index!" );
  862. if ( buffer && stream == 0 )
  863. setVertexFormat( &buffer->mVertexFormat );
  864. if ( buffer != mCurrentVertexBuffer[stream] )
  865. {
  866. mCurrentVertexBuffer[stream] = buffer;
  867. mVertexBufferDirty[stream] = true;
  868. mStateDirty = true;
  869. }
  870. if ( mVertexBufferFrequency[stream] != frequency )
  871. {
  872. mVertexBufferFrequency[stream] = frequency;
  873. mVertexBufferFrequencyDirty[stream] = true;
  874. mStateDirty = true;
  875. }
  876. }
  877. inline void GFXDevice::setVertexFormat( const GFXVertexFormat *vertexFormat )
  878. {
  879. if ( vertexFormat->getDecl() == mCurrVertexDecl )
  880. return;
  881. mCurrVertexDecl = vertexFormat->getDecl();
  882. mVertexDeclDirty = true;
  883. mStateDirty = true;
  884. }
  885. #endif // _GFXDEVICE_H_