gfxDevice.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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. };
  199. typedef Signal <bool (GFXDeviceEventType)> DeviceEventSignal;
  200. static DeviceEventSignal& getDeviceEventSignal();
  201. static GFXDevice *get() { return smGFXDevice; }
  202. static void initConsole();
  203. static bool destroy();
  204. static bool devicePresent() { return (smGFXDevice && smGFXDevice->getAdapterType() != NullDevice); }
  205. private:
  206. /// @name Device management variables
  207. /// @{
  208. static GFXDevice * smGFXDevice; ///< Global GFXDevice
  209. /// @}
  210. //--------------------------------------------------------------------------
  211. // Core GFX interface
  212. //--------------------------------------------------------------------------
  213. private:
  214. /// Adapter for this device.
  215. GFXAdapter mAdapter;
  216. protected:
  217. /// List of valid video modes for this device.
  218. Vector<GFXVideoMode> mVideoModes;
  219. /// The CardProfiler for this device.
  220. GFXCardProfiler *mCardProfiler;
  221. /// Head of the resource list.
  222. ///
  223. /// @see GFXResource
  224. GFXResource *mResourceListHead;
  225. /// Set once the device is active.
  226. bool mCanCurrentlyRender;
  227. /// Set if we're in a mode where we want rendering to occur.
  228. bool mAllowRender;
  229. /// This will allow querying to see if a device is initialized and ready to
  230. /// have operations performed on it.
  231. bool mInitialized;
  232. /// This is called before this, or any other device, is deleted in the global destroy()
  233. /// method. It allows the device to clean up anything while everything is still valid.
  234. virtual void preDestroy();
  235. /// Set the adapter that this device is using. For use by GFXInit::createDevice only.
  236. virtual void setAdapter(const GFXAdapter& adapter) { mAdapter = adapter; }
  237. /// Notify GFXDevice that we are initialized
  238. virtual void deviceInited();
  239. public:
  240. GFXDevice();
  241. virtual ~GFXDevice();
  242. /// Initialize this GFXDevice, optionally specifying a platform window to
  243. /// bind to.
  244. virtual void init( const GFXVideoMode &mode, PlatformWindow *window = NULL ) = 0;
  245. /// Returns true if the scene has begun and its
  246. /// safe to make rendering calls.
  247. /// @see beginScene
  248. /// @see endScene
  249. bool canCurrentlyRender() const { return mCanCurrentlyRender; }
  250. void setAllowRender( bool render ) { mAllowRender = render; }
  251. inline bool allowRender() const { return mAllowRender; }
  252. GFXCardProfiler* getCardProfiler() const { return mCardProfiler; }
  253. /// Returns active graphics adapter type.
  254. virtual GFXAdapterType getAdapterType()=0;
  255. /// Returns the Adapter that was used to create this device
  256. virtual const GFXAdapter& getAdapter() { return mAdapter; }
  257. /// @}
  258. /// @name Debug Methods
  259. /// @{
  260. virtual void enterDebugEvent(ColorI color, const char *name) = 0;
  261. virtual void leaveDebugEvent() = 0;
  262. virtual void setDebugMarker(ColorI color, const char *name) = 0;
  263. /// @}
  264. /// @name Resource debug methods
  265. /// @{
  266. /// Lists how many of each GFX resource (e.g. textures, texture targets, shaders, etc.) GFX is aware of
  267. /// @param unflaggedOnly If true, this method only counts unflagged resources
  268. virtual void listResources(bool unflaggedOnly);
  269. /// Flags all resources GFX is currently aware of
  270. virtual void flagCurrentResources();
  271. /// Clears the flag on all resources GFX is currently aware of
  272. virtual void clearResourceFlags();
  273. /// Dumps a description of the specified resource types to the console
  274. /// @param resNames A string of space separated class names (e.g. "GFXTextureObject GFXTextureTarget GFXShader")
  275. /// to describe to the console
  276. /// @param file A path to the file to write the descriptions to. If it is NULL or "", descriptions are
  277. /// written to the console.
  278. /// @param unflaggedOnly If true, this method only counts unflagged resources
  279. /// @note resNames is case sensitive because there is no dStristr function.
  280. virtual void describeResources(const char* resName, const char* file, bool unflaggedOnly);
  281. /// Returns the current GFXDeviceStatistics, stats are cleared every ::beginScene call.
  282. GFXDeviceStatistics* getDeviceStatistics() { return &mDeviceStatistics; }
  283. protected:
  284. GFXDeviceStatistics mDeviceStatistics;
  285. /// This is a helper method for describeResourcesToFile. It walks through the
  286. /// GFXResource list and sorts it by item type, putting the resources into the proper vector.
  287. /// @see describeResources
  288. virtual void fillResourceVectors(const char* resNames, bool unflaggedOnly, Vector<GFXResource*> &textureObjects,
  289. Vector<GFXResource*> &textureTargets, Vector<GFXResource*> &windowTargets, Vector<GFXResource*> &vertexBuffers,
  290. Vector<GFXResource*> &primitiveBuffers, Vector<GFXResource*> &fences, Vector<GFXResource*> &cubemaps,
  291. Vector<GFXResource*> &shaders, Vector<GFXResource*> &stateblocks);
  292. public:
  293. /// @}
  294. /// @name Video Mode Functions
  295. /// @{
  296. /// Enumerates the supported video modes of the device
  297. virtual void enumerateVideoModes() = 0;
  298. /// Returns the video mode list.
  299. /// @see GFXVideoMode
  300. const Vector<GFXVideoMode>* const getVideoModeList() const { return &mVideoModes; }
  301. /// Returns the first format from the list which meets all
  302. /// the criteria of the texture profile and query options.
  303. virtual GFXFormat selectSupportedFormat(GFXTextureProfile *profile,
  304. const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter) = 0;
  305. /// @}
  306. //-----------------------------------------------------------------------------
  307. protected:
  308. /// @name State tracking variables
  309. /// @{
  310. /// Set if ANY state is dirty, including matrices or primitive buffers.
  311. bool mStateDirty;
  312. enum TexDirtyType
  313. {
  314. GFXTDT_Normal,
  315. GFXTDT_Cube
  316. };
  317. GFXTexHandle mCurrentTexture[TEXTURE_STAGE_COUNT];
  318. GFXTexHandle mNewTexture[TEXTURE_STAGE_COUNT];
  319. GFXCubemapHandle mCurrentCubemap[TEXTURE_STAGE_COUNT];
  320. GFXCubemapHandle mNewCubemap[TEXTURE_STAGE_COUNT];
  321. TexDirtyType mTexType[TEXTURE_STAGE_COUNT];
  322. bool mTextureDirty[TEXTURE_STAGE_COUNT];
  323. bool mTexturesDirty;
  324. // This maps a GFXStateBlockDesc hash value to a GFXStateBlockRef
  325. typedef Map<U32, GFXStateBlockRef> StateBlockMap;
  326. StateBlockMap mCurrentStateBlocks;
  327. // This tracks whether or not our state block is dirty.
  328. bool mStateBlockDirty;
  329. GFXStateBlockRef mCurrentStateBlock;
  330. GFXStateBlockRef mNewStateBlock;
  331. GFXShaderConstBuffer *mCurrentShaderConstBuffer;
  332. /// A global forced wireframe mode.
  333. static bool smWireframe;
  334. /// The global vsync state.
  335. static bool smDisableVSync;
  336. /// The forced shader model version if non-zero.
  337. static F32 smForcedPixVersion;
  338. /// Disable all hardware occlusion queries causing
  339. /// them to return only the visibile state.
  340. static bool smDisableOcclusionQuery;
  341. /// @}
  342. /// @name Light Tracking
  343. /// @{
  344. GFXLightInfo mCurrentLight[LIGHT_STAGE_COUNT];
  345. bool mCurrentLightEnable[LIGHT_STAGE_COUNT];
  346. bool mLightDirty[LIGHT_STAGE_COUNT];
  347. bool mLightsDirty;
  348. ColorF mGlobalAmbientColor;
  349. bool mGlobalAmbientColorDirty;
  350. /// @}
  351. /// @name Fixed function material tracking
  352. /// @{
  353. GFXLightMaterial mCurrentLightMaterial;
  354. bool mLightMaterialDirty;
  355. /// @}
  356. /// @name Bitmap modulation and color stack
  357. /// @{
  358. ///
  359. /// @}
  360. /// @see getDeviceSwizzle32
  361. Swizzle<U8, 4> *mDeviceSwizzle32;
  362. /// @see getDeviceSwizzle24
  363. Swizzle<U8, 3> *mDeviceSwizzle24;
  364. //-----------------------------------------------------------------------------
  365. /// @name Matrix managing variables
  366. /// @{
  367. ///
  368. MatrixF mWorldMatrix[WORLD_STACK_MAX];
  369. bool mWorldMatrixDirty;
  370. S32 mWorldStackSize;
  371. MatrixF mProjectionMatrix;
  372. bool mProjectionMatrixDirty;
  373. MatrixF mViewMatrix;
  374. bool mViewMatrixDirty;
  375. MatrixF mTextureMatrix[TEXTURE_STAGE_COUNT];
  376. bool mTextureMatrixDirty[TEXTURE_STAGE_COUNT];
  377. bool mTextureMatrixCheckDirty;
  378. /// @}
  379. /// @name Current frustum planes
  380. /// @{
  381. ///
  382. Frustum mFrustum;
  383. //-----------------------------------------------------------------------------
  384. /// @name Stateblock functions
  385. /// @{
  386. /// Called by GFXDevice to create a device specific stateblock
  387. virtual GFXStateBlockRef createStateBlockInternal(const GFXStateBlockDesc& desc) = 0;
  388. /// Called by GFXDevice to actually set a stateblock.
  389. /// @param force If true, set all states
  390. virtual void setStateBlockInternal(GFXStateBlock* block, bool force) = 0;
  391. /// @}
  392. /// Called by base GFXDevice to actually set a const buffer
  393. virtual void setShaderConstBufferInternal(GFXShaderConstBuffer* buffer) = 0;
  394. virtual void setTextureInternal(U32 textureUnit, const GFXTextureObject*texture) = 0;
  395. virtual void setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable) = 0;
  396. virtual void setGlobalAmbientInternal(ColorF color) = 0;
  397. virtual void setLightMaterialInternal(const GFXLightMaterial mat) = 0;
  398. virtual bool beginSceneInternal() = 0;
  399. virtual void endSceneInternal() = 0;
  400. /// @name State Initialization.
  401. /// @{
  402. /// State initialization. This MUST BE CALLED in setVideoMode after the device
  403. /// is created.
  404. virtual void initStates() = 0;
  405. /// @}
  406. //-----------------------------------------------------------------------------
  407. /// This function must be implemented differently per
  408. /// API and it should set ONLY the current matrix.
  409. /// For example, in OpenGL, there should be NO matrix stack
  410. /// activity, all the stack stuff is managed in the GFX layer.
  411. ///
  412. /// OpenGL does not have separate world and
  413. /// view matrices. It has ModelView which is world * view.
  414. /// You must take this into consideration.
  415. ///
  416. /// @param mtype Which matrix to set, world/view/projection
  417. /// @param mat Matrix to assign
  418. virtual void setMatrix( GFXMatrixType mtype, const MatrixF &mat ) = 0;
  419. //-----------------------------------------------------------------------------
  420. protected:
  421. /// @name Buffer Allocation
  422. /// These methods are implemented per-device and are called by the GFX layer
  423. /// when a user calls an alloc
  424. ///
  425. /// @note Primitive Buffers are NOT implemented per device, they wrap index buffers
  426. /// @{
  427. /// This allocates a vertex buffer and returns a pointer to the allocated buffer.
  428. /// This function should not be called directly - rather it should be used by
  429. /// the GFXVertexBufferHandle class.
  430. virtual GFXVertexBuffer *allocVertexBuffer( U32 numVerts,
  431. const GFXVertexFormat *vertexFormat,
  432. U32 vertSize,
  433. GFXBufferType bufferType ) = 0;
  434. /// Called from GFXVertexFormat to allocate the hardware
  435. /// specific vertex declaration for rendering.
  436. virtual GFXVertexDecl* allocVertexDecl( const GFXVertexFormat *vertexFormat ) = 0;
  437. /// Sets the current vertex declaration on the device.
  438. virtual void setVertexDecl( const GFXVertexDecl *decl ) = 0;
  439. /// Sets the vertex buffer on the device.
  440. virtual void setVertexStream( U32 stream, GFXVertexBuffer *buffer ) = 0;
  441. /// Set the vertex stream frequency on the device.
  442. virtual void setVertexStreamFrequency( U32 stream, U32 frequency ) = 0;
  443. /// The maximum number of supported vertex streams which
  444. /// may be more than the device supports.
  445. static const U32 VERTEX_STREAM_COUNT = 4;
  446. StrongRefPtr<GFXVertexBuffer> mCurrentVertexBuffer[VERTEX_STREAM_COUNT];
  447. bool mVertexBufferDirty[VERTEX_STREAM_COUNT];
  448. U32 mVertexBufferFrequency[VERTEX_STREAM_COUNT];
  449. bool mVertexBufferFrequencyDirty[VERTEX_STREAM_COUNT];
  450. const GFXVertexDecl *mCurrVertexDecl;
  451. bool mVertexDeclDirty;
  452. StrongRefPtr<GFXPrimitiveBuffer> mCurrentPrimitiveBuffer;
  453. bool mPrimitiveBufferDirty;
  454. /// This allocates a primitive buffer and returns a pointer to the allocated buffer.
  455. /// A primitive buffer's type argument refers to the index data - the primitive data will
  456. /// always be preserved from call to call.
  457. ///
  458. /// @note All index buffers use unsigned 16-bit indices.
  459. virtual GFXPrimitiveBuffer *allocPrimitiveBuffer( U32 numIndices,
  460. U32 numPrimitives,
  461. GFXBufferType bufferType ) = 0;
  462. /// @}
  463. //---------------------------------------
  464. // SFX buffer
  465. //---------------------------------------
  466. protected:
  467. GFXTexHandle mFrontBuffer[2];
  468. U32 mCurrentFrontBufferIdx;
  469. //---------------------------------------
  470. // Render target related
  471. //---------------------------------------
  472. /// A stack of previously active render targets.
  473. Vector<GFXTargetRef> mRTStack;
  474. /// The current render target which may or may not
  475. /// not be yet activated.
  476. /// @see mRTDirty
  477. GFXTargetRef mCurrentRT;
  478. /// This tracks a previously activated render target
  479. /// which need to be deactivated.
  480. GFXTargetRef mRTDeactivate;
  481. /// This is set when the current and/or deactivate render
  482. /// targets have changed and the device need to update
  483. /// its state on the next draw/clear.
  484. bool mRTDirty;
  485. /// Updates the render targets and viewport in a device
  486. /// specific manner when they are dirty.
  487. virtual void _updateRenderTargets() = 0;
  488. /// The current viewport rect.
  489. RectI mViewport;
  490. /// If true the viewport has been changed and
  491. /// it must be updated on the next draw/clear.
  492. bool mViewportDirty;
  493. public:
  494. /// @name Texture functions
  495. /// @{
  496. protected:
  497. GFXTextureManager * mTextureManager;
  498. public:
  499. virtual GFXCubemap * createCubemap() = 0;
  500. inline GFXTextureManager *getTextureManager()
  501. {
  502. return mTextureManager;
  503. }
  504. ///@}
  505. /// Swizzle to convert 32bpp bitmaps from RGBA to the native device format.
  506. const Swizzle<U8, 4> *getDeviceSwizzle32() const
  507. {
  508. return mDeviceSwizzle32;
  509. }
  510. /// Swizzle to convert 24bpp bitmaps from RGB to the native device format.
  511. const Swizzle<U8, 3> *getDeviceSwizzle24() const
  512. {
  513. return mDeviceSwizzle24;
  514. }
  515. /// @name Render Target functions
  516. /// @{
  517. /// Allocate a target for doing render to texture operations, with no
  518. /// depth/stencil buffer.
  519. virtual GFXTextureTarget *allocRenderToTextureTarget()=0;
  520. /// Allocate a target for a given window.
  521. virtual GFXWindowTarget *allocWindowTarget(PlatformWindow *window)=0;
  522. /// Store the current render target to restore later.
  523. void pushActiveRenderTarget();
  524. /// Restore the previous render target.
  525. void popActiveRenderTarget();
  526. /// Assign a new active render target.
  527. void setActiveRenderTarget( GFXTarget *target );
  528. /// Returns the current active render target.
  529. inline GFXTarget* getActiveRenderTarget() { return mCurrentRT; }
  530. ///@}
  531. /// @name Shader functions
  532. /// @{
  533. virtual F32 getPixelShaderVersion() const = 0;
  534. virtual void setPixelShaderVersion( F32 version ) = 0;
  535. /// Returns the number of texture samplers that can be used in a shader rendering pass
  536. virtual U32 getNumSamplers() const = 0;
  537. /// Returns the number of simultaneous render targets supported by the device.
  538. virtual U32 getNumRenderTargets() const = 0;
  539. virtual void setShader( GFXShader *shader ) {}
  540. virtual void disableShaders() {}
  541. /// Set the buffer! (Actual set happens on the next draw call, just like textures, state blocks, etc)
  542. void setShaderConstBuffer(GFXShaderConstBuffer* buffer);
  543. /// Creates a new empty shader which must be initialized
  544. /// and deleted by the caller.
  545. /// @see GFXShader::init
  546. virtual GFXShader* createShader() = 0;
  547. /// @}
  548. //-----------------------------------------------------------------------------
  549. /// @name Rendering methods
  550. /// @{
  551. ///
  552. virtual void clear( U32 flags, ColorI color, F32 z, U32 stencil ) = 0;
  553. virtual bool beginScene();
  554. virtual void endScene();
  555. virtual GFXTexHandle & getFrontBuffer(){ return mFrontBuffer[mCurrentFrontBufferIdx]; }
  556. void setPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
  557. /// Sets the vertex buffer.
  558. ///
  559. /// When setting the stream 0 vertex buffer it will automatically
  560. /// set its associated vertex format as the active format.
  561. ///
  562. /// @param buffer The vertex buffer or NULL to clear the buffer.
  563. /// @param stream The stream index of the vertex source stream to place the buffer.
  564. /// @param frequency The stream frequency of the vertex buffer.
  565. void setVertexBuffer( GFXVertexBuffer *buffer, U32 stream = 0, U32 frequency = 0 );
  566. /// Sets the current vertex format.
  567. ///
  568. /// This should only be used if the vertex format of the stream 0 vertex
  569. /// buffer is different from the one associated to it. Typically this
  570. /// is used when rendering from multiple vertex streams.
  571. ///
  572. void setVertexFormat( const GFXVertexFormat *vertexFormat );
  573. virtual void drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount ) = 0;
  574. /// The parameters to drawIndexedPrimitive are somewhat complicated. From a raw-data stand point
  575. /// they evaluate to something like the following:
  576. /// @code
  577. /// U16 indicies[] = { 0, 1, 2, 1, 0, 0, 2 };
  578. /// Point3F verts[] = { Point3F( 0.0f, 0.0f, 0.0f ), Point3F( 0.0f, 1.0f, 0.0f ), Point3F( 0.0f, 0.0f, 1.0f ) };
  579. ///
  580. /// GFX->drawIndexedPrimitive( GFXLineList, // Drawing a list of lines, each line is two verts
  581. /// 0, // vertex 0 will be referenced so minIndex = 0
  582. /// 3, // 3 verticies will be used for this draw call
  583. /// 1, // We want index 1 to be the first index used, so indicies 1-6 will be used
  584. /// 3 // Drawing 3 LineList primitives, meaning 6 verts will be drawn
  585. /// );
  586. ///
  587. /// U16 *idxPtr = &indicies[1]; // 1 = startIndex, so the pointer is offset such that:
  588. /// // idxPtr[0] is the same as indicies[1]
  589. ///
  590. /// U32 numVertsToDrawFromBuffer = primitiveCount * 2; // 2 verts define a line in the GFXLineList primitive type (6)
  591. /// @endcode
  592. ///
  593. /// @param primType Type of primitive to draw
  594. ///
  595. /// @param startVertex This defines index zero. Its the offset from the start of
  596. /// the vertex buffer to the first vertex.
  597. ///
  598. /// @param minIndex The smallest index into the vertex stream which will be used for this draw call.
  599. /// This is a zero based index relative to startVertex. It is strictly a performance
  600. /// hint for implementations. No vertex below minIndex will be referenced by this draw
  601. /// call. For device implementors, this should _not_ be used to offset the vertex buffer,
  602. /// or index buffer.
  603. ///
  604. /// @param numVerts The number of verticies which will be referenced in this draw call. This is not
  605. /// the number of verticies which will be drawn. That is a function of 'primType' and
  606. /// 'primitiveCount'.
  607. ///
  608. /// @param startIndex An offset from the start of the index buffer to specify where to start. If
  609. /// 'idxBuffer' is a pointer to an array of integers, this could be written as
  610. /// int *offsetIdx = idxBuffer + startIndex;
  611. ///
  612. /// @param primitiveCount The number of primitives of type 'primType' to draw.
  613. ///
  614. virtual void drawIndexedPrimitive( GFXPrimitiveType primType,
  615. U32 startVertex,
  616. U32 minIndex,
  617. U32 numVerts,
  618. U32 startIndex,
  619. U32 primitiveCount ) = 0;
  620. void drawPrimitive( const GFXPrimitive &prim );
  621. void drawPrimitive( U32 primitiveIndex );
  622. void drawPrimitives();
  623. void drawPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
  624. /// @}
  625. //-----------------------------------------------------------------------------
  626. /// Allocate a fence. The API specific implementation of GFXDevice is responsible
  627. /// to make sure that the proper type is used. GFXGeneralFence should work in
  628. /// all cases.
  629. virtual GFXFence *createFence() = 0;
  630. /// Returns a hardware occlusion query object or NULL
  631. /// if this device does not support them.
  632. virtual GFXOcclusionQuery* createOcclusionQuery() { return NULL; }
  633. /// @name Light Settings
  634. /// NONE of these should be overridden by API implementations
  635. /// because of the state caching stuff.
  636. /// @{
  637. void setLight(U32 stage, GFXLightInfo* light);
  638. void setLightMaterial(GFXLightMaterial mat);
  639. void setGlobalAmbientColor(ColorF color);
  640. /// @}
  641. /// @name Texture State Settings
  642. /// NONE of these should be overridden by API implementations
  643. /// because of the state caching stuff.
  644. /// @{
  645. ///
  646. void setTexture(U32 stage, GFXTextureObject*texture);
  647. void setCubeTexture( U32 stage, GFXCubemap *cubemap );
  648. inline GFXTextureObject* getCurrentTexture( U32 stage ) { return mCurrentTexture[stage]; }
  649. /// @}
  650. /// @name State Block Interface
  651. /// @{
  652. /// Creates a state block object based on the desc passed in. This object
  653. /// represents an immutable state.
  654. virtual GFXStateBlockRef createStateBlock( const GFXStateBlockDesc &desc );
  655. /// Sets the current stateblock (actually activated in ::updateStates)
  656. virtual void setStateBlock( GFXStateBlock *block );
  657. /// This sets a stateblock directly from the description
  658. /// structure. Its acceptable to use this for debug rendering
  659. /// and other low frequency rendering tasks.
  660. virtual void setStateBlockByDesc( const GFXStateBlockDesc &desc );
  661. /// @}
  662. /// @name General state interface
  663. /// @{
  664. /// Sets the dirty Render/Texture/Sampler states from the caching system
  665. void updateStates(bool forceSetAll = false);
  666. /// Returns the forced global wireframe state.
  667. static bool getWireframe() { return smWireframe; }
  668. /// Returns true if the occlusion query is disabled.
  669. static bool getDisableOcclusionQuery() { return smDisableOcclusionQuery; }
  670. /// @}
  671. //-----------------------------------------------------------------------------
  672. /// @name Matrix interface
  673. /// @{
  674. /// Sets the top of the world matrix stack
  675. /// @param newWorld New world matrix to set
  676. void setWorldMatrix( const MatrixF &newWorld );
  677. /// Gets the matrix on the top of the world matrix stack
  678. inline const MatrixF &getWorldMatrix() const { return mWorldMatrix[mWorldStackSize]; }
  679. /// Pushes the world matrix stack and copies the current top
  680. /// matrix to the new top of the stack
  681. void pushWorldMatrix();
  682. /// Pops the world matrix stack
  683. void popWorldMatrix();
  684. /// Sets the projection matrix
  685. /// @param newProj New projection matrix to set
  686. void setProjectionMatrix( const MatrixF &newProj );
  687. /// Gets the projection matrix
  688. inline const MatrixF &getProjectionMatrix() const { return mProjectionMatrix; }
  689. /// Sets the view matrix
  690. /// @param newView New view matrix to set
  691. void setViewMatrix( const MatrixF &newView );
  692. /// Gets the view matrix
  693. inline const MatrixF &getViewMatrix() const { return mViewMatrix; }
  694. /// Multiplies the matrix at the top of the world matrix stack by a matrix
  695. /// and replaces the top of the matrix stack with the result
  696. /// @param mat Matrix to multiply
  697. void multWorld( const MatrixF &mat );
  698. /// Set texture matrix for a sampler
  699. void setTextureMatrix( const U32 stage, const MatrixF &texMat );
  700. /// Set an area of the target to render to.
  701. void setViewport( const RectI &rect );
  702. /// Get the current area of the target we will render to.
  703. const RectI &getViewport() const { return mViewport; }
  704. virtual void setClipRect( const RectI &rect ) = 0;
  705. virtual const RectI &getClipRect() const = 0;
  706. /// Set the projection frustum.
  707. ///
  708. /// @see MathUtils::makeFrustum()
  709. virtual void setFrustum( F32 left, F32 right,
  710. F32 bottom, F32 top,
  711. F32 nearPlane, F32 farPlane,
  712. bool bRotate = true);
  713. ///
  714. virtual void setFrustum( const Frustum& frust,
  715. bool bRotate = true );
  716. /// Get the projection frustum.
  717. void getFrustum( F32 *left,
  718. F32 *right,
  719. F32 *bottom,
  720. F32 *top,
  721. F32 *nearPlane,
  722. F32 *farPlane,
  723. bool *isOrtho ) const;
  724. /// Get the projection frustum.
  725. const Frustum& getFrustum() const { return mFrustum; }
  726. /// This will construct and apply an orthographic projection matrix with the provided parameters
  727. /// @param doRotate If set to true, the resulting matrix will be rotated PI/2 around the X axis
  728. // for support in tsShapeInstance. You probably want to leave this as 'false'.
  729. void setOrtho(F32 left, F32 right, F32 bottom, F32 top, F32 nearPlane, F32 farPlane, bool doRotate = false);
  730. /// Return true if the current frustum uses orthographic projection rather than perspective projection.
  731. bool isFrustumOrtho() const { return mFrustum.isOrtho(); }
  732. /// @}
  733. /// Returns the scale for converting world space
  734. /// units to screen space units... aka pixels.
  735. ///
  736. /// This is the true scale which is best used for GUI
  737. /// drawing. For doing lod calculations you should be
  738. /// using the functions in SceneState which is adjusted
  739. /// for special cases like shadows and reflections.
  740. ///
  741. /// @see SceneState::getWorldToScreenScale()
  742. /// @see SceneState::projectRadius()
  743. ///
  744. Point2F getWorldToScreenScale() const;
  745. public:
  746. enum GenericShaderType
  747. {
  748. GSColor = 0,
  749. GSTexture,
  750. GSModColorTexture,
  751. GSAddColorTexture,
  752. GSTargetRestore,
  753. GS_COUNT
  754. };
  755. /// This is a helper function to set a default shader for rendering GUI elements
  756. /// on systems which do not support fixed-function operations as well as for
  757. /// things which need just generic position/texture/color shaders
  758. ///
  759. /// @param type Type of generic shader, add your own if you need
  760. virtual void setupGenericShaders( GenericShaderType type = GSColor ) {};
  761. /// Get the fill convention for this device
  762. virtual F32 getFillConventionOffset() const = 0;
  763. virtual U32 getMaxDynamicVerts() = 0;
  764. virtual U32 getMaxDynamicIndices() = 0;
  765. virtual void doParanoidStateCheck(){};
  766. /// Get access to this device's drawing utility class.
  767. GFXDrawUtil *getDrawUtil();
  768. #ifndef TORQUE_SHIPPING
  769. /// This is a method designed for debugging. It will allow you to dump the states
  770. /// in the render manager out to a file so that it can be diffed and examined.
  771. void dumpStates( const char *fileName ) const;
  772. #else
  773. void dumpStates( const char *fileName ) const {};
  774. #endif
  775. protected:
  776. GFXDrawUtil *mDrawer;
  777. };
  778. //-----------------------------------------------------------------------------
  779. // Matrix interface
  780. inline void GFXDevice::setWorldMatrix( const MatrixF &newWorld )
  781. {
  782. mWorldMatrixDirty = true;
  783. mStateDirty = true;
  784. mWorldMatrix[mWorldStackSize] = newWorld;
  785. }
  786. inline void GFXDevice::pushWorldMatrix()
  787. {
  788. mWorldMatrixDirty = true;
  789. mStateDirty = true;
  790. mWorldStackSize++;
  791. AssertFatal( mWorldStackSize < WORLD_STACK_MAX, "GFX: Exceeded world matrix stack size" );
  792. mWorldMatrix[mWorldStackSize] = mWorldMatrix[mWorldStackSize - 1];
  793. }
  794. inline void GFXDevice::popWorldMatrix()
  795. {
  796. mWorldMatrixDirty = true;
  797. mStateDirty = true;
  798. mWorldStackSize--;
  799. AssertFatal( mWorldStackSize >= 0, "GFX: Negative WorldStackSize!" );
  800. }
  801. inline void GFXDevice::multWorld( const MatrixF &mat )
  802. {
  803. mWorldMatrixDirty = true;
  804. mStateDirty = true;
  805. mWorldMatrix[mWorldStackSize].mul(mat);
  806. }
  807. inline void GFXDevice::setProjectionMatrix( const MatrixF &newProj )
  808. {
  809. mProjectionMatrixDirty = true;
  810. mStateDirty = true;
  811. mProjectionMatrix = newProj;
  812. }
  813. inline void GFXDevice::setViewMatrix( const MatrixF &newView )
  814. {
  815. mStateDirty = true;
  816. mViewMatrixDirty = true;
  817. mViewMatrix = newView;
  818. }
  819. inline void GFXDevice::setTextureMatrix( const U32 stage, const MatrixF &texMat )
  820. {
  821. AssertFatal( stage < TEXTURE_STAGE_COUNT, "Out of range texture sampler" );
  822. mStateDirty = true;
  823. mTextureMatrixDirty[stage] = true;
  824. mTextureMatrix[stage] = texMat;
  825. mTextureMatrixCheckDirty = true;
  826. }
  827. //-----------------------------------------------------------------------------
  828. // Buffer management
  829. inline void GFXDevice::setVertexBuffer( GFXVertexBuffer *buffer, U32 stream, U32 frequency )
  830. {
  831. AssertFatal( stream < VERTEX_STREAM_COUNT, "GFXDevice::setVertexBuffer - Bad stream index!" );
  832. if ( buffer && stream == 0 )
  833. setVertexFormat( &buffer->mVertexFormat );
  834. if ( buffer != mCurrentVertexBuffer[stream] )
  835. {
  836. mCurrentVertexBuffer[stream] = buffer;
  837. mVertexBufferDirty[stream] = true;
  838. mStateDirty = true;
  839. }
  840. if ( mVertexBufferFrequency[stream] != frequency )
  841. {
  842. mVertexBufferFrequency[stream] = frequency;
  843. mVertexBufferFrequencyDirty[stream] = true;
  844. mStateDirty = true;
  845. }
  846. }
  847. inline void GFXDevice::setVertexFormat( const GFXVertexFormat *vertexFormat )
  848. {
  849. if ( vertexFormat->getDecl() == mCurrVertexDecl )
  850. return;
  851. mCurrVertexDecl = vertexFormat->getDecl();
  852. mVertexDeclDirty = true;
  853. mStateDirty = true;
  854. }
  855. #endif // _GFXDEVICE_H_