gfxD3D9Device.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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. #include "gfx/D3D9/gfxD3D9Device.h"
  23. #include "console/console.h"
  24. #include "core/stream/fileStream.h"
  25. #include "core/strings/unicode.h"
  26. #include "gfx/D3D9/gfxD3D9CardProfiler.h"
  27. #include "gfx/D3D9/gfxD3D9VertexBuffer.h"
  28. #include "gfx/D3D9/screenShotD3D9.h"
  29. #include "gfx/D3D9/gfxD3D9EnumTranslate.h"
  30. #include "gfx/D3D9/gfxD3D9QueryFence.h"
  31. #include "gfx/D3D9/gfxD3D9OcclusionQuery.h"
  32. #include "gfx/D3D9/gfxD3D9Shader.h"
  33. #include "windowManager/platformWindow.h"
  34. #ifndef TORQUE_OS_XENON
  35. # include "windowManager/win32/win32Window.h"
  36. #endif
  37. D3DXFNTable GFXD3D9Device::smD3DX;
  38. GFXD3D9Device::GFXD3D9Device( LPDIRECT3D9 d3d, U32 index )
  39. {
  40. mDeviceSwizzle32 = &Swizzles::bgra;
  41. GFXVertexColor::setSwizzle( mDeviceSwizzle32 );
  42. mDeviceSwizzle24 = &Swizzles::bgr;
  43. mD3D = d3d;
  44. mAdapterIndex = index;
  45. mD3DDevice = NULL;
  46. mVolatileVB = NULL;
  47. mCurrentPB = NULL;
  48. mDynamicPB = NULL;
  49. mLastVertShader = NULL;
  50. mLastPixShader = NULL;
  51. mCanCurrentlyRender = false;
  52. mTextureManager = NULL;
  53. mCurrentStateBlock = NULL;
  54. mResourceListHead = NULL;
  55. #ifdef TORQUE_DEBUG
  56. mVBListHead = NULL;
  57. mNumAllocatedVertexBuffers = 0;
  58. #endif
  59. mPixVersion = 0.0;
  60. mNumSamplers = 0;
  61. mNumRenderTargets = 0;
  62. mCardProfiler = NULL;
  63. mDeviceDepthStencil = NULL;
  64. mDeviceBackbuffer = NULL;
  65. mDeviceColor = NULL;
  66. mCreateFenceType = -1; // Unknown, test on first allocate
  67. mCurrentConstBuffer = NULL;
  68. mOcclusionQuerySupported = false;
  69. // Set up the Enum translation tables
  70. GFXD3D9EnumTranslate::init();
  71. #if !defined(TORQUE_OS_XENON)
  72. mD3DEx = NULL;
  73. mD3DDeviceEx = NULL;
  74. #endif
  75. }
  76. //-----------------------------------------------------------------------------
  77. GFXD3D9Device::~GFXD3D9Device()
  78. {
  79. // Release our refcount on the current stateblock object
  80. mCurrentStateBlock = NULL;
  81. releaseDefaultPoolResources();
  82. // Free the vertex declarations.
  83. VertexDeclMap::Iterator iter = mVertexDecls.begin();
  84. for ( ; iter != mVertexDecls.end(); iter++ )
  85. delete iter->value;
  86. // Check up on things
  87. Con::printf("Cur. D3DDevice ref count=%d", mD3DDevice->AddRef() - 1);
  88. mD3DDevice->Release();
  89. // Forcibly clean up the pools
  90. mVolatileVBList.setSize(0);
  91. mDynamicPB = NULL;
  92. // And release our D3D resources.
  93. SAFE_RELEASE( mDeviceDepthStencil );
  94. SAFE_RELEASE( mDeviceBackbuffer )
  95. SAFE_RELEASE( mDeviceColor );
  96. SAFE_RELEASE( mD3D );
  97. SAFE_RELEASE( mD3DDevice );
  98. #ifdef TORQUE_DEBUG
  99. logVertexBuffers();
  100. #endif
  101. if( mCardProfiler )
  102. {
  103. delete mCardProfiler;
  104. mCardProfiler = NULL;
  105. }
  106. if( gScreenShot )
  107. {
  108. delete gScreenShot;
  109. gScreenShot = NULL;
  110. }
  111. }
  112. //------------------------------------------------------------------------------
  113. // setupGenericShaders - This function is totally not needed on PC because there
  114. // is fixed-function support in D3D9
  115. //------------------------------------------------------------------------------
  116. inline void GFXD3D9Device::setupGenericShaders( GenericShaderType type /* = GSColor */ )
  117. {
  118. #ifdef WANT_TO_SIMULATE_UI_ON_360
  119. if( mGenericShader[GSColor] == NULL )
  120. {
  121. mGenericShader[GSColor] = createShader( "shaders/common/genericColorV.hlsl",
  122. "shaders/common/genericColorP.hlsl",
  123. 2.f );
  124. mGenericShader[GSModColorTexture] = createShader( "shaders/common/genericModColorTextureV.hlsl",
  125. "shaders/common/genericModColorTextureP.hlsl",
  126. 2.f );
  127. mGenericShader[GSAddColorTexture] = createShader( "shaders/common/genericAddColorTextureV.hlsl",
  128. "shaders/common/genericAddColorTextureP.hlsl",
  129. 2.f );
  130. }
  131. mGenericShader[type]->process();
  132. MatrixF world, view, proj;
  133. mWorldMatrix[mWorldStackSize].transposeTo( world );
  134. mViewMatrix.transposeTo( view );
  135. mProjectionMatrix.transposeTo( proj );
  136. mTempMatrix = world * view * proj;
  137. setVertexShaderConstF( VC_WORLD_PROJ, (F32 *)&mTempMatrix, 4 );
  138. #else
  139. disableShaders();
  140. #endif
  141. }
  142. //-----------------------------------------------------------------------------
  143. /// Creates a state block object based on the desc passed in. This object
  144. /// represents an immutable state.
  145. GFXStateBlockRef GFXD3D9Device::createStateBlockInternal(const GFXStateBlockDesc& desc)
  146. {
  147. return GFXStateBlockRef(new GFXD3D9StateBlock(desc, mD3DDevice));
  148. }
  149. /// Activates a stateblock
  150. void GFXD3D9Device::setStateBlockInternal(GFXStateBlock* block, bool force)
  151. {
  152. AssertFatal(dynamic_cast<GFXD3D9StateBlock*>(block), "Incorrect stateblock type for this device!");
  153. GFXD3D9StateBlock* d3dBlock = static_cast<GFXD3D9StateBlock*>(block);
  154. GFXD3D9StateBlock* d3dCurrent = static_cast<GFXD3D9StateBlock*>(mCurrentStateBlock.getPointer());
  155. if (force)
  156. d3dCurrent = NULL;
  157. d3dBlock->activate(d3dCurrent);
  158. }
  159. /// Called by base GFXDevice to actually set a const buffer
  160. void GFXD3D9Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  161. {
  162. if (buffer)
  163. {
  164. PROFILE_SCOPE(GFXD3D9Device_setShaderConstBufferInternal);
  165. AssertFatal(dynamic_cast<GFXD3D9ShaderConstBuffer*>(buffer), "Incorrect shader const buffer type for this device!");
  166. GFXD3D9ShaderConstBuffer* d3dBuffer = static_cast<GFXD3D9ShaderConstBuffer*>(buffer);
  167. d3dBuffer->activate(mCurrentConstBuffer);
  168. mCurrentConstBuffer = d3dBuffer;
  169. } else {
  170. mCurrentConstBuffer = NULL;
  171. }
  172. }
  173. //-----------------------------------------------------------------------------
  174. void GFXD3D9Device::clear( U32 flags, ColorI color, F32 z, U32 stencil )
  175. {
  176. // Make sure we have flushed our render target state.
  177. _updateRenderTargets();
  178. // Kind of a bummer we have to do this, there should be a better way made
  179. DWORD realflags = 0;
  180. if( flags & GFXClearTarget )
  181. realflags |= D3DCLEAR_TARGET;
  182. if( flags & GFXClearZBuffer )
  183. realflags |= D3DCLEAR_ZBUFFER;
  184. if( flags & GFXClearStencil )
  185. realflags |= D3DCLEAR_STENCIL;
  186. mD3DDevice->Clear( 0, NULL, realflags,
  187. D3DCOLOR_ARGB( color.alpha, color.red, color.green, color.blue ),
  188. z, stencil );
  189. }
  190. //-----------------------------------------------------------------------------
  191. bool GFXD3D9Device::beginSceneInternal()
  192. {
  193. HRESULT hr = mD3DDevice->BeginScene();
  194. D3D9Assert(hr, "GFXD3D9Device::beginSceneInternal - failed to BeginScene");
  195. mCanCurrentlyRender = SUCCEEDED(hr);
  196. return mCanCurrentlyRender;
  197. }
  198. //-----------------------------------------------------------------------------
  199. void GFXD3D9Device::endSceneInternal()
  200. {
  201. mD3DDevice->EndScene();
  202. mCanCurrentlyRender = false;
  203. }
  204. void GFXD3D9Device::_updateRenderTargets()
  205. {
  206. if ( mRTDirty || ( mCurrentRT && mCurrentRT->isPendingState() ) )
  207. {
  208. if ( mRTDeactivate )
  209. {
  210. mRTDeactivate->deactivate();
  211. mRTDeactivate = NULL;
  212. }
  213. // NOTE: The render target changes are not really accurate
  214. // as the GFXTextureTarget supports MRT internally. So when
  215. // we activate a GFXTarget it could result in multiple calls
  216. // to SetRenderTarget on the actual device.
  217. mDeviceStatistics.mRenderTargetChanges++;
  218. mCurrentRT->activate();
  219. mRTDirty = false;
  220. }
  221. if ( mViewportDirty )
  222. {
  223. D3DVIEWPORT9 viewport;
  224. viewport.X = mViewport.point.x;
  225. viewport.Y = mViewport.point.y;
  226. viewport.Width = mViewport.extent.x;
  227. viewport.Height = mViewport.extent.y;
  228. viewport.MinZ = 0.0;
  229. viewport.MaxZ = 1.0;
  230. D3D9Assert( mD3DDevice->SetViewport( &viewport ),
  231. "GFXD3D9Device::_updateRenderTargets() - Error setting viewport!" );
  232. mViewportDirty = false;
  233. }
  234. }
  235. #ifdef TORQUE_DEBUG
  236. void GFXD3D9Device::logVertexBuffers()
  237. {
  238. // NOTE: This function should be called on the destructor of this class and ONLY then
  239. // otherwise it'll produce the wrong output
  240. if( mNumAllocatedVertexBuffers == 0 )
  241. return;
  242. FileStream fs;
  243. fs.open( "vertexbuffer.log", Torque::FS::File::Write );
  244. char buff[256];
  245. fs.writeLine( (U8 *)avar("-- Vertex buffer memory leak report -- time = %d", Platform::getRealMilliseconds()) );
  246. dSprintf( (char *)&buff, sizeof( buff ), "%d un-freed vertex buffers", mNumAllocatedVertexBuffers );
  247. fs.writeLine( (U8 *)buff );
  248. GFXD3D9VertexBuffer *walk = mVBListHead;
  249. while( walk != NULL )
  250. {
  251. dSprintf( (char *)&buff, sizeof( buff ), "[Name: %s] Size: %d", walk->name, walk->mNumVerts );
  252. fs.writeLine( (U8 *)buff );
  253. walk = walk->next;
  254. }
  255. fs.writeLine( (U8 *)"-- End report --" );
  256. fs.close();
  257. }
  258. //-----------------------------------------------------------------------------
  259. void GFXD3D9Device::addVertexBuffer( GFXD3D9VertexBuffer *buffer )
  260. {
  261. mNumAllocatedVertexBuffers++;
  262. if( mVBListHead == NULL )
  263. {
  264. mVBListHead = buffer;
  265. }
  266. else
  267. {
  268. GFXD3D9VertexBuffer *walk = mVBListHead;
  269. while( walk->next != NULL )
  270. {
  271. walk = walk->next;
  272. }
  273. walk->next = buffer;
  274. }
  275. buffer->next = NULL;
  276. }
  277. //-----------------------------------------------------------------------------
  278. void GFXD3D9Device::removeVertexBuffer( GFXD3D9VertexBuffer *buffer )
  279. {
  280. mNumAllocatedVertexBuffers--;
  281. // Quick check to see if this is head of list
  282. if( mVBListHead == buffer )
  283. {
  284. mVBListHead = mVBListHead->next;
  285. return;
  286. }
  287. GFXD3D9VertexBuffer *walk = mVBListHead;
  288. while( walk->next != NULL )
  289. {
  290. if( walk->next == buffer )
  291. {
  292. walk->next = walk->next->next;
  293. return;
  294. }
  295. walk = walk->next;
  296. }
  297. AssertFatal( false, "Vertex buffer not found in list." );
  298. }
  299. #endif
  300. //-----------------------------------------------------------------------------
  301. void GFXD3D9Device::releaseDefaultPoolResources()
  302. {
  303. // Release all the dynamic vertex buffer arrays
  304. // Forcibly clean up the pools
  305. for( U32 i=0; i<mVolatileVBList.size(); i++ )
  306. {
  307. // Con::printf("Trying to release volatile vb with COM refcount of %d and internal refcount of %d", mVolatileVBList[i]->vb->AddRef() - 1, mVolatileVBList[i]->mRefCount);
  308. // mVolatileVBList[i]->vb->Release();
  309. mVolatileVBList[i]->vb->Release();
  310. mVolatileVBList[i]->vb = NULL;
  311. mVolatileVBList[i] = NULL;
  312. }
  313. mVolatileVBList.setSize(0);
  314. // We gotta clear the current const buffer else the next
  315. // activate may erroneously think the device is still holding
  316. // this state and fail to set it.
  317. mCurrentConstBuffer = NULL;
  318. // Set current VB to NULL and set state dirty
  319. for ( U32 i=0; i < VERTEX_STREAM_COUNT; i++ )
  320. {
  321. mCurrentVertexBuffer[i] = NULL;
  322. mVertexBufferDirty[i] = true;
  323. mVertexBufferFrequency[i] = 0;
  324. mVertexBufferFrequencyDirty[i] = true;
  325. }
  326. // Release dynamic index buffer
  327. if( mDynamicPB != NULL )
  328. {
  329. SAFE_RELEASE( mDynamicPB->ib );
  330. }
  331. // Set current PB/IB to NULL and set state dirty
  332. mCurrentPrimitiveBuffer = NULL;
  333. mCurrentPB = NULL;
  334. mPrimitiveBufferDirty = true;
  335. // Zombify texture manager (for D3D this only modifies default pool textures)
  336. if( mTextureManager )
  337. mTextureManager->zombify();
  338. // Kill off other potentially dangling references...
  339. SAFE_RELEASE( mDeviceDepthStencil );
  340. SAFE_RELEASE( mDeviceBackbuffer );
  341. mD3DDevice->SetDepthStencilSurface(NULL);
  342. // Set global dirty state so the IB/PB and VB get reset
  343. mStateDirty = true;
  344. // Walk the resource list and zombify everything.
  345. GFXResource *walk = mResourceListHead;
  346. while(walk)
  347. {
  348. walk->zombify();
  349. walk = walk->getNextResource();
  350. }
  351. }
  352. //-----------------------------------------------------------------------------
  353. void GFXD3D9Device::reacquireDefaultPoolResources()
  354. {
  355. // Now do the dynamic index buffers
  356. if( mDynamicPB == NULL )
  357. mDynamicPB = new GFXD3D9PrimitiveBuffer(this, 0, 0, GFXBufferTypeDynamic);
  358. D3D9Assert( mD3DDevice->CreateIndexBuffer( sizeof( U16 ) * MAX_DYNAMIC_INDICES,
  359. #ifdef TORQUE_OS_XENON
  360. D3DUSAGE_WRITEONLY,
  361. #else
  362. D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC,
  363. #endif
  364. GFXD3D9IndexFormat[GFXIndexFormat16], D3DPOOL_DEFAULT, &mDynamicPB->ib, NULL ), "Failed to allocate dynamic IB" );
  365. // Grab the depth-stencil...
  366. SAFE_RELEASE(mDeviceDepthStencil);
  367. D3D9Assert(mD3DDevice->GetDepthStencilSurface(&mDeviceDepthStencil),
  368. "GFXD3D9Device::reacquireDefaultPoolResources - couldn't grab reference to device's depth-stencil surface.");
  369. SAFE_RELEASE(mDeviceBackbuffer);
  370. mD3DDevice->GetBackBuffer( 0, 0, D3DBACKBUFFER_TYPE_MONO, &mDeviceBackbuffer );
  371. // Store for query later.
  372. mD3DDevice->GetDisplayMode( 0, &mDisplayMode );
  373. // Walk the resource list and zombify everything.
  374. GFXResource *walk = mResourceListHead;
  375. while(walk)
  376. {
  377. walk->resurrect();
  378. walk = walk->getNextResource();
  379. }
  380. if(mTextureManager)
  381. mTextureManager->resurrect();
  382. }
  383. GFXD3D9VertexBuffer* GFXD3D9Device::findVBPool( const GFXVertexFormat *vertexFormat, U32 vertsNeeded )
  384. {
  385. PROFILE_SCOPE( GFXD3D9Device_findVBPool );
  386. // Verts needed is ignored on the base device, 360 is different
  387. for( U32 i=0; i<mVolatileVBList.size(); i++ )
  388. if( mVolatileVBList[i]->mVertexFormat.isEqual( *vertexFormat ) )
  389. return mVolatileVBList[i];
  390. return NULL;
  391. }
  392. GFXD3D9VertexBuffer * GFXD3D9Device::createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize )
  393. {
  394. PROFILE_SCOPE( GFXD3D9Device_createVBPool );
  395. // this is a bit funky, but it will avoid problems with (lack of) copy constructors
  396. // with a push_back() situation
  397. mVolatileVBList.increment();
  398. StrongRefPtr<GFXD3D9VertexBuffer> newBuff;
  399. mVolatileVBList.last() = new GFXD3D9VertexBuffer();
  400. newBuff = mVolatileVBList.last();
  401. newBuff->mNumVerts = 0;
  402. newBuff->mBufferType = GFXBufferTypeVolatile;
  403. newBuff->mVertexFormat.copy( *vertexFormat );
  404. newBuff->mVertexSize = vertSize;
  405. newBuff->mDevice = this;
  406. // Requesting it will allocate it.
  407. vertexFormat->getDecl();
  408. // Con::printf("Created buff with type %x", vertFlags);
  409. D3D9Assert( mD3DDevice->CreateVertexBuffer( vertSize * MAX_DYNAMIC_VERTS,
  410. #ifdef TORQUE_OS_XENON
  411. D3DUSAGE_WRITEONLY,
  412. #else
  413. D3DUSAGE_WRITEONLY | D3DUSAGE_DYNAMIC,
  414. #endif
  415. 0,
  416. D3DPOOL_DEFAULT,
  417. &newBuff->vb,
  418. NULL ),
  419. "Failed to allocate dynamic VB" );
  420. return newBuff;
  421. }
  422. //-----------------------------------------------------------------------------
  423. void GFXD3D9Device::setClipRect( const RectI &inRect )
  424. {
  425. // We transform the incoming rect by the view
  426. // matrix first, so that it can be used to pan
  427. // and scale the clip rect.
  428. //
  429. // This is currently used to take tiled screenshots.
  430. Point3F pos( inRect.point.x, inRect.point.y, 0.0f );
  431. Point3F extent( inRect.extent.x, inRect.extent.y, 0.0f );
  432. getViewMatrix().mulP( pos );
  433. getViewMatrix().mulV( extent );
  434. RectI rect( pos.x, pos.y, extent.x, extent.y );
  435. // Clip the rect against the renderable size.
  436. Point2I size = mCurrentRT->getSize();
  437. RectI maxRect(Point2I(0,0), size);
  438. rect.intersect(maxRect);
  439. mClipRect = rect;
  440. F32 l = F32( mClipRect.point.x );
  441. F32 r = F32( mClipRect.point.x + mClipRect.extent.x );
  442. F32 b = F32( mClipRect.point.y + mClipRect.extent.y );
  443. F32 t = F32( mClipRect.point.y );
  444. // Set up projection matrix,
  445. static Point4F pt;
  446. pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f);
  447. mTempMatrix.setColumn(0, pt);
  448. pt.set(0.0f, 2.0f/(t - b), 0.0f, 0.0f);
  449. mTempMatrix.setColumn(1, pt);
  450. pt.set(0.0f, 0.0f, 1.0f, 0.0f);
  451. mTempMatrix.setColumn(2, pt);
  452. pt.set((l+r)/(l-r), (t+b)/(b-t), 1.0f, 1.0f);
  453. mTempMatrix.setColumn(3, pt);
  454. setProjectionMatrix( mTempMatrix );
  455. // Set up world/view matrix
  456. mTempMatrix.identity();
  457. setWorldMatrix( mTempMatrix );
  458. setViewport( mClipRect );
  459. }
  460. void GFXD3D9Device::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  461. {
  462. GFXD3D9VertexBuffer *d3dBuffer = static_cast<GFXD3D9VertexBuffer*>( buffer );
  463. if ( stream == 0 )
  464. {
  465. // Set the volatile buffer which is used to
  466. // offset the start index when doing draw calls.
  467. if ( d3dBuffer && d3dBuffer->mVolatileStart > 0 )
  468. mVolatileVB = d3dBuffer;
  469. else
  470. mVolatileVB = NULL;
  471. }
  472. // NOTE: We do not use the stream offset here for stream 0
  473. // as that feature is *supposedly* not as well supported as
  474. // using the start index in drawPrimitive.
  475. //
  476. // If we can verify that this is not the case then we should
  477. // start using this method exclusively for all streams.
  478. D3D9Assert( mD3DDevice->SetStreamSource( stream,
  479. d3dBuffer ? d3dBuffer->vb : NULL,
  480. d3dBuffer && stream != 0 ? d3dBuffer->mVolatileStart * d3dBuffer->mVertexSize : 0,
  481. d3dBuffer ? d3dBuffer->mVertexSize : 0 ),
  482. "GFXD3D9Device::setVertexStream - Failed to set stream source." );
  483. }
  484. void GFXD3D9Device::setVertexStreamFrequency( U32 stream, U32 frequency )
  485. {
  486. if ( frequency == 0 )
  487. frequency = 1;
  488. else
  489. {
  490. if ( stream == 0 )
  491. frequency = D3DSTREAMSOURCE_INDEXEDDATA | frequency;
  492. else
  493. frequency = D3DSTREAMSOURCE_INSTANCEDATA | frequency;
  494. }
  495. D3D9Assert( mD3DDevice->SetStreamSourceFreq( stream, frequency ),
  496. "GFXD3D9Device::setVertexStreamFrequency - Failed to set stream frequency." );
  497. }
  498. void GFXD3D9Device::_setPrimitiveBuffer( GFXPrimitiveBuffer *buffer )
  499. {
  500. mCurrentPB = static_cast<GFXD3D9PrimitiveBuffer *>( buffer );
  501. D3D9Assert( mD3DDevice->SetIndices( mCurrentPB->ib ), "Failed to set indices" );
  502. }
  503. void GFXD3D9Device::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  504. {
  505. // This is done to avoid the function call overhead if possible
  506. if( mStateDirty )
  507. updateStates();
  508. if (mCurrentShaderConstBuffer)
  509. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  510. if ( mVolatileVB )
  511. vertexStart += mVolatileVB->mVolatileStart;
  512. D3D9Assert( mD3DDevice->DrawPrimitive( GFXD3D9PrimType[primType], vertexStart, primitiveCount ), "Failed to draw primitives" );
  513. mDeviceStatistics.mDrawCalls++;
  514. if ( mVertexBufferFrequency[0] > 1 )
  515. mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
  516. else
  517. mDeviceStatistics.mPolyCount += primitiveCount;
  518. }
  519. //-----------------------------------------------------------------------------
  520. void GFXD3D9Device::drawIndexedPrimitive( GFXPrimitiveType primType,
  521. U32 startVertex,
  522. U32 minIndex,
  523. U32 numVerts,
  524. U32 startIndex,
  525. U32 primitiveCount )
  526. {
  527. // This is done to avoid the function call overhead if possible
  528. if( mStateDirty )
  529. updateStates();
  530. if (mCurrentShaderConstBuffer)
  531. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  532. AssertFatal( mCurrentPB != NULL, "Trying to call drawIndexedPrimitive with no current index buffer, call setIndexBuffer()" );
  533. if ( mVolatileVB )
  534. startVertex += mVolatileVB->mVolatileStart;
  535. D3D9Assert( mD3DDevice->DrawIndexedPrimitive( GFXD3D9PrimType[primType],
  536. startVertex,
  537. /* mCurrentPB->mVolatileStart + */ minIndex,
  538. numVerts,
  539. mCurrentPB->mVolatileStart + startIndex,
  540. primitiveCount ), "Failed to draw indexed primitive" );
  541. mDeviceStatistics.mDrawCalls++;
  542. if ( mVertexBufferFrequency[0] > 1 )
  543. mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0];
  544. else
  545. mDeviceStatistics.mPolyCount += primitiveCount;
  546. }
  547. GFXShader* GFXD3D9Device::createShader()
  548. {
  549. GFXD3D9Shader* shader = new GFXD3D9Shader();
  550. shader->registerResourceWithDevice( this );
  551. return shader;
  552. }
  553. void GFXD3D9Device::disableShaders(bool force)
  554. {
  555. setShader( NULL, force );
  556. setShaderConstBuffer( NULL );
  557. }
  558. //-----------------------------------------------------------------------------
  559. // Set shader - this function exists to make sure this is done in one place,
  560. // and to make sure redundant shader states are not being
  561. // sent to the card.
  562. //-----------------------------------------------------------------------------
  563. void GFXD3D9Device::setShader( GFXShader *shader, bool force )
  564. {
  565. GFXD3D9Shader *d3dShader = static_cast<GFXD3D9Shader*>( shader );
  566. IDirect3DPixelShader9 *pixShader = ( d3dShader != NULL ? d3dShader->mPixShader : NULL );
  567. IDirect3DVertexShader9 *vertShader = ( d3dShader ? d3dShader->mVertShader : NULL );
  568. if( pixShader != mLastPixShader || force )
  569. {
  570. mD3DDevice->SetPixelShader( pixShader );
  571. mLastPixShader = pixShader;
  572. }
  573. if( vertShader != mLastVertShader || force )
  574. {
  575. mD3DDevice->SetVertexShader( vertShader );
  576. mLastVertShader = vertShader;
  577. }
  578. }
  579. //-----------------------------------------------------------------------------
  580. // allocPrimitiveBuffer
  581. //-----------------------------------------------------------------------------
  582. GFXPrimitiveBuffer * GFXD3D9Device::allocPrimitiveBuffer( U32 numIndices,
  583. U32 numPrimitives,
  584. GFXBufferType bufferType )
  585. {
  586. // Allocate a buffer to return
  587. GFXD3D9PrimitiveBuffer * res = new GFXD3D9PrimitiveBuffer(this, numIndices, numPrimitives, bufferType);
  588. // Determine usage flags
  589. U32 usage = 0;
  590. D3DPOOL pool = D3DPOOL_DEFAULT;
  591. // Assumptions:
  592. // - static buffers are write once, use many
  593. // - dynamic buffers are write many, use many
  594. // - volatile buffers are write once, use once
  595. // You may never read from a buffer.
  596. switch(bufferType)
  597. {
  598. case GFXBufferTypeStatic:
  599. pool = isD3D9Ex() ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
  600. break;
  601. case GFXBufferTypeDynamic:
  602. case GFXBufferTypeVolatile:
  603. #ifndef TORQUE_OS_XENON
  604. usage |= D3DUSAGE_DYNAMIC;
  605. #endif
  606. break;
  607. }
  608. // Register resource
  609. res->registerResourceWithDevice(this);
  610. // We never allow reading from a primitive buffer.
  611. usage |= D3DUSAGE_WRITEONLY;
  612. // Create d3d index buffer
  613. if(bufferType == GFXBufferTypeVolatile)
  614. {
  615. // Get it from the pool if it's a volatile...
  616. AssertFatal( numIndices < MAX_DYNAMIC_INDICES, "Cannot allocate that many indices in a volatile buffer, increase MAX_DYNAMIC_INDICES." );
  617. res->ib = mDynamicPB->ib;
  618. // mDynamicPB->ib->AddRef();
  619. res->mVolatileBuffer = mDynamicPB;
  620. }
  621. else
  622. {
  623. // Otherwise, get it as a seperate buffer...
  624. D3D9Assert(mD3DDevice->CreateIndexBuffer( sizeof(U16) * numIndices , usage, GFXD3D9IndexFormat[GFXIndexFormat16], pool, &res->ib, 0),
  625. "Failed to allocate an index buffer.");
  626. }
  627. return res;
  628. }
  629. //-----------------------------------------------------------------------------
  630. // allocVertexBuffer
  631. //-----------------------------------------------------------------------------
  632. GFXVertexBuffer * GFXD3D9Device::allocVertexBuffer( U32 numVerts,
  633. const GFXVertexFormat *vertexFormat,
  634. U32 vertSize,
  635. GFXBufferType bufferType )
  636. {
  637. PROFILE_SCOPE( GFXD3D9Device_allocVertexBuffer );
  638. GFXD3D9VertexBuffer *res = new GFXD3D9VertexBuffer( this,
  639. numVerts,
  640. vertexFormat,
  641. vertSize,
  642. bufferType );
  643. // Determine usage flags
  644. U32 usage = 0;
  645. D3DPOOL pool = D3DPOOL_DEFAULT;
  646. res->mNumVerts = 0;
  647. // Assumptions:
  648. // - static buffers are write once, use many
  649. // - dynamic buffers are write many, use many
  650. // - volatile buffers are write once, use once
  651. // You may never read from a buffer.
  652. switch(bufferType)
  653. {
  654. case GFXBufferTypeStatic:
  655. pool = isD3D9Ex() ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
  656. break;
  657. case GFXBufferTypeDynamic:
  658. case GFXBufferTypeVolatile:
  659. pool = D3DPOOL_DEFAULT;
  660. usage |= D3DUSAGE_WRITEONLY;
  661. #ifndef TORQUE_OS_XENON
  662. usage |= D3DUSAGE_DYNAMIC;
  663. #endif
  664. break;
  665. }
  666. res->registerResourceWithDevice(this);
  667. // Create vertex buffer
  668. if( bufferType == GFXBufferTypeVolatile )
  669. {
  670. // NOTE: Volatile VBs are pooled and will be allocated at lock time.
  671. AssertFatal( numVerts <= MAX_DYNAMIC_VERTS,
  672. "GFXD3D9Device::allocVertexBuffer - Volatile vertex buffer is too big... see MAX_DYNAMIC_VERTS!" );
  673. }
  674. else
  675. {
  676. // Requesting it will allocate it.
  677. vertexFormat->getDecl();
  678. // Get a new buffer...
  679. D3D9Assert( mD3DDevice->CreateVertexBuffer( vertSize * numVerts, usage, 0, pool, &res->vb, NULL ),
  680. "Failed to allocate VB" );
  681. }
  682. res->mNumVerts = numVerts;
  683. return res;
  684. }
  685. //-----------------------------------------------------------------------------
  686. // deallocate vertex buffer
  687. //-----------------------------------------------------------------------------
  688. void GFXD3D9Device::deallocVertexBuffer( GFXD3D9VertexBuffer *vertBuff )
  689. {
  690. SAFE_RELEASE(vertBuff->vb);
  691. }
  692. GFXVertexDecl* GFXD3D9Device::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  693. {
  694. PROFILE_SCOPE( GFXD3D9Device_allocVertexDecl );
  695. // First check the map... you shouldn't allocate VBs very often
  696. // if you want performance. The map lookup should never become
  697. // a performance bottleneck.
  698. D3D9VertexDecl *decl = mVertexDecls[vertexFormat->getDescription()];
  699. if ( decl )
  700. return decl;
  701. // Setup the declaration struct.
  702. U32 elemCount = vertexFormat->getElementCount();
  703. U32 offsets[4] = { 0 };
  704. U32 stream;
  705. D3DVERTEXELEMENT9 *vd = new D3DVERTEXELEMENT9[ elemCount + 1 ];
  706. for ( U32 i=0; i < elemCount; i++ )
  707. {
  708. const GFXVertexElement &element = vertexFormat->getElement( i );
  709. stream = element.getStreamIndex();
  710. vd[i].Stream = stream;
  711. vd[i].Offset = offsets[stream];
  712. vd[i].Type = GFXD3D9DeclType[element.getType()];
  713. vd[i].Method = D3DDECLMETHOD_DEFAULT;
  714. // We force the usage index of 0 for everything but
  715. // texture coords for now... this may change later.
  716. vd[i].UsageIndex = 0;
  717. if ( element.isSemantic( GFXSemantic::POSITION ) )
  718. vd[i].Usage = D3DDECLUSAGE_POSITION;
  719. else if ( element.isSemantic( GFXSemantic::NORMAL ) )
  720. vd[i].Usage = D3DDECLUSAGE_NORMAL;
  721. else if ( element.isSemantic( GFXSemantic::COLOR ) )
  722. vd[i].Usage = D3DDECLUSAGE_COLOR;
  723. else if ( element.isSemantic( GFXSemantic::TANGENT ) )
  724. vd[i].Usage = D3DDECLUSAGE_TANGENT;
  725. else if ( element.isSemantic( GFXSemantic::BINORMAL ) )
  726. vd[i].Usage = D3DDECLUSAGE_BINORMAL;
  727. else
  728. {
  729. // Anything that falls thru to here will be a texture coord.
  730. vd[i].Usage = D3DDECLUSAGE_TEXCOORD;
  731. vd[i].UsageIndex = element.getSemanticIndex();
  732. }
  733. offsets[stream] += element.getSizeInBytes();
  734. }
  735. D3DVERTEXELEMENT9 declEnd = D3DDECL_END();
  736. vd[elemCount] = declEnd;
  737. decl = new D3D9VertexDecl();
  738. D3D9Assert( mD3DDevice->CreateVertexDeclaration( vd, &decl->decl ),
  739. "GFXD3D9Device::allocVertexDecl - Failed to create vertex declaration!" );
  740. delete [] vd;
  741. // Store it in the cache.
  742. mVertexDecls[vertexFormat->getDescription()] = decl;
  743. return decl;
  744. }
  745. void GFXD3D9Device::setVertexDecl( const GFXVertexDecl *decl )
  746. {
  747. IDirect3DVertexDeclaration9 *dx9Decl = NULL;
  748. if ( decl )
  749. dx9Decl = static_cast<const D3D9VertexDecl*>( decl )->decl;
  750. D3D9Assert( mD3DDevice->SetVertexDeclaration( dx9Decl ), "GFXD3D9Device::setVertexDecl - Failed to set vertex declaration." );
  751. }
  752. //-----------------------------------------------------------------------------
  753. // This function should ONLY be called from GFXDevice::updateStates() !!!
  754. //-----------------------------------------------------------------------------
  755. void GFXD3D9Device::setTextureInternal( U32 textureUnit, const GFXTextureObject *texture)
  756. {
  757. if( texture == NULL )
  758. {
  759. D3D9Assert(mD3DDevice->SetTexture( textureUnit, NULL ), "Failed to set texture to null!");
  760. return;
  761. }
  762. GFXD3D9TextureObject *tex = (GFXD3D9TextureObject *) texture;
  763. D3D9Assert(mD3DDevice->SetTexture( textureUnit, tex->getTex()), "Failed to set texture to valid value!");
  764. }
  765. //-----------------------------------------------------------------------------
  766. // This function should ONLY be called from GFXDevice::updateStates() !!!
  767. //-----------------------------------------------------------------------------
  768. void GFXD3D9Device::setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable)
  769. {
  770. #ifndef TORQUE_OS_XENON
  771. if(!lightEnable)
  772. {
  773. mD3DDevice->LightEnable(lightStage, false);
  774. return;
  775. }
  776. D3DLIGHT9 d3dLight;
  777. switch (light.mType)
  778. {
  779. case GFXLightInfo::Ambient:
  780. AssertFatal(false, "Instead of setting an ambient light you should set the global ambient color.");
  781. return;
  782. case GFXLightInfo::Vector:
  783. d3dLight.Type = D3DLIGHT_DIRECTIONAL;
  784. break;
  785. case GFXLightInfo::Point:
  786. d3dLight.Type = D3DLIGHT_POINT;
  787. break;
  788. case GFXLightInfo::Spot:
  789. d3dLight.Type = D3DLIGHT_SPOT;
  790. break;
  791. default :
  792. AssertFatal(false, "Unknown light type!");
  793. };
  794. dMemcpy(&d3dLight.Diffuse, &light.mColor, sizeof(light.mColor));
  795. dMemcpy(&d3dLight.Ambient, &light.mAmbient, sizeof(light.mAmbient));
  796. dMemcpy(&d3dLight.Specular, &light.mColor, sizeof(light.mColor));
  797. dMemcpy(&d3dLight.Position, &light.mPos, sizeof(light.mPos));
  798. dMemcpy(&d3dLight.Direction, &light.mDirection, sizeof(light.mDirection));
  799. d3dLight.Range = light.mRadius;
  800. d3dLight.Falloff = 1.0;
  801. d3dLight.Attenuation0 = 1.0f;
  802. d3dLight.Attenuation1 = 0.1f;
  803. d3dLight.Attenuation2 = 0.0f;
  804. d3dLight.Theta = light.mInnerConeAngle;
  805. d3dLight.Phi = light.mOuterConeAngle;
  806. mD3DDevice->SetLight(lightStage, &d3dLight);
  807. mD3DDevice->LightEnable(lightStage, true);
  808. #endif
  809. }
  810. void GFXD3D9Device::setLightMaterialInternal(const GFXLightMaterial mat)
  811. {
  812. #ifndef TORQUE_OS_XENON
  813. D3DMATERIAL9 d3dmat;
  814. dMemset(&d3dmat, 0, sizeof(D3DMATERIAL9));
  815. D3DCOLORVALUE col;
  816. col.r = mat.ambient.red;
  817. col.g = mat.ambient.green;
  818. col.b = mat.ambient.blue;
  819. col.a = mat.ambient.alpha;
  820. d3dmat.Ambient = col;
  821. col.r = mat.diffuse.red;
  822. col.g = mat.diffuse.green;
  823. col.b = mat.diffuse.blue;
  824. col.a = mat.diffuse.alpha;
  825. d3dmat.Diffuse = col;
  826. col.r = mat.specular.red;
  827. col.g = mat.specular.green;
  828. col.b = mat.specular.blue;
  829. col.a = mat.specular.alpha;
  830. d3dmat.Specular = col;
  831. col.r = mat.emissive.red;
  832. col.g = mat.emissive.green;
  833. col.b = mat.emissive.blue;
  834. col.a = mat.emissive.alpha;
  835. d3dmat.Emissive = col;
  836. d3dmat.Power = mat.shininess;
  837. mD3DDevice->SetMaterial(&d3dmat);
  838. #endif
  839. }
  840. void GFXD3D9Device::setGlobalAmbientInternal(ColorF color)
  841. {
  842. #ifndef TORQUE_OS_XENON
  843. mD3DDevice->SetRenderState(D3DRS_AMBIENT,
  844. D3DCOLOR_COLORVALUE(color.red, color.green, color.blue, color.alpha));
  845. #endif
  846. }
  847. //------------------------------------------------------------------------------
  848. // Check for texture mis-match between GFX internal state and what is on the card
  849. // This function is expensive because of the readbacks from DX, and additionally
  850. // won't work unless it's a non-pure device.
  851. //
  852. // This function can crash or give false positives when the game
  853. // is shutting down or returning to the main menu as some of the textures
  854. // present in the mCurrentTexture array will have been freed.
  855. //
  856. // This function is best used as a quick check for mismatched state when it is
  857. // suspected.
  858. //------------------------------------------------------------------------------
  859. void GFXD3D9Device::doParanoidStateCheck()
  860. {
  861. #ifdef TORQUE_DEBUG
  862. // Read back all states and make sure they match what we think they should be.
  863. // For now just do texture binds.
  864. for(U32 i = 0; i < getNumSamplers(); i++)
  865. {
  866. IDirect3DBaseTexture9 *b=NULL;
  867. getDevice()->GetTexture(i, &b);
  868. if ((mCurrentTexture[i].isNull()) && (mCurrentCubemap[i].isNull()))
  869. {
  870. AssertFatal(b == NULL, "GFXD3D9Device::doParanoidStateCheck - got non-null texture in expected NULL slot!");
  871. getDevice()->SetTexture(i, NULL);
  872. }
  873. else
  874. {
  875. AssertFatal(mCurrentTexture[i] || mCurrentCubemap[i], "GFXD3D9Device::doParanoidStateCheck - got null texture in expected non-null slot!");
  876. if (mCurrentCubemap[i])
  877. {
  878. IDirect3DCubeTexture9 *cur= static_cast<GFXD3D9Cubemap*>(mCurrentCubemap[i].getPointer())->mCubeTex;
  879. AssertFatal(cur == b, "GFXD3D9Device::doParanoidStateCheck - mismatched cubemap!");
  880. }
  881. else
  882. {
  883. IDirect3DBaseTexture9 *cur= static_cast<GFXD3D9TextureObject*>(mCurrentTexture[i].getPointer())->getTex();
  884. AssertFatal(cur == b, "GFXD3D9Device::doParanoidStateCheck - mismatched 2d texture!");
  885. }
  886. }
  887. SAFE_RELEASE(b);
  888. }
  889. #endif
  890. }
  891. GFXFence *GFXD3D9Device::createFence()
  892. {
  893. // Figure out what fence type we should be making if we don't know
  894. if( mCreateFenceType == -1 )
  895. {
  896. IDirect3DQuery9 *testQuery = NULL;
  897. mCreateFenceType = ( mD3DDevice->CreateQuery( D3DQUERYTYPE_EVENT, &testQuery ) == D3DERR_NOTAVAILABLE );
  898. SAFE_RELEASE( testQuery );
  899. }
  900. // Cool, use queries
  901. if( !mCreateFenceType )
  902. {
  903. GFXFence* fence = new GFXD3D9QueryFence( this );
  904. fence->registerResourceWithDevice(this);
  905. return fence;
  906. }
  907. // CodeReview: At some point I would like a specialized D3D9 implementation of
  908. // the method used by the general fence, only without the overhead incurred
  909. // by using the GFX constructs. Primarily the lock() method on texture handles
  910. // will do a data copy, and this method doesn't require a copy, just a lock
  911. // [5/10/2007 Pat]
  912. GFXFence* fence = new GFXGeneralFence( this );
  913. fence->registerResourceWithDevice(this);
  914. return fence;
  915. }
  916. GFXOcclusionQuery* GFXD3D9Device::createOcclusionQuery()
  917. {
  918. GFXOcclusionQuery *query;
  919. if (mOcclusionQuerySupported)
  920. query = new GFXD3D9OcclusionQuery( this );
  921. else
  922. return NULL;
  923. query->registerResourceWithDevice(this);
  924. return query;
  925. }
  926. GFXCubemap * GFXD3D9Device::createCubemap()
  927. {
  928. GFXD3D9Cubemap* cube = new GFXD3D9Cubemap();
  929. cube->registerResourceWithDevice(this);
  930. return cube;
  931. }