CmD3D9RenderSystem.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmD3D9RenderSystem.h"
  25. #include "CmD3D9Prerequisites.h"
  26. #include "CmD3D9DriverList.h"
  27. #include "CmD3D9Driver.h"
  28. #include "CmD3D9VideoModeList.h"
  29. #include "CmD3D9VideoMode.h"
  30. #include "CmD3D9RenderWindow.h"
  31. #include "CmD3D9TextureManager.h"
  32. #include "CmD3D9Texture.h"
  33. #include "CmMath.h"
  34. #include "CmCamera.h"
  35. #include "CmD3D9HardwareBufferManager.h"
  36. #include "CmD3D9IndexBuffer.h"
  37. #include "CmD3D9VertexBuffer.h"
  38. #include "CmD3D9VertexDeclaration.h"
  39. #include "CmD3D9GpuProgram.h"
  40. #include "CmD3D9GpuProgramManager.h"
  41. #include "CmD3D9HLSLProgramFactory.h"
  42. #include "CmD3D9OcclusionQuery.h"
  43. #include "CmD3D9DeviceManager.h"
  44. #include "CmD3D9ResourceManager.h"
  45. #include "CmD3D9RenderWindowManager.h"
  46. #include "CmD3D9BuiltinMaterialManager.h"
  47. #include "CmHighLevelGpuProgramManager.h"
  48. #include "CmRenderStateManager.h"
  49. #include "CmAsyncOp.h"
  50. #include "CmBlendState.h"
  51. #include "CmRasterizerState.h"
  52. #include "CmDepthStencilState.h"
  53. #include "CmGpuParams.h"
  54. #include "CmGpuParamDesc.h"
  55. #include "CmGpuParamBlock.h"
  56. #include "CmDebug.h"
  57. #if CM_DEBUG_MODE
  58. #define THROW_IF_NOT_RENDER_THREAD throwIfNotRenderThread();
  59. #define THROW_IF_NOT_RENDER_THREAD_STATIC msD3D9RenderSystem->throwIfNotRenderThread();
  60. #else
  61. #define THROW_IF_NOT_RENDER_THREAD
  62. #define THROW_IF_NOT_RENDER_THREAD_STATIC
  63. #endif
  64. #define FLOAT2DWORD(f) *((DWORD*)&f)
  65. // Formats to try, in decreasing order of preference
  66. D3DFORMAT ddDepthStencilFormats[]={
  67. D3DFMT_D24FS8,
  68. D3DFMT_D24S8,
  69. D3DFMT_D24X4S4,
  70. D3DFMT_D24X8,
  71. D3DFMT_D15S1,
  72. D3DFMT_D16,
  73. D3DFMT_D32
  74. };
  75. #define NDSFORMATS (sizeof(ddDepthStencilFormats)/sizeof(D3DFORMAT))
  76. namespace CamelotEngine
  77. {
  78. D3D9RenderSystem* D3D9RenderSystem::msD3D9RenderSystem = NULL;
  79. /************************************************************************/
  80. /* PUBLIC INTERFACE */
  81. /************************************************************************/
  82. //---------------------------------------------------------------------
  83. D3D9RenderSystem::D3D9RenderSystem( HINSTANCE hInstance )
  84. : mTexStageDesc(nullptr)
  85. , mNumTexStages(0)
  86. , mCurrentDrawOperation(DOT_TRIANGLE_LIST)
  87. {
  88. // update singleton access pointer.
  89. msD3D9RenderSystem = this;
  90. // set the instance being passed
  91. mhInstance = hInstance;
  92. // set pointers to NULL
  93. mpD3D = NULL;
  94. mDriverList = NULL;
  95. mActiveD3DDriver = NULL;
  96. mUseNVPerfHUD = false;
  97. mHLSLProgramFactory = NULL;
  98. mCgProgramFactory = NULL;
  99. mDeviceManager = NULL;
  100. mResourceManager = nullptr;
  101. mScissorRect.left = 0;
  102. mScissorRect.right = 1280;
  103. mScissorRect.top = 0;
  104. mScissorRect.bottom = 720;
  105. }
  106. //---------------------------------------------------------------------
  107. D3D9RenderSystem::~D3D9RenderSystem()
  108. {
  109. // This needs to be called from the child class, since destroy_internal is virtual
  110. queueCommand(boost::bind(&D3D9RenderSystem::destroy_internal, this), true);
  111. }
  112. const String& D3D9RenderSystem::getName() const
  113. {
  114. static String strName( "D3D9RenderSystem");
  115. return strName;
  116. }
  117. const String& D3D9RenderSystem::getShadingLanguageName() const
  118. {
  119. static String strName("hlsl");
  120. return strName;
  121. }
  122. void D3D9RenderSystem::initialize_internal()
  123. {
  124. THROW_IF_NOT_RENDER_THREAD;
  125. // Create the resource manager.
  126. mResourceManager = CM_NEW(D3D9ResourceManager, GenAlloc) D3D9ResourceManager();
  127. // Create our Direct3D object
  128. if( NULL == (mpD3D = Direct3DCreate9(D3D_SDK_VERSION)) )
  129. CM_EXCEPT(InternalErrorException, "Failed to create Direct3D9 object");
  130. RenderWindow* autoWindow = NULL;
  131. // Init using current settings
  132. mActiveD3DDriver = getDirect3DDrivers()->item(0); // TODO - We always use the first driver
  133. if( !mActiveD3DDriver )
  134. CM_EXCEPT(InvalidParametersException, "Problems finding requested Direct3D driver!" );
  135. // get driver version
  136. mDriverVersion.major = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  137. mDriverVersion.minor = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  138. mDriverVersion.release = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  139. mDriverVersion.build = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  140. // Create the device manager.
  141. mDeviceManager = CM_NEW(D3D9DeviceManager, GenAlloc) D3D9DeviceManager();
  142. // Create the texture manager for use by others
  143. TextureManager::startUp(CM_NEW(D3D9TextureManager, GenAlloc) D3D9TextureManager());
  144. // Also create hardware buffer manager
  145. HardwareBufferManager::startUp(CM_NEW(D3D9HardwareBufferManager, GenAlloc) D3D9HardwareBufferManager());
  146. // Create the GPU program manager
  147. GpuProgramManager::startUp(CM_NEW(D3D9GpuProgramManager, GenAlloc) D3D9GpuProgramManager());
  148. // Create & register HLSL factory
  149. mHLSLProgramFactory = CM_NEW(D3D9HLSLProgramFactory, GenAlloc) D3D9HLSLProgramFactory();
  150. // Create & register Cg factory
  151. mCgProgramFactory = CM_NEW(CgProgramFactory, GenAlloc) CgProgramFactory();
  152. // Create render window manager
  153. RenderWindowManager::startUp(CM_NEW(D3D9RenderWindowManager, GenAlloc) D3D9RenderWindowManager(this));
  154. // Create render state manager
  155. RenderStateManager::startUp(CM_NEW(RenderStateManager, GenAlloc) RenderStateManager());
  156. BuiltinMaterialManager::startUp(CM_NEW(D3D9BuiltinMaterialManager, GenAlloc) D3D9BuiltinMaterialManager());
  157. // call superclass method
  158. RenderSystem::initialize_internal();
  159. }
  160. //---------------------------------------------------------------------
  161. void D3D9RenderSystem::destroy_internal()
  162. {
  163. if(mTexStageDesc != nullptr)
  164. {
  165. CM_DELETE_ARRAY(mTexStageDesc, sD3DTextureStageDesc, mNumTexStages, GenAlloc);
  166. mTexStageDesc = nullptr;
  167. }
  168. RenderSystem::destroy_internal();
  169. if(mDeviceManager != nullptr)
  170. {
  171. CM_DELETE(mDeviceManager, D3D9DeviceManager, GenAlloc);
  172. mDeviceManager = nullptr;
  173. }
  174. if(mDriverList != nullptr)
  175. {
  176. CM_DELETE(mDriverList, D3D9DriverList, GenAlloc);
  177. mDriverList = nullptr;
  178. }
  179. mActiveD3DDriver = NULL;
  180. BuiltinMaterialManager::shutDown();
  181. TextureManager::shutDown();
  182. HardwareBufferManager::shutDown();
  183. GpuProgramManager::shutDown();
  184. RenderWindowManager::shutDown();
  185. RenderStateManager::shutDown();
  186. // Deleting the HLSL program factory
  187. if (mHLSLProgramFactory)
  188. {
  189. HighLevelGpuProgramManager::instance().removeFactory(mHLSLProgramFactory);
  190. CM_DELETE(mHLSLProgramFactory, D3D9HLSLProgramFactory, GenAlloc);
  191. mHLSLProgramFactory = 0;
  192. }
  193. if(mCgProgramFactory)
  194. {
  195. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  196. CM_DELETE(mCgProgramFactory, CgProgramFactory, GenAlloc);
  197. mCgProgramFactory = 0;
  198. }
  199. SAFE_RELEASE( mpD3D );
  200. if(mResourceManager != nullptr)
  201. {
  202. CM_DELETE(mResourceManager, D3D9ResourceManager, GenAlloc);
  203. mResourceManager = nullptr;
  204. }
  205. msD3D9RenderSystem = NULL;
  206. }
  207. //--------------------------------------------------------------------
  208. void D3D9RenderSystem::_notifyWindowCreated(RenderWindow& renderWindow)
  209. {
  210. THROW_IF_NOT_RENDER_THREAD;
  211. D3D9RenderWindow* d3d9renderWindow = static_cast<D3D9RenderWindow*>(&renderWindow);
  212. String msg;
  213. mResourceManager->lockDeviceAccess();
  214. try
  215. {
  216. mDeviceManager->linkRenderWindow(d3d9renderWindow);
  217. }
  218. catch (const CamelotEngine::RenderingAPIException&)
  219. {
  220. // after catching the exception, clean up
  221. mResourceManager->unlockDeviceAccess();
  222. // re-throw
  223. throw;
  224. }
  225. mResourceManager->unlockDeviceAccess();
  226. updateRenderSystemCapabilities(d3d9renderWindow);
  227. }
  228. void D3D9RenderSystem::bindGpuProgram(HGpuProgram prg)
  229. {
  230. THROW_IF_NOT_RENDER_THREAD;
  231. if(!prg.isLoaded())
  232. return;
  233. GpuProgramPtr bindingPrg = prg->getBindingDelegate();
  234. HRESULT hr;
  235. switch (bindingPrg->getType())
  236. {
  237. case GPT_VERTEX_PROGRAM:
  238. hr = getActiveD3D9Device()->SetVertexShader(
  239. static_cast<D3D9GpuVertexProgram*>(bindingPrg.get())->getVertexShader());
  240. if (FAILED(hr))
  241. {
  242. CM_EXCEPT(RenderingAPIException, "Error calling SetVertexShader");
  243. }
  244. break;
  245. case GPT_FRAGMENT_PROGRAM:
  246. hr = getActiveD3D9Device()->SetPixelShader(
  247. static_cast<D3D9GpuFragmentProgram*>(bindingPrg.get())->getPixelShader());
  248. if (FAILED(hr))
  249. {
  250. CM_EXCEPT(RenderingAPIException, "Error calling SetPixelShader");
  251. }
  252. break;
  253. };
  254. // Make sure texcoord index is equal to stage value, As SDK Doc suggests:
  255. // "When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value."
  256. // This solves such an errors when working with the Debug runtime -
  257. // "Direct3D9: (ERROR) :Stage 1 - Texture coordinate index in the stage must be equal to the stage index when programmable vertex pipeline is used".
  258. for (unsigned int nStage=0; nStage < 8; ++nStage)
  259. __SetTextureStageState(nStage, D3DTSS_TEXCOORDINDEX, nStage);
  260. RenderSystem::bindGpuProgram(prg);
  261. }
  262. void D3D9RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  263. {
  264. THROW_IF_NOT_RENDER_THREAD;
  265. HRESULT hr;
  266. switch(gptype)
  267. {
  268. case GPT_VERTEX_PROGRAM:
  269. hr = getActiveD3D9Device()->SetVertexShader(NULL);
  270. if (FAILED(hr))
  271. {
  272. CM_EXCEPT(RenderingAPIException, "Error resetting SetVertexShader to NULL");
  273. }
  274. break;
  275. case GPT_FRAGMENT_PROGRAM:
  276. hr = getActiveD3D9Device()->SetPixelShader(NULL);
  277. if (FAILED(hr))
  278. {
  279. CM_EXCEPT(RenderingAPIException, "Error resetting SetPixelShader to NULL");
  280. }
  281. break;
  282. };
  283. RenderSystem::unbindGpuProgram(gptype);
  284. }
  285. //---------------------------------------------------------------------
  286. void D3D9RenderSystem::bindGpuParams(GpuProgramType gptype, GpuParamsPtr params)
  287. {
  288. THROW_IF_NOT_RENDER_THREAD;
  289. const GpuParamDesc& paramDesc = params->getParamDesc();
  290. for(auto iter = paramDesc.samplers.begin(); iter != paramDesc.samplers.end(); ++iter)
  291. {
  292. HSamplerState& samplerState = params->getSamplerState(iter->second.slot);
  293. if(samplerState == nullptr)
  294. setSamplerState(gptype, iter->second.slot, SamplerState::getDefault());
  295. else
  296. setSamplerState(gptype, iter->second.slot, samplerState.getInternalPtr());
  297. }
  298. for(auto iter = paramDesc.textures.begin(); iter != paramDesc.textures.end(); ++iter)
  299. {
  300. HTexture texture = params->getTexture(iter->second.slot);
  301. if(!texture.isLoaded())
  302. setTexture(gptype, iter->second.slot, false, nullptr);
  303. else
  304. setTexture(gptype, iter->second.slot, true, texture.getInternalPtr());
  305. }
  306. HRESULT hr;
  307. switch(gptype)
  308. {
  309. case GPT_VERTEX_PROGRAM:
  310. {
  311. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  312. {
  313. const GpuParamDataDesc& paramDesc = iter->second;
  314. GpuParamBlockPtr paramBlock = params->getParamBlock(paramDesc.paramBlockSlot);
  315. const GpuParamBlockBuffer* currentBlockBuffer = paramBlock->getBindableBuffer();
  316. const UINT8* ptrData = currentBlockBuffer->getDataPtr(paramDesc.cpuMemOffset * sizeof(UINT32));
  317. switch(paramDesc.type)
  318. {
  319. case GPDT_FLOAT1:
  320. case GPDT_FLOAT2:
  321. case GPDT_FLOAT3:
  322. case GPDT_FLOAT4:
  323. case GPDT_MATRIX_2X2:
  324. case GPDT_MATRIX_2X3:
  325. case GPDT_MATRIX_2X4:
  326. case GPDT_MATRIX_3X2:
  327. case GPDT_MATRIX_3X3:
  328. case GPDT_MATRIX_3X4:
  329. case GPDT_MATRIX_4X2:
  330. case GPDT_MATRIX_4X3:
  331. case GPDT_MATRIX_4X4:
  332. {
  333. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  334. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  335. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantF(paramDesc.gpuMemOffset, (const float*)ptrData, slotCount)))
  336. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader float parameters.");
  337. break;
  338. }
  339. case GPDT_INT1:
  340. case GPDT_INT2:
  341. case GPDT_INT3:
  342. case GPDT_INT4:
  343. {
  344. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  345. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  346. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantI(paramDesc.gpuMemOffset, (const INT32*)ptrData, slotCount)))
  347. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader int parameters.");
  348. break;
  349. }
  350. case GPDT_BOOL:
  351. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantB(paramDesc.gpuMemOffset, (const BOOL*)ptrData, paramDesc.arraySize)))
  352. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader bool parameters.");
  353. break;
  354. }
  355. }
  356. }
  357. break;
  358. case GPT_FRAGMENT_PROGRAM:
  359. {
  360. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  361. {
  362. const GpuParamDataDesc& paramDesc = iter->second;
  363. GpuParamBlockPtr paramBlock = params->getParamBlock(paramDesc.paramBlockSlot);
  364. const GpuParamBlockBuffer* currentBlockBuffer = paramBlock->getBindableBuffer();
  365. const UINT8* ptrData = currentBlockBuffer->getDataPtr(paramDesc.cpuMemOffset * sizeof(UINT32));
  366. switch(paramDesc.type)
  367. {
  368. case GPDT_FLOAT1:
  369. case GPDT_FLOAT2:
  370. case GPDT_FLOAT3:
  371. case GPDT_FLOAT4:
  372. case GPDT_MATRIX_2X2:
  373. case GPDT_MATRIX_2X3:
  374. case GPDT_MATRIX_2X4:
  375. case GPDT_MATRIX_3X2:
  376. case GPDT_MATRIX_3X3:
  377. case GPDT_MATRIX_3X4:
  378. case GPDT_MATRIX_4X2:
  379. case GPDT_MATRIX_4X3:
  380. case GPDT_MATRIX_4X4:
  381. {
  382. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  383. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  384. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantF(paramDesc.gpuMemOffset, (const float*)ptrData, slotCount)))
  385. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader float parameters.");
  386. break;
  387. }
  388. case GPDT_INT1:
  389. case GPDT_INT2:
  390. case GPDT_INT3:
  391. case GPDT_INT4:
  392. {
  393. UINT32 slotCount = (paramDesc.elementSize / 4) * paramDesc.arraySize;
  394. assert (paramDesc.elementSize % 4 == 0 && "Should not have any elements less than 4 wide for D3D9");
  395. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantI(paramDesc.gpuMemOffset, (const INT32*)ptrData, slotCount)))
  396. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader int parameters.");
  397. break;
  398. }
  399. case GPDT_BOOL:
  400. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantB(paramDesc.gpuMemOffset, (const BOOL*)ptrData, paramDesc.arraySize)))
  401. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader bool parameters.");
  402. break;
  403. }
  404. }
  405. }
  406. break;
  407. };
  408. }
  409. //---------------------------------------------------------------------
  410. void D3D9RenderSystem::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr& tex)
  411. {
  412. THROW_IF_NOT_RENDER_THREAD;
  413. if(gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_VERTEX_PROGRAM)
  414. {
  415. LOGWRN("D3D9 cannot assign textures to this gpu program type: " + toString(gptype));
  416. return;
  417. }
  418. if(gptype == GPT_VERTEX_PROGRAM)
  419. {
  420. unit = D3DVERTEXTEXTURESAMPLER0 + unit; // Vertex stage uses special samplers
  421. }
  422. HRESULT hr;
  423. D3D9TexturePtr dt = std::static_pointer_cast<D3D9Texture>(tex);
  424. if (enabled && (dt != nullptr))
  425. {
  426. IDirect3DBaseTexture9 *pTex = dt->getTexture_internal();
  427. if (mTexStageDesc[unit].pTex != pTex)
  428. {
  429. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(unit), pTex);
  430. if( hr != S_OK )
  431. {
  432. String str = "Unable to set texture in D3D9";
  433. CM_EXCEPT(RenderingAPIException, str);
  434. }
  435. // set stage desc.
  436. mTexStageDesc[unit].pTex = pTex;
  437. mTexStageDesc[unit].texType = D3D9Mappings::get(dt->getTextureType());
  438. // Set gamma now too
  439. if (dt->isHardwareGammaReadToBeUsed())
  440. {
  441. __SetSamplerState(static_cast<DWORD>(unit), D3DSAMP_SRGBTEXTURE, TRUE);
  442. }
  443. else
  444. {
  445. __SetSamplerState(static_cast<DWORD>(unit), D3DSAMP_SRGBTEXTURE, FALSE);
  446. }
  447. }
  448. }
  449. else
  450. {
  451. if (mTexStageDesc[unit].pTex != 0)
  452. {
  453. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(unit), 0);
  454. if( hr != S_OK )
  455. {
  456. String str = "Unable to disable texture '" + toString(unit) + "' in D3D9";
  457. CM_EXCEPT(RenderingAPIException, str);
  458. }
  459. }
  460. hr = __SetTextureStageState(static_cast<DWORD>(unit), D3DTSS_COLOROP, D3DTOP_DISABLE);
  461. if( hr != S_OK )
  462. {
  463. String str = "Unable to disable texture '" + toString(unit) + "' in D3D9";
  464. CM_EXCEPT(RenderingAPIException, str);
  465. }
  466. // set stage desc. to defaults
  467. mTexStageDesc[unit].pTex = 0;
  468. mTexStageDesc[unit].coordIndex = 0;
  469. mTexStageDesc[unit].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  470. }
  471. }
  472. //-----------------------------------------------------------------------
  473. void D3D9RenderSystem::setSamplerState(GpuProgramType gptype, UINT16 unit, const SamplerStatePtr& state)
  474. {
  475. THROW_IF_NOT_RENDER_THREAD;
  476. if(gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_VERTEX_PROGRAM)
  477. {
  478. LOGWRN("D3D9 doesn't support this gpu program type: " + toString(gptype));
  479. return;
  480. }
  481. if(gptype == GPT_VERTEX_PROGRAM)
  482. {
  483. unit = D3DVERTEXTEXTURESAMPLER0 + unit; // Vertex stage uses special samplers
  484. }
  485. // Set texture layer filtering
  486. setTextureFiltering(unit, FT_MIN, state->getTextureFiltering(FT_MIN));
  487. setTextureFiltering(unit, FT_MAG, state->getTextureFiltering(FT_MAG));
  488. setTextureFiltering(unit, FT_MIP, state->getTextureFiltering(FT_MIP));
  489. // Set texture layer filtering
  490. setTextureAnisotropy(unit, state->getTextureAnisotropy());
  491. // Set mipmap biasing
  492. setTextureMipmapBias(unit, state->getTextureMipmapBias());
  493. // Texture addressing mode
  494. const UVWAddressingMode& uvw = state->getTextureAddressingMode();
  495. setTextureAddressingMode(unit, uvw);
  496. // Set border color
  497. setTextureBorderColor(unit, state->getBorderColor());
  498. }
  499. //-----------------------------------------------------------------------
  500. void D3D9RenderSystem::setBlendState(const BlendStatePtr& blendState)
  501. {
  502. THROW_IF_NOT_RENDER_THREAD;
  503. // Alpha to coverage
  504. setAlphaToCoverage(blendState->getAlphaToCoverageEnabled());
  505. // Blend states
  506. // DirectX 9 doesn't allow us to specify blend state per render target, so we just use the first one.
  507. if(blendState->getBlendEnabled(0))
  508. {
  509. setSceneBlending(blendState->getSrcBlend(0), blendState->getDstBlend(0), blendState->getAlphaSrcBlend(0), blendState->getAlphaDstBlend(0)
  510. , blendState->getBlendOperation(0), blendState->getAlphaBlendOperation(0));
  511. }
  512. else
  513. {
  514. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  515. }
  516. // Color write mask
  517. UINT8 writeMask = blendState->getRenderTargetWriteMask(0);
  518. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  519. }
  520. //----------------------------------------------------------------------
  521. void D3D9RenderSystem::setRasterizerState(const RasterizerStatePtr& rasterizerState)
  522. {
  523. THROW_IF_NOT_RENDER_THREAD;
  524. setDepthBias((float)rasterizerState->getDepthBias(), rasterizerState->getSlopeScaledDepthBias());
  525. setCullingMode(rasterizerState->getCullMode());
  526. setPolygonMode(rasterizerState->getPolygonMode());
  527. setScissorTestEnable(rasterizerState->getScissorEnable());
  528. setMultisampleAntialiasEnable(rasterizerState->getMultisampleEnable());
  529. setAntialiasedLineEnable(rasterizerState->getAntialiasedLineEnable());
  530. }
  531. //----------------------------------------------------------------------
  532. void D3D9RenderSystem::setDepthStencilState(const DepthStencilStatePtr& depthStencilState, UINT32 stencilRefValue)
  533. {
  534. THROW_IF_NOT_RENDER_THREAD;
  535. // Set stencil buffer options
  536. setStencilCheckEnabled(depthStencilState->getStencilEnable());
  537. setStencilBufferOperations(depthStencilState->getStencilFrontFailOp(), depthStencilState->getStencilFrontZFailOp(), depthStencilState->getStencilFrontPassOp(), true);
  538. setStencilBufferFunc(depthStencilState->getStencilFrontCompFunc(), true);
  539. setStencilBufferOperations(depthStencilState->getStencilBackFailOp(), depthStencilState->getStencilBackZFailOp(), depthStencilState->getStencilBackPassOp(), false);
  540. setStencilBufferFunc(depthStencilState->getStencilBackCompFunc(), false);
  541. setStencilBufferReadMask(depthStencilState->getStencilReadMask());
  542. setStencilBufferWriteMask(depthStencilState->getStencilWriteMask());
  543. // Set depth buffer options
  544. setDepthBufferCheckEnabled(depthStencilState->getDepthReadEnable());
  545. setDepthBufferWriteEnabled(depthStencilState->getDepthWriteEnable());
  546. setDepthBufferFunction(depthStencilState->getDepthComparisonFunc());
  547. // Set stencil ref value
  548. setStencilRefValue(stencilRefValue);
  549. }
  550. //---------------------------------------------------------------------
  551. void D3D9RenderSystem::setTextureMipmapBias(UINT16 unit, float bias)
  552. {
  553. THROW_IF_NOT_RENDER_THREAD;
  554. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  555. {
  556. // ugh - have to pass float data through DWORD with no conversion
  557. HRESULT hr = __SetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MIPMAPLODBIAS,
  558. *(DWORD*)&bias);
  559. if(FAILED(hr))
  560. CM_EXCEPT(RenderingAPIException, "Unable to set texture mipmap bias");
  561. }
  562. }
  563. //---------------------------------------------------------------------
  564. void D3D9RenderSystem::setTextureAddressingMode( UINT16 stage,
  565. const UVWAddressingMode& uvw )
  566. {
  567. THROW_IF_NOT_RENDER_THREAD;
  568. HRESULT hr;
  569. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSU, D3D9Mappings::get(uvw.u, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  570. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for U" );
  571. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSV, D3D9Mappings::get(uvw.v, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  572. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for V");
  573. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSW, D3D9Mappings::get(uvw.w, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  574. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for W");
  575. }
  576. //-----------------------------------------------------------------------------
  577. void D3D9RenderSystem::setTextureBorderColor(UINT16 stage,
  578. const Color& colour)
  579. {
  580. THROW_IF_NOT_RENDER_THREAD;
  581. HRESULT hr;
  582. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_BORDERCOLOR, colour.getAsARGB()) ) )
  583. CM_EXCEPT(RenderingAPIException, "Failed to set texture border colour");
  584. }
  585. //---------------------------------------------------------------------
  586. void D3D9RenderSystem::setSceneBlending( BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  587. {
  588. THROW_IF_NOT_RENDER_THREAD;
  589. HRESULT hr;
  590. if( sourceFactor == BF_ONE && destFactor == BF_ZERO)
  591. {
  592. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  593. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  594. }
  595. else
  596. {
  597. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  598. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  599. if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE)))
  600. CM_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  601. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  602. CM_EXCEPT(RenderingAPIException, "Failed to set source blend");
  603. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  604. CM_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  605. }
  606. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  607. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  608. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(op))))
  609. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  610. }
  611. //---------------------------------------------------------------------
  612. void D3D9RenderSystem::setSceneBlending( BlendFactor sourceFactor, BlendFactor destFactor, BlendFactor sourceFactorAlpha,
  613. BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp )
  614. {
  615. THROW_IF_NOT_RENDER_THREAD;
  616. HRESULT hr;
  617. if( sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  618. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  619. {
  620. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  621. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  622. }
  623. else
  624. {
  625. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  626. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  627. if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE)))
  628. CM_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  629. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  630. CM_EXCEPT(RenderingAPIException, "Failed to set source blend");
  631. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  632. CM_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  633. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLENDALPHA, D3D9Mappings::get(sourceFactorAlpha) ) ) )
  634. CM_EXCEPT(RenderingAPIException, "Failed to set alpha source blend");
  635. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLENDALPHA, D3D9Mappings::get(destFactorAlpha) ) ) )
  636. CM_EXCEPT(RenderingAPIException, "Failed to set alpha destination blend");
  637. }
  638. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  639. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  640. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(alphaOp))))
  641. CM_EXCEPT(RenderingAPIException, "Failed to set alpha scene blending operation option");
  642. }
  643. //---------------------------------------------------------------------
  644. void D3D9RenderSystem::setAlphaTest(CompareFunction func, unsigned char value)
  645. {
  646. THROW_IF_NOT_RENDER_THREAD;
  647. HRESULT hr;
  648. if (func != CMPF_ALWAYS_PASS)
  649. {
  650. if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ) ) )
  651. CM_EXCEPT(RenderingAPIException, "Failed to enable alpha testing");
  652. }
  653. else
  654. {
  655. if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ) ) )
  656. CM_EXCEPT(RenderingAPIException, "Failed to disable alpha testing");
  657. }
  658. // Set always just be sure
  659. if( FAILED( hr = __SetRenderState( D3DRS_ALPHAFUNC, D3D9Mappings::get(func) ) ) )
  660. CM_EXCEPT(RenderingAPIException, "Failed to set alpha reject function");
  661. if( FAILED( hr = __SetRenderState( D3DRS_ALPHAREF, value ) ) )
  662. CM_EXCEPT(RenderingAPIException, "Failed to set render state D3DRS_ALPHAREF");
  663. }
  664. //---------------------------------------------------------------------
  665. void D3D9RenderSystem::setAlphaToCoverage(bool enable)
  666. {
  667. THROW_IF_NOT_RENDER_THREAD;
  668. HRESULT hr;
  669. static bool lasta2c = false;
  670. // Alpha to coverage
  671. if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  672. {
  673. // Vendor-specific hacks on renderstate, gotta love 'em
  674. if (getCapabilities()->getVendor() == GPU_NVIDIA)
  675. {
  676. if (enable)
  677. {
  678. if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C') ) ) )
  679. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  680. }
  681. else
  682. {
  683. if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, D3DFMT_UNKNOWN ) ) )
  684. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  685. }
  686. }
  687. else if ((getCapabilities()->getVendor() == GPU_ATI))
  688. {
  689. if (enable)
  690. {
  691. if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','1') ) ) )
  692. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  693. }
  694. else
  695. {
  696. // discovered this through trial and error, seems to work
  697. if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','0') ) ) )
  698. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  699. }
  700. }
  701. lasta2c = enable;
  702. }
  703. }
  704. //---------------------------------------------------------------------
  705. void D3D9RenderSystem::setCullingMode( CullingMode mode )
  706. {
  707. THROW_IF_NOT_RENDER_THREAD;
  708. mCullingMode = mode;
  709. HRESULT hr;
  710. bool flip = ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  711. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding));
  712. if( FAILED (hr = __SetRenderState(D3DRS_CULLMODE,
  713. D3D9Mappings::get(mode, flip))) )
  714. CM_EXCEPT(RenderingAPIException, "Failed to set culling mode");
  715. }
  716. //---------------------------------------------------------------------
  717. void D3D9RenderSystem::setDepthBufferParams( bool depthTest, bool depthWrite, CompareFunction depthFunction )
  718. {
  719. THROW_IF_NOT_RENDER_THREAD;
  720. setDepthBufferCheckEnabled( depthTest );
  721. setDepthBufferWriteEnabled( depthWrite );
  722. setDepthBufferFunction( depthFunction );
  723. }
  724. //---------------------------------------------------------------------
  725. void D3D9RenderSystem::setDepthBufferCheckEnabled( bool enabled )
  726. {
  727. THROW_IF_NOT_RENDER_THREAD;
  728. HRESULT hr;
  729. if( enabled )
  730. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
  731. else
  732. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
  733. if( FAILED( hr ) )
  734. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer test state");
  735. }
  736. //---------------------------------------------------------------------
  737. void D3D9RenderSystem::setDepthBufferWriteEnabled( bool enabled )
  738. {
  739. THROW_IF_NOT_RENDER_THREAD;
  740. HRESULT hr;
  741. if( FAILED( hr = __SetRenderState( D3DRS_ZWRITEENABLE, enabled ) ) )
  742. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer write state");
  743. }
  744. //---------------------------------------------------------------------
  745. void D3D9RenderSystem::setDepthBufferFunction( CompareFunction func )
  746. {
  747. THROW_IF_NOT_RENDER_THREAD;
  748. HRESULT hr;
  749. if( FAILED( hr = __SetRenderState( D3DRS_ZFUNC, D3D9Mappings::get(func) ) ) )
  750. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer test function");
  751. }
  752. //---------------------------------------------------------------------
  753. void D3D9RenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  754. {
  755. THROW_IF_NOT_RENDER_THREAD;
  756. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_DEPTHBIAS) != 0)
  757. {
  758. // Negate bias since D3D is backward
  759. // D3D also expresses the constant bias as an absolute value, rather than
  760. // relative to minimum depth unit, so scale to fit
  761. constantBias = -constantBias / 250000.0f;
  762. HRESULT hr = __SetRenderState(D3DRS_DEPTHBIAS, FLOAT2DWORD(constantBias));
  763. if (FAILED(hr))
  764. CM_EXCEPT(RenderingAPIException, "Error setting constant depth bias");
  765. }
  766. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS) != 0)
  767. {
  768. // Negate bias since D3D is backward
  769. slopeScaleBias = -slopeScaleBias;
  770. HRESULT hr = __SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, FLOAT2DWORD(slopeScaleBias));
  771. if (FAILED(hr))
  772. CM_EXCEPT(RenderingAPIException, "Error setting slope scale depth bias");
  773. }
  774. }
  775. //---------------------------------------------------------------------
  776. void D3D9RenderSystem::setColorBufferWriteEnabled(bool red, bool green,
  777. bool blue, bool alpha)
  778. {
  779. THROW_IF_NOT_RENDER_THREAD;
  780. DWORD val = 0;
  781. if (red)
  782. val |= D3DCOLORWRITEENABLE_RED;
  783. if (green)
  784. val |= D3DCOLORWRITEENABLE_GREEN;
  785. if (blue)
  786. val |= D3DCOLORWRITEENABLE_BLUE;
  787. if (alpha)
  788. val |= D3DCOLORWRITEENABLE_ALPHA;
  789. HRESULT hr = __SetRenderState(D3DRS_COLORWRITEENABLE, val);
  790. if (FAILED(hr))
  791. CM_EXCEPT(RenderingAPIException, "Error setting colour write enable flags");
  792. }
  793. //---------------------------------------------------------------------
  794. void D3D9RenderSystem::setPolygonMode(PolygonMode level)
  795. {
  796. THROW_IF_NOT_RENDER_THREAD;
  797. HRESULT hr = __SetRenderState(D3DRS_FILLMODE, D3D9Mappings::get(level));
  798. if (FAILED(hr))
  799. CM_EXCEPT(RenderingAPIException, "Error setting polygon mode.");
  800. }
  801. //---------------------------------------------------------------------
  802. void D3D9RenderSystem::setStencilCheckEnabled(bool enabled)
  803. {
  804. THROW_IF_NOT_RENDER_THREAD;
  805. // Allow stencilling
  806. HRESULT hr = __SetRenderState(D3DRS_STENCILENABLE, enabled);
  807. if (FAILED(hr))
  808. CM_EXCEPT(RenderingAPIException, "Error enabling / disabling stencilling.");
  809. if (mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  810. {
  811. hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
  812. if (FAILED(hr))
  813. CM_EXCEPT(RenderingAPIException, "Error setting 2-sided stencil mode.");
  814. }
  815. else
  816. {
  817. hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
  818. if (FAILED(hr))
  819. CM_EXCEPT(RenderingAPIException, "Error setting 1-sided stencil mode.");
  820. }
  821. }
  822. //---------------------------------------------------------------------
  823. void D3D9RenderSystem::setStencilBufferOperations(StencilOperation stencilFailOp, StencilOperation depthFailOp, StencilOperation passOp, bool ccw)
  824. {
  825. THROW_IF_NOT_RENDER_THREAD;
  826. HRESULT hr;
  827. // 2-sided operation
  828. if (ccw)
  829. {
  830. // fail op
  831. hr = __SetRenderState(D3DRS_CCW_STENCILFAIL, D3D9Mappings::get(stencilFailOp, mInvertVertexWinding));
  832. if (FAILED(hr))
  833. CM_EXCEPT(RenderingAPIException, "Error setting stencil fail operation (ccw).");
  834. // depth fail op
  835. hr = __SetRenderState(D3DRS_CCW_STENCILZFAIL, D3D9Mappings::get(depthFailOp, mInvertVertexWinding));
  836. if (FAILED(hr))
  837. CM_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation (ccw).");
  838. // pass op
  839. hr = __SetRenderState(D3DRS_CCW_STENCILPASS, D3D9Mappings::get(passOp, mInvertVertexWinding));
  840. if (FAILED(hr))
  841. CM_EXCEPT(RenderingAPIException, "Error setting stencil pass operation (ccw).");
  842. }
  843. else
  844. {
  845. // fail op
  846. hr = __SetRenderState(D3DRS_STENCILFAIL, D3D9Mappings::get(stencilFailOp, !mInvertVertexWinding));
  847. if (FAILED(hr))
  848. CM_EXCEPT(RenderingAPIException, "Error setting stencil fail operation (cw).");
  849. // depth fail op
  850. hr = __SetRenderState(D3DRS_STENCILZFAIL, D3D9Mappings::get(depthFailOp, !mInvertVertexWinding));
  851. if (FAILED(hr))
  852. CM_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation (cw).");
  853. // pass op
  854. hr = __SetRenderState(D3DRS_STENCILPASS, D3D9Mappings::get(passOp, !mInvertVertexWinding));
  855. if (FAILED(hr))
  856. CM_EXCEPT(RenderingAPIException, "Error setting stencil pass operation (cw).");
  857. }
  858. }
  859. //---------------------------------------------------------------------
  860. void D3D9RenderSystem::setStencilBufferFunc(CompareFunction func, bool ccw)
  861. {
  862. HRESULT hr;
  863. if(ccw)
  864. hr = __SetRenderState(D3DRS_CCW_STENCILFUNC, D3D9Mappings::get(func));
  865. else
  866. hr = __SetRenderState(D3DRS_STENCILFUNC, D3D9Mappings::get(func));
  867. if (FAILED(hr))
  868. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer test function.");
  869. }
  870. //---------------------------------------------------------------------
  871. void D3D9RenderSystem::setStencilBufferReadMask(UINT32 mask)
  872. {
  873. HRESULT hr = __SetRenderState(D3DRS_STENCILMASK, mask);
  874. if (FAILED(hr))
  875. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer mask.");
  876. }
  877. //--------------------------------------------------------------------
  878. void D3D9RenderSystem::setStencilBufferWriteMask(UINT32 mask)
  879. {
  880. HRESULT hr = __SetRenderState(D3DRS_STENCILWRITEMASK, mask);
  881. if (FAILED(hr))
  882. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer write mask.");
  883. }
  884. //----------------------------------------------------------------------
  885. void D3D9RenderSystem::setStencilRefValue(UINT32 refValue)
  886. {
  887. THROW_IF_NOT_RENDER_THREAD;
  888. HRESULT hr = __SetRenderState(D3DRS_STENCILREF, refValue);
  889. if (FAILED(hr))
  890. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer reference value.");
  891. }
  892. //---------------------------------------------------------------------
  893. void D3D9RenderSystem::setTextureFiltering(UINT16 unit, FilterType ftype,
  894. FilterOptions filter)
  895. {
  896. THROW_IF_NOT_RENDER_THREAD;
  897. HRESULT hr;
  898. D3D9Mappings::eD3DTexType texType = mTexStageDesc[unit].texType;
  899. hr = __SetSamplerState( static_cast<DWORD>(unit), D3D9Mappings::get(ftype),
  900. D3D9Mappings::get(ftype, filter, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps(), texType));
  901. if (FAILED(hr))
  902. CM_EXCEPT(RenderingAPIException, "Failed to set texture filter ");
  903. }
  904. //---------------------------------------------------------------------
  905. void D3D9RenderSystem::setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy)
  906. {
  907. THROW_IF_NOT_RENDER_THREAD;
  908. if (static_cast<DWORD>(maxAnisotropy) > mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy)
  909. maxAnisotropy = mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy;
  910. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  911. __SetSamplerState( static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, maxAnisotropy );
  912. }
  913. //---------------------------------------------------------------------
  914. void D3D9RenderSystem::setRenderTarget(RenderTargetPtr target)
  915. {
  916. THROW_IF_NOT_RENDER_THREAD;
  917. mActiveRenderTarget = target;
  918. HRESULT hr;
  919. // Possibly change device if the target is a window
  920. if (target->isWindow())
  921. {
  922. D3D9RenderWindow* window = static_cast<D3D9RenderWindow*>(target.get());
  923. mDeviceManager->setActiveRenderTargetDevice(window->getDevice());
  924. window->_validateDevice();
  925. }
  926. // Retrieve render surfaces
  927. UINT32 maxRenderTargets = mCurrentCapabilities->getNumMultiRenderTargets();
  928. IDirect3DSurface9** pBack = CM_NEW_ARRAY(IDirect3DSurface9*, maxRenderTargets, ScratchAlloc);
  929. memset(pBack, 0, sizeof(IDirect3DSurface9*) * maxRenderTargets);
  930. target->getCustomAttribute( "DDBACKBUFFER", pBack );
  931. if (!pBack[0])
  932. {
  933. CM_DELETE_ARRAY(pBack, IDirect3DSurface9*, maxRenderTargets, ScratchAlloc);
  934. return;
  935. }
  936. IDirect3DSurface9* pDepth = NULL;
  937. if (!pDepth)
  938. target->getCustomAttribute( "D3DZBUFFER", &pDepth );
  939. // Bind render targets
  940. for(UINT32 x = 0; x < maxRenderTargets; ++x)
  941. {
  942. hr = getActiveD3D9Device()->SetRenderTarget(x, pBack[x]);
  943. if (FAILED(hr))
  944. {
  945. String msg = DXGetErrorDescription(hr);
  946. CM_EXCEPT(RenderingAPIException, "Failed to setRenderTarget : " + msg);
  947. }
  948. }
  949. CM_DELETE_ARRAY(pBack, IDirect3DSurface9*, maxRenderTargets, ScratchAlloc);
  950. hr = getActiveD3D9Device()->SetDepthStencilSurface(pDepth);
  951. if (FAILED(hr))
  952. {
  953. String msg = DXGetErrorDescription(hr);
  954. CM_EXCEPT(RenderingAPIException, "Failed to setDepthStencil : " + msg);
  955. }
  956. }
  957. //---------------------------------------------------------------------
  958. void D3D9RenderSystem::setViewport(ViewportPtr& vp)
  959. {
  960. THROW_IF_NOT_RENDER_THREAD;
  961. assert(vp != nullptr);
  962. // ok, it's different, time to set render target and viewport params
  963. D3DVIEWPORT9 d3dvp;
  964. HRESULT hr;
  965. // Set render target
  966. RenderTargetPtr target = vp->getTarget();
  967. setRenderTarget(target);
  968. setCullingMode( mCullingMode );
  969. // set viewport dimensions
  970. d3dvp.X = vp->getLeft();
  971. d3dvp.Y = vp->getTop();
  972. d3dvp.Width = vp->getWidth();
  973. d3dvp.Height = vp->getHeight();
  974. if (target->requiresTextureFlipping())
  975. {
  976. // Convert "top-left" to "bottom-left"
  977. d3dvp.Y = target->getHeight() - d3dvp.Height - d3dvp.Y;
  978. }
  979. // Z-values from 0.0 to 1.0 (TODO: standardise with OpenGL)
  980. d3dvp.MinZ = 0.0f;
  981. d3dvp.MaxZ = 1.0f;
  982. if( FAILED( hr = getActiveD3D9Device()->SetViewport( &d3dvp ) ) )
  983. CM_EXCEPT(RenderingAPIException, "Failed to set viewport.");
  984. // Set sRGB write mode
  985. __SetRenderState(D3DRS_SRGBWRITEENABLE, target->isHardwareGammaEnabled());
  986. }
  987. //---------------------------------------------------------------------
  988. void D3D9RenderSystem::beginFrame()
  989. {
  990. THROW_IF_NOT_RENDER_THREAD;
  991. HRESULT hr;
  992. if( FAILED( hr = getActiveD3D9Device()->BeginScene() ) )
  993. {
  994. String msg = DXGetErrorDescription(hr);
  995. CM_EXCEPT(RenderingAPIException, "Error beginning frame :" + msg);
  996. }
  997. mDeviceManager->getActiveDevice()->clearDeviceStreams();
  998. }
  999. //---------------------------------------------------------------------
  1000. void D3D9RenderSystem::endFrame()
  1001. {
  1002. THROW_IF_NOT_RENDER_THREAD;
  1003. HRESULT hr;
  1004. if( FAILED( hr = getActiveD3D9Device()->EndScene() ) )
  1005. CM_EXCEPT(RenderingAPIException, "Error ending frame");
  1006. mDeviceManager->destroyInactiveRenderDevices();
  1007. }
  1008. //---------------------------------------------------------------------
  1009. void D3D9RenderSystem::setVertexDeclaration(VertexDeclarationPtr decl)
  1010. {
  1011. THROW_IF_NOT_RENDER_THREAD;
  1012. HRESULT hr;
  1013. std::shared_ptr<D3D9VertexDeclaration> d3ddecl =
  1014. std::static_pointer_cast<D3D9VertexDeclaration>(decl);
  1015. if (FAILED(hr = getActiveD3D9Device()->SetVertexDeclaration(d3ddecl->getD3DVertexDeclaration())))
  1016. {
  1017. CM_EXCEPT(RenderingAPIException, "Unable to set D3D9 vertex declaration");
  1018. }
  1019. }
  1020. //---------------------------------------------------------------------
  1021. void D3D9RenderSystem::setVertexBuffer(UINT32 index, const VertexBufferPtr& buffer)
  1022. {
  1023. THROW_IF_NOT_RENDER_THREAD;
  1024. UINT32 maxBoundVertexBuffers = mCurrentCapabilities->getMaxBoundVertexBuffers();
  1025. if(index < 0 || index >= maxBoundVertexBuffers)
  1026. CM_EXCEPT(InvalidParametersException, "Invalid vertex index: " + toString(index) + ". Valid range is 0 .. " + toString(maxBoundVertexBuffers - 1));
  1027. HRESULT hr;
  1028. if(buffer != nullptr)
  1029. {
  1030. D3D9VertexBuffer* d3d9buf = static_cast<D3D9VertexBuffer*>(buffer.get());
  1031. hr = getActiveD3D9Device()->SetStreamSource(
  1032. static_cast<UINT>(index),
  1033. d3d9buf->getD3D9VertexBuffer(),
  1034. 0,
  1035. static_cast<UINT>(d3d9buf->getVertexSize()) // stride
  1036. );
  1037. }
  1038. else
  1039. {
  1040. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(index), nullptr, 0, 0);
  1041. }
  1042. if (FAILED(hr))
  1043. CM_EXCEPT(RenderingAPIException, "Unable to set D3D9 stream source for buffer binding");
  1044. }
  1045. //---------------------------------------------------------------------
  1046. void D3D9RenderSystem::setIndexBuffer(const IndexBufferPtr& buffer)
  1047. {
  1048. THROW_IF_NOT_RENDER_THREAD;
  1049. D3D9IndexBuffer* d3dIdxBuf = static_cast<D3D9IndexBuffer*>(buffer.get());
  1050. HRESULT hr = getActiveD3D9Device()->SetIndices( d3dIdxBuf->getD3DIndexBuffer() );
  1051. if (FAILED(hr))
  1052. CM_EXCEPT(RenderingAPIException, "Failed to set index buffer");
  1053. }
  1054. //---------------------------------------------------------------------
  1055. void D3D9RenderSystem::setDrawOperation(DrawOperationType op)
  1056. {
  1057. THROW_IF_NOT_RENDER_THREAD;
  1058. mCurrentDrawOperation = op;
  1059. }
  1060. //---------------------------------------------------------------------
  1061. void D3D9RenderSystem::draw(UINT32 vertexCount)
  1062. {
  1063. UINT32 primCount = pointCountToPrimCount(mCurrentDrawOperation, vertexCount);
  1064. HRESULT hr = getActiveD3D9Device()->DrawPrimitive(getD3D9PrimitiveType(), 0, static_cast<UINT>(primCount));
  1065. if( FAILED( hr ) )
  1066. {
  1067. String msg = DXGetErrorDescription(hr);
  1068. CM_EXCEPT(RenderingAPIException, "Failed to DrawPrimitive : " + msg);
  1069. }
  1070. }
  1071. //---------------------------------------------------------------------
  1072. void D3D9RenderSystem::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexCount)
  1073. {
  1074. UINT32 primCount = pointCountToPrimCount(mCurrentDrawOperation, indexCount);
  1075. // do indexed draw operation
  1076. HRESULT hr = getActiveD3D9Device()->DrawIndexedPrimitive(
  1077. getD3D9PrimitiveType(),
  1078. 0,
  1079. 0,
  1080. static_cast<UINT>(vertexCount),
  1081. static_cast<UINT>(startIndex),
  1082. static_cast<UINT>(primCount)
  1083. );
  1084. if( FAILED( hr ) )
  1085. {
  1086. String msg = DXGetErrorDescription(hr);
  1087. CM_EXCEPT(RenderingAPIException, "Failed to DrawIndexedPrimitive : " + msg);
  1088. }
  1089. }
  1090. //---------------------------------------------------------------------
  1091. void D3D9RenderSystem::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  1092. {
  1093. THROW_IF_NOT_RENDER_THREAD;
  1094. mScissorRect.left = static_cast<LONG>(left);
  1095. mScissorRect.top = static_cast<LONG>(top);
  1096. mScissorRect.bottom = static_cast<LONG>(bottom);
  1097. mScissorRect.right = static_cast<LONG>(right);
  1098. }
  1099. //--------------------------------------------------------------------
  1100. void D3D9RenderSystem::setScissorTestEnable(bool enable)
  1101. {
  1102. THROW_IF_NOT_RENDER_THREAD;
  1103. HRESULT hr;
  1104. if (enable)
  1105. {
  1106. if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE)))
  1107. {
  1108. CM_EXCEPT(RenderingAPIException, "Unable to enable scissor rendering state; " + getErrorDescription(hr));
  1109. }
  1110. if (FAILED(hr = getActiveD3D9Device()->SetScissorRect(&mScissorRect)))
  1111. {
  1112. CM_EXCEPT(RenderingAPIException, "Unable to set scissor rectangle; " + getErrorDescription(hr));
  1113. }
  1114. }
  1115. else
  1116. {
  1117. if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE)))
  1118. {
  1119. CM_EXCEPT(RenderingAPIException, "Unable to disable scissor rendering state; " + getErrorDescription(hr));
  1120. }
  1121. }
  1122. }
  1123. //--------------------------------------------------------------------
  1124. void D3D9RenderSystem::setMultisampleAntialiasEnable(bool enable)
  1125. {
  1126. HRESULT hr;
  1127. if(enable)
  1128. {
  1129. if (FAILED(hr = __SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE)))
  1130. {
  1131. CM_EXCEPT(RenderingAPIException, "Unable to enable multisample antialiasing. Error description: " + getErrorDescription(hr));
  1132. }
  1133. }
  1134. else
  1135. {
  1136. if (FAILED(hr = __SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE)))
  1137. {
  1138. CM_EXCEPT(RenderingAPIException, "Unable to disable multisample antialiasing. Error description: " + getErrorDescription(hr));
  1139. }
  1140. }
  1141. }
  1142. //---------------------------------------------------------------------
  1143. void D3D9RenderSystem::setAntialiasedLineEnable(bool enable)
  1144. {
  1145. HRESULT hr;
  1146. if(enable)
  1147. {
  1148. if (FAILED(hr = __SetRenderState(D3DRS_ANTIALIASEDLINEENABLE, TRUE)))
  1149. {
  1150. CM_EXCEPT(RenderingAPIException, "Unable to enable line antialiasing. Error description: " + getErrorDescription(hr));
  1151. }
  1152. }
  1153. else
  1154. {
  1155. if (FAILED(hr = __SetRenderState(D3DRS_ANTIALIASEDLINEENABLE, FALSE)))
  1156. {
  1157. CM_EXCEPT(RenderingAPIException, "Unable to disable line antialiasing. Error description: " + getErrorDescription(hr));
  1158. }
  1159. }
  1160. }
  1161. //---------------------------------------------------------------------
  1162. void D3D9RenderSystem::clear(RenderTargetPtr target, unsigned int buffers,
  1163. const Color& colour, float depth, unsigned short stencil)
  1164. {
  1165. THROW_IF_NOT_RENDER_THREAD;
  1166. RenderTargetPtr previousRenderTarget = mActiveRenderTarget;
  1167. if(target != mActiveRenderTarget)
  1168. {
  1169. previousRenderTarget = mActiveRenderTarget;
  1170. setRenderTarget(target);
  1171. }
  1172. DWORD flags = 0;
  1173. if (buffers & FBT_COLOUR)
  1174. {
  1175. flags |= D3DCLEAR_TARGET;
  1176. }
  1177. if (buffers & FBT_DEPTH)
  1178. {
  1179. flags |= D3DCLEAR_ZBUFFER;
  1180. }
  1181. // Only try to clear the stencil buffer if supported
  1182. if (buffers & FBT_STENCIL && mCurrentCapabilities->hasCapability(RSC_HWSTENCIL))
  1183. {
  1184. flags |= D3DCLEAR_STENCIL;
  1185. }
  1186. HRESULT hr;
  1187. if( FAILED( hr = getActiveD3D9Device()->Clear(
  1188. 0,
  1189. NULL,
  1190. flags,
  1191. colour.getAsARGB(),
  1192. depth,
  1193. stencil ) ) )
  1194. {
  1195. String msg = DXGetErrorDescription(hr);
  1196. CM_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  1197. }
  1198. if(target != previousRenderTarget)
  1199. {
  1200. setRenderTarget(previousRenderTarget);
  1201. }
  1202. }
  1203. //---------------------------------------------------------------------
  1204. IDirect3D9* D3D9RenderSystem::getDirect3D9()
  1205. {
  1206. THROW_IF_NOT_RENDER_THREAD_STATIC;
  1207. IDirect3D9* pDirect3D9 = msD3D9RenderSystem->mpD3D;
  1208. if (pDirect3D9 == NULL)
  1209. {
  1210. CM_EXCEPT(InvalidParametersException, "Direct3D9 interface is NULL !!!");
  1211. }
  1212. return pDirect3D9;
  1213. }
  1214. //---------------------------------------------------------------------
  1215. UINT D3D9RenderSystem::getResourceCreationDeviceCount()
  1216. {
  1217. THROW_IF_NOT_RENDER_THREAD_STATIC;
  1218. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  1219. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  1220. {
  1221. return 1;
  1222. }
  1223. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  1224. {
  1225. return msD3D9RenderSystem->mDeviceManager->getDeviceCount();
  1226. }
  1227. CM_EXCEPT(InvalidParametersException, "Invalid resource creation policy !!!" );
  1228. return 0;
  1229. }
  1230. //---------------------------------------------------------------------
  1231. IDirect3DDevice9* D3D9RenderSystem::getResourceCreationDevice(UINT index)
  1232. {
  1233. THROW_IF_NOT_RENDER_THREAD_STATIC;
  1234. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  1235. IDirect3DDevice9* d3d9Device = NULL;
  1236. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  1237. {
  1238. d3d9Device = msD3D9RenderSystem->getActiveD3D9Device();
  1239. }
  1240. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  1241. {
  1242. d3d9Device = msD3D9RenderSystem->mDeviceManager->getDevice(index)->getD3D9Device();
  1243. }
  1244. else
  1245. {
  1246. CM_EXCEPT(InvalidParametersException, "Invalid resource creation policy !!!" );
  1247. }
  1248. return d3d9Device;
  1249. }
  1250. //---------------------------------------------------------------------
  1251. IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9Device()
  1252. {
  1253. THROW_IF_NOT_RENDER_THREAD_STATIC;
  1254. D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice();
  1255. IDirect3DDevice9* d3d9Device;
  1256. d3d9Device = activeDevice->getD3D9Device();
  1257. if (d3d9Device == NULL)
  1258. {
  1259. CM_EXCEPT(InvalidParametersException, "Current d3d9 device is NULL !!!" );
  1260. }
  1261. return d3d9Device;
  1262. }
  1263. //---------------------------------------------------------------------
  1264. D3D9ResourceManager* D3D9RenderSystem::getResourceManager()
  1265. {
  1266. // No need to check if we're on render thread as this is synced up internally
  1267. return msD3D9RenderSystem->mResourceManager;
  1268. }
  1269. //---------------------------------------------------------------------
  1270. D3D9DeviceManager* D3D9RenderSystem::getDeviceManager()
  1271. {
  1272. THROW_IF_NOT_RENDER_THREAD_STATIC;
  1273. return msD3D9RenderSystem->mDeviceManager;
  1274. }
  1275. /************************************************************************/
  1276. /* UTILITY METHODS */
  1277. /************************************************************************/
  1278. //---------------------------------------------------------------------
  1279. float D3D9RenderSystem::getHorizontalTexelOffset()
  1280. {
  1281. // D3D considers the origin to be in the center of a pixel
  1282. return -0.5f;
  1283. }
  1284. //---------------------------------------------------------------------
  1285. float D3D9RenderSystem::getVerticalTexelOffset()
  1286. {
  1287. // D3D considers the origin to be in the center of a pixel
  1288. return -0.5f;
  1289. }
  1290. //---------------------------------------------------------------------
  1291. float D3D9RenderSystem::getMinimumDepthInputValue()
  1292. {
  1293. // Range [0.0f, 1.0f]
  1294. return 0.0f;
  1295. }
  1296. //---------------------------------------------------------------------
  1297. float D3D9RenderSystem::getMaximumDepthInputValue()
  1298. {
  1299. // Range [0.0f, 1.0f]
  1300. // D3D inverts even identity view matrices, so maximum INPUT is -1.0
  1301. return -1.0f;
  1302. }
  1303. //---------------------------------------------------------------------
  1304. VertexElementType D3D9RenderSystem::getColorVertexElementType() const
  1305. {
  1306. return VET_COLOR_ARGB;
  1307. }
  1308. //---------------------------------------------------------------------
  1309. void D3D9RenderSystem::convertProjectionMatrix(const Matrix4& matrix,
  1310. Matrix4& dest, bool forGpuProgram)
  1311. {
  1312. dest = matrix;
  1313. // Convert depth range from [-1,+1] to [0,1]
  1314. dest[2][0] = (dest[2][0] + dest[3][0]) / 2;
  1315. dest[2][1] = (dest[2][1] + dest[3][1]) / 2;
  1316. dest[2][2] = (dest[2][2] + dest[3][2]) / 2;
  1317. dest[2][3] = (dest[2][3] + dest[3][3]) / 2;
  1318. if (!forGpuProgram)
  1319. {
  1320. // Convert right-handed to left-handed
  1321. dest[0][2] = -dest[0][2];
  1322. dest[1][2] = -dest[1][2];
  1323. dest[2][2] = -dest[2][2];
  1324. dest[3][2] = -dest[3][2];
  1325. }
  1326. }
  1327. /************************************************************************/
  1328. /* PRIVATE */
  1329. /************************************************************************/
  1330. //---------------------------------------------------------------------
  1331. D3D9DriverList* D3D9RenderSystem::getDirect3DDrivers()
  1332. {
  1333. if( !mDriverList )
  1334. mDriverList = CM_NEW(D3D9DriverList, GenAlloc) D3D9DriverList();
  1335. return mDriverList;
  1336. }
  1337. //---------------------------------------------------------------------
  1338. D3DPRIMITIVETYPE D3D9RenderSystem::getD3D9PrimitiveType() const
  1339. {
  1340. switch(mCurrentDrawOperation)
  1341. {
  1342. case DOT_POINT_LIST:
  1343. return D3DPT_POINTLIST;
  1344. case DOT_LINE_LIST:
  1345. return D3DPT_LINELIST;
  1346. case DOT_LINE_STRIP:
  1347. return D3DPT_LINESTRIP;
  1348. case DOT_TRIANGLE_LIST:
  1349. return D3DPT_TRIANGLELIST;
  1350. case DOT_TRIANGLE_STRIP:
  1351. return D3DPT_TRIANGLESTRIP;
  1352. case DOT_TRIANGLE_FAN:
  1353. return D3DPT_TRIANGLEFAN;
  1354. }
  1355. return D3DPT_TRIANGLELIST;
  1356. }
  1357. //---------------------------------------------------------------------
  1358. UINT32 D3D9RenderSystem::pointCountToPrimCount(DrawOperationType type, UINT32 elementCount) const
  1359. {
  1360. DWORD primCount = 0;
  1361. switch(type)
  1362. {
  1363. case DOT_POINT_LIST:
  1364. primCount = elementCount;
  1365. break;
  1366. case DOT_LINE_LIST:
  1367. primCount = elementCount / 2;
  1368. break;
  1369. case DOT_LINE_STRIP:
  1370. primCount = elementCount - 1;
  1371. break;
  1372. case DOT_TRIANGLE_LIST:
  1373. primCount = elementCount / 3;
  1374. break;
  1375. case DOT_TRIANGLE_STRIP:
  1376. primCount = elementCount - 2;
  1377. break;
  1378. case DOT_TRIANGLE_FAN:
  1379. primCount = elementCount - 2;
  1380. break;
  1381. }
  1382. return primCount;
  1383. }
  1384. //---------------------------------------------------------------------
  1385. bool D3D9RenderSystem::_checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen)
  1386. {
  1387. HRESULT hr;
  1388. hr = mpD3D->CheckDeviceMultiSampleType(
  1389. adapterNum,
  1390. deviceType,
  1391. format,
  1392. fullScreen,
  1393. type,
  1394. outQuality);
  1395. if (SUCCEEDED(hr))
  1396. return true;
  1397. else
  1398. return false;
  1399. }
  1400. //---------------------------------------------------------------------
  1401. RenderSystemCapabilities* D3D9RenderSystem::updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow)
  1402. {
  1403. RenderSystemCapabilities* rsc = mCurrentCapabilities;
  1404. if (rsc == NULL)
  1405. rsc = CM_NEW(RenderSystemCapabilities, GenAlloc) RenderSystemCapabilities();
  1406. rsc->setCategoryRelevant(CAPS_CATEGORY_D3D9, true);
  1407. rsc->setDriverVersion(mDriverVersion);
  1408. rsc->setDeviceName(mActiveD3DDriver->DriverDescription());
  1409. rsc->setRenderSystemName(getName());
  1410. // Supports fixed-function
  1411. rsc->setCapability(RSC_FIXED_FUNCTION);
  1412. // Init caps to maximum.
  1413. rsc->setCapability(RSC_ANISOTROPY);
  1414. rsc->setCapability(RSC_AUTOMIPMAP);
  1415. rsc->setCapability(RSC_DOT3);
  1416. rsc->setCapability(RSC_CUBEMAPPING);
  1417. rsc->setCapability(RSC_SCISSOR_TEST);
  1418. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1419. rsc->setCapability(RSC_STENCIL_WRAP);
  1420. rsc->setCapability(RSC_HWOCCLUSION);
  1421. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1422. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1423. rsc->setCapability(RSC_TEXTURE_3D);
  1424. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1425. rsc->setNonPOW2TexturesLimited(false);
  1426. rsc->setNumMultiRenderTargets(CM_MAX_MULTIPLE_RENDER_TARGETS);
  1427. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1428. rsc->setCapability(RSC_POINT_SPRITES);
  1429. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1430. rsc->setMaxPointSize(10.0);
  1431. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1432. rsc->setCapability(RSC_PERSTAGECONSTANT);
  1433. rsc->setCapability(RSC_HWSTENCIL);
  1434. rsc->setStencilBufferBitDepth(8);
  1435. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1436. for (UINT32 i=0; i < mDeviceManager->getDeviceCount(); ++i)
  1437. {
  1438. D3D9Device* device = mDeviceManager->getDevice(i);
  1439. IDirect3DDevice9* d3d9Device = device->getD3D9Device();
  1440. IDirect3DSurface9* pSurf;
  1441. // Check for hardware stencil support
  1442. d3d9Device->GetDepthStencilSurface(&pSurf);
  1443. if (pSurf != NULL)
  1444. {
  1445. D3DSURFACE_DESC surfDesc;
  1446. pSurf->GetDesc(&surfDesc);
  1447. pSurf->Release();
  1448. if (surfDesc.Format != D3DFMT_D15S1 &&
  1449. surfDesc.Format != D3DFMT_D24S8 &&
  1450. surfDesc.Format != D3DFMT_D24X4S4 &&
  1451. surfDesc.Format != D3DFMT_D24FS8)
  1452. rsc->unsetCapability(RSC_HWSTENCIL);
  1453. }
  1454. // Check for hardware occlusion support
  1455. HRESULT hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL);
  1456. if (FAILED(hr))
  1457. rsc->unsetCapability(RSC_HWOCCLUSION);
  1458. }
  1459. // Update RS caps using the minimum value found in adapter list.
  1460. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1461. {
  1462. D3D9Driver* pCurDriver = mDriverList->item(i);
  1463. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  1464. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, 16); // We don't support anything lower than SM3, and 16 is the sampler count determined by the specification
  1465. rsc->setMaxBoundVertexBuffers(static_cast<UINT32>(rkCurCaps.MaxStreams));
  1466. // Check for Anisotropy.
  1467. if (rkCurCaps.MaxAnisotropy <= 1)
  1468. rsc->unsetCapability(RSC_ANISOTROPY);
  1469. // Check automatic mipmap generation.
  1470. if ((rkCurCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) == 0)
  1471. rsc->unsetCapability(RSC_AUTOMIPMAP);
  1472. // Check Dot product 3.
  1473. if ((rkCurCaps.TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) == 0)
  1474. rsc->unsetCapability(RSC_DOT3);
  1475. // Scissor test
  1476. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST) == 0)
  1477. rsc->unsetCapability(RSC_SCISSOR_TEST);
  1478. // Two-sided stencil
  1479. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) == 0)
  1480. rsc->unsetCapability(RSC_TWO_SIDED_STENCIL);
  1481. // stencil wrap
  1482. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_INCR) == 0 ||
  1483. (rkCurCaps.StencilCaps & D3DSTENCILCAPS_DECR) == 0)
  1484. rsc->unsetCapability(RSC_STENCIL_WRAP);
  1485. // User clip planes
  1486. if (rkCurCaps.MaxUserClipPlanes == 0)
  1487. rsc->unsetCapability(RSC_USER_CLIP_PLANES);
  1488. // UBYTE4 type?
  1489. if ((rkCurCaps.DeclTypes & D3DDTCAPS_UBYTE4) == 0)
  1490. rsc->unsetCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1491. // Check cube map support.
  1492. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP) == 0)
  1493. rsc->unsetCapability(RSC_CUBEMAPPING);
  1494. // 3D textures?
  1495. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_VOLUMEMAP) == 0)
  1496. rsc->unsetCapability(RSC_TEXTURE_3D);
  1497. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_POW2)
  1498. {
  1499. // Conditional support for non POW2
  1500. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL)
  1501. rsc->setNonPOW2TexturesLimited(true);
  1502. // Only power of 2 supported.
  1503. else
  1504. rsc->unsetCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1505. }
  1506. // Number of render targets
  1507. if (rkCurCaps.NumSimultaneousRTs < rsc->getNumMultiRenderTargets())
  1508. {
  1509. rsc->setNumMultiRenderTargets(std::min((UINT16)rkCurCaps.NumSimultaneousRTs, (UINT16)CM_MAX_MULTIPLE_RENDER_TARGETS));
  1510. }
  1511. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS) == 0)
  1512. {
  1513. rsc->unsetCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1514. }
  1515. // Point sprites
  1516. if (rkCurCaps.MaxPointSize <= 1.0f)
  1517. {
  1518. rsc->unsetCapability(RSC_POINT_SPRITES);
  1519. // sprites and extended parameters go together in D3D
  1520. rsc->unsetCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1521. }
  1522. // Take the minimum point size.
  1523. if (rkCurCaps.MaxPointSize < rsc->getMaxPointSize())
  1524. rsc->setMaxPointSize(rkCurCaps.MaxPointSize);
  1525. // Mipmap LOD biasing?
  1526. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_MIPMAPLODBIAS) == 0)
  1527. rsc->unsetCapability(RSC_MIPMAP_LOD_BIAS);
  1528. // Do we support per-stage src_manual constants?
  1529. // HACK - ATI drivers seem to be buggy and don't support per-stage constants properly?
  1530. // TODO: move this to RSC
  1531. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_PERSTAGECONSTANT) == 0)
  1532. rsc->unsetCapability(RSC_PERSTAGECONSTANT);
  1533. // Advanced blend operations? min max subtract rev
  1534. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_BLENDOP) == 0)
  1535. rsc->unsetCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1536. }
  1537. // Blending between stages supported
  1538. rsc->setCapability(RSC_BLENDING);
  1539. // We always support compression, D3DX will decompress if device does not support
  1540. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1541. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1542. // We always support VBOs
  1543. rsc->setCapability(RSC_VBO);
  1544. convertVertexShaderCaps(rsc);
  1545. convertPixelShaderCaps(rsc);
  1546. // Adapter details
  1547. const D3DADAPTER_IDENTIFIER9& adapterID = mActiveD3DDriver->getAdapterIdentifier();
  1548. // determine vendor
  1549. // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id
  1550. switch(adapterID.VendorId)
  1551. {
  1552. case 0x10DE:
  1553. rsc->setVendor(GPU_NVIDIA);
  1554. break;
  1555. case 0x1002:
  1556. rsc->setVendor(GPU_ATI);
  1557. break;
  1558. case 0x163C:
  1559. case 0x8086:
  1560. rsc->setVendor(GPU_INTEL);
  1561. break;
  1562. case 0x5333:
  1563. rsc->setVendor(GPU_S3);
  1564. break;
  1565. case 0x3D3D:
  1566. rsc->setVendor(GPU_3DLABS);
  1567. break;
  1568. case 0x102B:
  1569. rsc->setVendor(GPU_MATROX);
  1570. break;
  1571. case 0x1039:
  1572. rsc->setVendor(GPU_SIS);
  1573. break;
  1574. default:
  1575. rsc->setVendor(GPU_UNKNOWN);
  1576. break;
  1577. };
  1578. // Infinite projection?
  1579. // We have no capability for this, so we have to base this on our
  1580. // experience and reports from users
  1581. // Non-vertex program capable hardware does not appear to support it
  1582. if (rsc->hasCapability(RSC_VERTEX_PROGRAM))
  1583. {
  1584. // GeForce4 Ti (and presumably GeForce3) does not
  1585. // render infinite projection properly, even though it does in GL
  1586. // So exclude all cards prior to the FX range from doing infinite
  1587. if (rsc->getVendor() != GPU_NVIDIA || // not nVidia
  1588. !((adapterID.DeviceId >= 0x200 && adapterID.DeviceId <= 0x20F) || //gf3
  1589. (adapterID.DeviceId >= 0x250 && adapterID.DeviceId <= 0x25F) || //gf4ti
  1590. (adapterID.DeviceId >= 0x280 && adapterID.DeviceId <= 0x28F) || //gf4ti
  1591. (adapterID.DeviceId >= 0x170 && adapterID.DeviceId <= 0x18F) || //gf4 go
  1592. (adapterID.DeviceId >= 0x280 && adapterID.DeviceId <= 0x28F))) //gf4ti go
  1593. {
  1594. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1595. }
  1596. }
  1597. // We always support rendertextures bigger than the frame buffer
  1598. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1599. // Determine if any floating point texture format is supported
  1600. D3DFORMAT floatFormats[6] = {D3DFMT_R16F, D3DFMT_G16R16F,
  1601. D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F,
  1602. D3DFMT_A32B32G32R32F};
  1603. IDirect3DSurface9* bbSurf;
  1604. renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  1605. D3DSURFACE_DESC bbSurfDesc;
  1606. bbSurf->GetDesc(&bbSurfDesc);
  1607. for (int i = 0; i < 6; ++i)
  1608. {
  1609. if (SUCCEEDED(mpD3D->CheckDeviceFormat(mActiveD3DDriver->getAdapterNumber(),
  1610. D3DDEVTYPE_HAL, bbSurfDesc.Format,
  1611. 0, D3DRTYPE_TEXTURE, floatFormats[i])))
  1612. {
  1613. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1614. break;
  1615. }
  1616. }
  1617. // Vertex textures
  1618. if (rsc->isShaderProfileSupported("vs_3_0"))
  1619. {
  1620. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1621. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, 4);
  1622. rsc->setNumCombinedTextureUnits(rsc->getNumTextureUnits(GPT_FRAGMENT_PROGRAM) +
  1623. rsc->getNumTextureUnits(GPT_VERTEX_PROGRAM));
  1624. }
  1625. else
  1626. {
  1627. rsc->setNumCombinedTextureUnits(rsc->getNumTextureUnits(GPT_FRAGMENT_PROGRAM));
  1628. }
  1629. // Check alpha to coverage support
  1630. // this varies per vendor! But at least SM3 is required
  1631. if (rsc->isShaderProfileSupported("ps_3_0"))
  1632. {
  1633. // NVIDIA needs a separate check
  1634. if (rsc->getVendor() == GPU_NVIDIA)
  1635. {
  1636. if (mpD3D->CheckDeviceFormat(
  1637. D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
  1638. (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK)
  1639. {
  1640. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1641. }
  1642. }
  1643. else if (rsc->getVendor() == GPU_ATI)
  1644. {
  1645. // There is no check on ATI, we have to assume SM3 == support
  1646. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1647. }
  1648. // no other cards have Dx9 hacks for alpha to coverage, as far as I know
  1649. }
  1650. if (mCurrentCapabilities == NULL)
  1651. {
  1652. mCurrentCapabilities = rsc;
  1653. mCurrentCapabilities->addShaderProfile("hlsl");
  1654. mCurrentCapabilities->addShaderProfile("cg");
  1655. initialiseFromRenderSystemCapabilities(mCurrentCapabilities);
  1656. }
  1657. return rsc;
  1658. }
  1659. //---------------------------------------------------------------------
  1660. void D3D9RenderSystem::convertVertexShaderCaps(RenderSystemCapabilities* rsc) const
  1661. {
  1662. UINT16 major = 0xFF;
  1663. UINT16 minor = 0xFF;
  1664. D3DCAPS9 minVSCaps;
  1665. // Find the device with the lowest vertex shader caps.
  1666. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1667. {
  1668. D3D9Driver* pCurDriver = mDriverList->item(i);
  1669. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  1670. UINT16 currMajor = static_cast<UINT16>((rkCurCaps.VertexShaderVersion & 0x0000FF00) >> 8);
  1671. UINT16 currMinor = static_cast<UINT16>(rkCurCaps.VertexShaderVersion & 0x000000FF);
  1672. if (currMajor < major)
  1673. {
  1674. major = currMajor;
  1675. minor = currMinor;
  1676. minVSCaps = rkCurCaps;
  1677. }
  1678. else if (currMajor == major && currMinor < minor)
  1679. {
  1680. minor = currMinor;
  1681. minVSCaps = rkCurCaps;
  1682. }
  1683. }
  1684. // In case we didn't found any vertex shader support
  1685. // try the IDirect3DDevice9 caps instead of the IDirect3D9
  1686. // software vertex processing is reported there
  1687. if (major == 0 && minor == 0)
  1688. {
  1689. IDirect3DDevice9* lpD3DDevice9 = getActiveD3D9Device();
  1690. D3DCAPS9 d3dDeviceCaps9;
  1691. lpD3DDevice9->GetDeviceCaps(&d3dDeviceCaps9);
  1692. major = static_cast<UINT16>((d3dDeviceCaps9.VertexShaderVersion & 0x0000FF00) >> 8);
  1693. minor = static_cast<UINT16>(d3dDeviceCaps9.VertexShaderVersion & 0x000000FF);
  1694. }
  1695. bool vs2x = false;
  1696. bool vs2a = false;
  1697. // Special case detection for vs_2_x/a support
  1698. if (major >= 2)
  1699. {
  1700. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  1701. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  1702. (minVSCaps.VS20Caps.NumTemps >= 12))
  1703. {
  1704. vs2x = true;
  1705. }
  1706. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  1707. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  1708. (minVSCaps.VS20Caps.NumTemps >= 13))
  1709. {
  1710. vs2a = true;
  1711. }
  1712. }
  1713. // Populate max param count
  1714. switch (major)
  1715. {
  1716. case 1:
  1717. // No boolean params allowed
  1718. rsc->setVertexProgramConstantBoolCount(0);
  1719. // No integer params allowed
  1720. rsc->setVertexProgramConstantIntCount(0);
  1721. // float params, always 4D
  1722. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1723. break;
  1724. case 2:
  1725. // 16 boolean params allowed
  1726. rsc->setVertexProgramConstantBoolCount(16);
  1727. // 16 integer params allowed, 4D
  1728. rsc->setVertexProgramConstantIntCount(16);
  1729. // float params, always 4D
  1730. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1731. break;
  1732. case 3:
  1733. // 16 boolean params allowed
  1734. rsc->setVertexProgramConstantBoolCount(16);
  1735. // 16 integer params allowed, 4D
  1736. rsc->setVertexProgramConstantIntCount(16);
  1737. // float params, always 4D
  1738. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1739. break;
  1740. }
  1741. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1742. switch(major)
  1743. {
  1744. case 3:
  1745. rsc->addShaderProfile("vs_3_0");
  1746. rsc->addGpuProgramProfile(GPP_VS_3_0, "vs_3_0");
  1747. case 2:
  1748. if (vs2x)
  1749. {
  1750. rsc->addShaderProfile("vs_2_x");
  1751. rsc->addGpuProgramProfile(GPP_VS_2_x, "vs_2_x");
  1752. }
  1753. if (vs2a)
  1754. {
  1755. rsc->addShaderProfile("vs_2_a");
  1756. rsc->addGpuProgramProfile(GPP_VS_2_a, "vs_2_a");
  1757. }
  1758. rsc->addShaderProfile("vs_2_0");
  1759. rsc->addGpuProgramProfile(GPP_VS_2_0, "vs_2_0");
  1760. case 1:
  1761. rsc->addShaderProfile("vs_1_1");
  1762. rsc->addGpuProgramProfile(GPP_VS_1_1, "vs_1_1");
  1763. rsc->setCapability(RSC_VERTEX_PROGRAM);
  1764. }
  1765. }
  1766. //---------------------------------------------------------------------
  1767. void D3D9RenderSystem::convertPixelShaderCaps(RenderSystemCapabilities* rsc) const
  1768. {
  1769. UINT16 major = 0xFF;
  1770. UINT16 minor = 0xFF;
  1771. D3DCAPS9 minPSCaps;
  1772. // Find the device with the lowest pixel shader caps.
  1773. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1774. {
  1775. D3D9Driver* pCurDriver = mDriverList->item(i);
  1776. const D3DCAPS9& currCaps = pCurDriver->getD3D9DeviceCaps();
  1777. UINT16 currMajor = static_cast<UINT16>((currCaps.PixelShaderVersion & 0x0000FF00) >> 8);
  1778. UINT16 currMinor = static_cast<UINT16>(currCaps.PixelShaderVersion & 0x000000FF);
  1779. if (currMajor < major)
  1780. {
  1781. major = currMajor;
  1782. minor = currMinor;
  1783. minPSCaps = currCaps;
  1784. }
  1785. else if (currMajor == major && currMinor < minor)
  1786. {
  1787. minor = currMinor;
  1788. minPSCaps = currCaps;
  1789. }
  1790. }
  1791. bool ps2a = false;
  1792. bool ps2b = false;
  1793. bool ps2x = false;
  1794. // Special case detection for ps_2_x/a/b support
  1795. if (major >= 2)
  1796. {
  1797. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1798. (minPSCaps.PS20Caps.NumTemps >= 32))
  1799. {
  1800. ps2b = true;
  1801. }
  1802. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1803. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NODEPENDENTREADLIMIT) &&
  1804. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_ARBITRARYSWIZZLE) &&
  1805. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) &&
  1806. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_PREDICATION) &&
  1807. (minPSCaps.PS20Caps.NumTemps >= 22))
  1808. {
  1809. ps2a = true;
  1810. }
  1811. // Does this enough?
  1812. if (ps2a || ps2b)
  1813. {
  1814. ps2x = true;
  1815. }
  1816. }
  1817. switch (major)
  1818. {
  1819. case 1:
  1820. // no boolean params allowed
  1821. rsc->setFragmentProgramConstantBoolCount(0);
  1822. // no integer params allowed
  1823. rsc->setFragmentProgramConstantIntCount(0);
  1824. // float params, always 4D
  1825. // NB in ps_1_x these are actually stored as fixed point values,
  1826. // but they are entered as floats
  1827. rsc->setFragmentProgramConstantFloatCount(8);
  1828. break;
  1829. case 2:
  1830. // 16 boolean params allowed
  1831. rsc->setFragmentProgramConstantBoolCount(16);
  1832. // 16 integer params allowed, 4D
  1833. rsc->setFragmentProgramConstantIntCount(16);
  1834. // float params, always 4D
  1835. rsc->setFragmentProgramConstantFloatCount(32);
  1836. break;
  1837. case 3:
  1838. // 16 boolean params allowed
  1839. rsc->setFragmentProgramConstantBoolCount(16);
  1840. // 16 integer params allowed, 4D
  1841. rsc->setFragmentProgramConstantIntCount(16);
  1842. // float params, always 4D
  1843. rsc->setFragmentProgramConstantFloatCount(224);
  1844. break;
  1845. }
  1846. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1847. switch(major)
  1848. {
  1849. case 3:
  1850. if (minor > 0)
  1851. {
  1852. rsc->addShaderProfile("ps_3_x");
  1853. rsc->addGpuProgramProfile(GPP_PS_3_x, "ps_3_x");
  1854. }
  1855. rsc->addShaderProfile("ps_3_0");
  1856. rsc->addGpuProgramProfile(GPP_PS_3_0, "ps_3_0");
  1857. case 2:
  1858. if (ps2x)
  1859. {
  1860. rsc->addShaderProfile("ps_2_x");
  1861. rsc->addGpuProgramProfile(GPP_PS_2_x, "ps_2_x");
  1862. }
  1863. if (ps2a)
  1864. {
  1865. rsc->addShaderProfile("ps_2_a");
  1866. rsc->addGpuProgramProfile(GPP_PS_2_a, "ps_2_a");
  1867. }
  1868. if (ps2b)
  1869. {
  1870. rsc->addShaderProfile("ps_2_b");
  1871. rsc->addGpuProgramProfile(GPP_PS_2_b, "ps_2_b");
  1872. }
  1873. rsc->addShaderProfile("ps_2_0");
  1874. rsc->addGpuProgramProfile(GPP_PS_2_0, "ps_2_0");
  1875. case 1:
  1876. if (major > 1 || minor >= 4)
  1877. {
  1878. rsc->addShaderProfile("ps_1_4");
  1879. rsc->addGpuProgramProfile(GPP_PS_1_4, "ps_1_4");
  1880. }
  1881. if (major > 1 || minor >= 3)
  1882. {
  1883. rsc->addShaderProfile("ps_1_3");
  1884. rsc->addGpuProgramProfile(GPP_PS_1_3, "ps_1_3");
  1885. }
  1886. if (major > 1 || minor >= 2)
  1887. {
  1888. rsc->addShaderProfile("ps_1_2");
  1889. rsc->addGpuProgramProfile(GPP_PS_1_2, "ps_1_2");
  1890. }
  1891. rsc->addShaderProfile("ps_1_1");
  1892. rsc->addGpuProgramProfile(GPP_PS_1_1, "ps_1_1");
  1893. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  1894. }
  1895. }
  1896. //-----------------------------------------------------------------------
  1897. bool D3D9RenderSystem::checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const
  1898. {
  1899. bool anySupported = false;
  1900. IDirect3DSurface9* bbSurf;
  1901. renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  1902. D3DSURFACE_DESC bbSurfDesc;
  1903. bbSurf->GetDesc(&bbSurfDesc);
  1904. for (UINT32 ipf = static_cast<UINT32>(PF_L8); ipf < static_cast<UINT32>(PF_COUNT); ++ipf)
  1905. {
  1906. PixelFormat pf = (PixelFormat)ipf;
  1907. D3DFORMAT fmt =
  1908. D3D9Mappings::_getPF(D3D9Mappings::_getClosestSupportedPF(pf));
  1909. if (SUCCEEDED(mpD3D->CheckDeviceFormat(
  1910. mActiveD3DDriver->getAdapterNumber(), D3DDEVTYPE_HAL, bbSurfDesc.Format,
  1911. D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, fmt)))
  1912. {
  1913. // cool, at least one supported
  1914. anySupported = true;
  1915. }
  1916. }
  1917. return anySupported;
  1918. }
  1919. //-----------------------------------------------------------------------
  1920. void D3D9RenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps)
  1921. {
  1922. if (caps->getRenderSystemName() != getName())
  1923. {
  1924. CM_EXCEPT(InvalidParametersException,
  1925. "Trying to initialize D3D9RenderSystem from RenderSystemCapabilities that do not support Direct3D9");
  1926. }
  1927. if (caps->isShaderProfileSupported("hlsl"))
  1928. HighLevelGpuProgramManager::instance().addFactory(mHLSLProgramFactory);
  1929. if (caps->isShaderProfileSupported("cg"))
  1930. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  1931. mNumTexStages = caps->getNumCombinedTextureUnits();
  1932. mTexStageDesc = CM_NEW_ARRAY(sD3DTextureStageDesc, mNumTexStages, GenAlloc);
  1933. // set stages desc. to defaults
  1934. for (UINT32 n = 0; n < mNumTexStages; n++)
  1935. {
  1936. mTexStageDesc[n].coordIndex = 0;
  1937. mTexStageDesc[n].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  1938. mTexStageDesc[n].pTex = 0;
  1939. mTexStageDesc[n].pVertexTex = 0;
  1940. }
  1941. }
  1942. //-----------------------------------------------------------------------
  1943. bool D3D9RenderSystem::checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage)
  1944. {
  1945. // Gets D3D format
  1946. D3DFORMAT d3dPF = D3D9Mappings::_getPF(format);
  1947. if (d3dPF == D3DFMT_UNKNOWN)
  1948. return false;
  1949. for (UINT32 i = 0; i < mDeviceManager->getDeviceCount(); ++i)
  1950. {
  1951. D3D9Device* currDevice = mDeviceManager->getDevice(i);
  1952. D3D9RenderWindow* currDevicePrimaryWindow = currDevice->getPrimaryWindow();
  1953. IDirect3DSurface9* pSurface = currDevicePrimaryWindow->getRenderSurface();
  1954. D3DSURFACE_DESC srfDesc;
  1955. // Get surface desc
  1956. if (FAILED(pSurface->GetDesc(&srfDesc)))
  1957. return false;
  1958. // Calculate usage
  1959. DWORD d3dusage = D3DUSAGE_QUERY_FILTER;
  1960. if (usage & TU_RENDERTARGET)
  1961. d3dusage |= D3DUSAGE_RENDERTARGET;
  1962. if (usage & TU_DEPTHSTENCIL)
  1963. d3dusage |= D3DUSAGE_DEPTHSTENCIL;
  1964. if (usage & TU_DYNAMIC)
  1965. d3dusage |= D3DUSAGE_DYNAMIC;
  1966. // Detect resource type
  1967. D3DRESOURCETYPE rtype;
  1968. switch(ttype)
  1969. {
  1970. case TEX_TYPE_1D:
  1971. case TEX_TYPE_2D:
  1972. rtype = D3DRTYPE_TEXTURE;
  1973. break;
  1974. case TEX_TYPE_3D:
  1975. rtype = D3DRTYPE_VOLUMETEXTURE;
  1976. break;
  1977. case TEX_TYPE_CUBE_MAP:
  1978. rtype = D3DRTYPE_CUBETEXTURE;
  1979. break;
  1980. default:
  1981. return false;
  1982. }
  1983. HRESULT hr = mpD3D->CheckDeviceFormat(
  1984. currDevice->getAdapterNumber(),
  1985. currDevice->getDeviceType(),
  1986. srfDesc.Format,
  1987. d3dusage,
  1988. rtype,
  1989. d3dPF);
  1990. if (FAILED(hr))
  1991. return false;
  1992. }
  1993. return true;
  1994. }
  1995. //---------------------------------------------------------------------
  1996. String D3D9RenderSystem::getErrorDescription( long errorNumber ) const
  1997. {
  1998. const String errMsg = DXGetErrorDescription( errorNumber );
  1999. return errMsg;
  2000. }
  2001. // ------------------------------------------------------------------
  2002. void D3D9RenderSystem::setClipPlane (UINT16 index, float A, float B, float C, float D)
  2003. {
  2004. float plane[4] = { A, B, C, D };
  2005. getActiveD3D9Device()->SetClipPlane (index, plane);
  2006. }
  2007. // ------------------------------------------------------------------
  2008. void D3D9RenderSystem::enableClipPlane (UINT16 index, bool enable)
  2009. {
  2010. DWORD prev;
  2011. getActiveD3D9Device()->GetRenderState(D3DRS_CLIPPLANEENABLE, &prev);
  2012. __SetRenderState(D3DRS_CLIPPLANEENABLE, enable?
  2013. (prev | (1 << index)) : (prev & ~(1 << index)));
  2014. }
  2015. //---------------------------------------------------------------------
  2016. void D3D9RenderSystem::notifyOnDeviceLost(D3D9Device* device)
  2017. {
  2018. }
  2019. //---------------------------------------------------------------------
  2020. void D3D9RenderSystem::notifyOnDeviceReset(D3D9Device* device)
  2021. {
  2022. // Reset state attributes.
  2023. mVertexProgramBound = false;
  2024. mFragmentProgramBound = false;
  2025. }
  2026. //---------------------------------------------------------------------
  2027. void D3D9RenderSystem::determineFSAASettings(IDirect3DDevice9* d3d9Device,
  2028. UINT32 fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat,
  2029. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality)
  2030. {
  2031. bool ok = false;
  2032. bool qualityHint = fsaaHint.find("Quality") != String::npos;
  2033. UINT32 origFSAA = fsaa;
  2034. D3D9DriverList* driverList = getDirect3DDrivers();
  2035. D3D9Driver* deviceDriver = mActiveD3DDriver;
  2036. D3D9Device* device = mDeviceManager->getDeviceFromD3D9Device(d3d9Device);
  2037. for (UINT32 i = 0; i < driverList->count(); ++i)
  2038. {
  2039. D3D9Driver* currDriver = driverList->item(i);
  2040. if (currDriver->getAdapterNumber() == device->getAdapterNumber())
  2041. {
  2042. deviceDriver = currDriver;
  2043. break;
  2044. }
  2045. }
  2046. bool tryCSAA = false;
  2047. // NVIDIA, prefer CSAA if available for 8+
  2048. // it would be tempting to use getCapabilities()->getVendor() == GPU_NVIDIA but
  2049. // if this is the first window, caps will not be initialised yet
  2050. if (deviceDriver->getAdapterIdentifier().VendorId == 0x10DE &&
  2051. fsaa >= 8)
  2052. {
  2053. tryCSAA = true;
  2054. }
  2055. while (!ok)
  2056. {
  2057. // Deal with special cases
  2058. if (tryCSAA)
  2059. {
  2060. // see http://developer.nvidia.com/object/coverage-sampled-aa.html
  2061. switch(fsaa)
  2062. {
  2063. case 8:
  2064. if (qualityHint)
  2065. {
  2066. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  2067. *outMultisampleQuality = 0;
  2068. }
  2069. else
  2070. {
  2071. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  2072. *outMultisampleQuality = 2;
  2073. }
  2074. break;
  2075. case 16:
  2076. if (qualityHint)
  2077. {
  2078. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  2079. *outMultisampleQuality = 2;
  2080. }
  2081. else
  2082. {
  2083. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  2084. *outMultisampleQuality = 4;
  2085. }
  2086. break;
  2087. }
  2088. }
  2089. else // !CSAA
  2090. {
  2091. *outMultisampleType = (D3DMULTISAMPLE_TYPE)fsaa;
  2092. *outMultisampleQuality = 0;
  2093. }
  2094. HRESULT hr;
  2095. DWORD outQuality;
  2096. hr = mpD3D->CheckDeviceMultiSampleType(
  2097. deviceDriver->getAdapterNumber(),
  2098. D3DDEVTYPE_HAL,
  2099. d3dPixelFormat,
  2100. fullScreen,
  2101. *outMultisampleType,
  2102. &outQuality);
  2103. if (SUCCEEDED(hr) &&
  2104. (!tryCSAA || outQuality > *outMultisampleQuality))
  2105. {
  2106. ok = true;
  2107. }
  2108. else
  2109. {
  2110. // downgrade
  2111. if (tryCSAA && fsaa == 8)
  2112. {
  2113. // for CSAA, we'll try downgrading with quality mode at all samples.
  2114. // then try without quality, then drop CSAA
  2115. if (qualityHint)
  2116. {
  2117. // drop quality first
  2118. qualityHint = false;
  2119. }
  2120. else
  2121. {
  2122. // drop CSAA entirely
  2123. tryCSAA = false;
  2124. }
  2125. // return to original requested samples
  2126. fsaa = origFSAA;
  2127. }
  2128. else
  2129. {
  2130. // drop samples
  2131. --fsaa;
  2132. if (fsaa == 1)
  2133. {
  2134. // ran out of options, no FSAA
  2135. fsaa = 0;
  2136. ok = true;
  2137. }
  2138. }
  2139. }
  2140. } // while !ok
  2141. }
  2142. //---------------------------------------------------------------------
  2143. RenderSystemCapabilities* D3D9RenderSystem::createRenderSystemCapabilities() const
  2144. {
  2145. return mCurrentCapabilities;
  2146. }
  2147. //---------------------------------------------------------------------
  2148. void D3D9RenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  2149. {
  2150. size_t i;
  2151. size_t numClipPlanes;
  2152. D3DXPLANE dx9ClipPlane;
  2153. DWORD mask = 0;
  2154. HRESULT hr;
  2155. numClipPlanes = clipPlanes.size();
  2156. for (i = 0; i < numClipPlanes; ++i)
  2157. {
  2158. const Plane& plane = clipPlanes[i];
  2159. dx9ClipPlane.a = plane.normal.x;
  2160. dx9ClipPlane.b = plane.normal.y;
  2161. dx9ClipPlane.c = plane.normal.z;
  2162. dx9ClipPlane.d = plane.d;
  2163. // TODO Low priority - Transform planes to clip space?
  2164. hr = getActiveD3D9Device()->SetClipPlane(static_cast<DWORD>(i), dx9ClipPlane);
  2165. if (FAILED(hr))
  2166. {
  2167. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  2168. }
  2169. mask |= (1 << i);
  2170. }
  2171. hr = __SetRenderState(D3DRS_CLIPPLANEENABLE, mask);
  2172. if (FAILED(hr))
  2173. {
  2174. CM_EXCEPT(RenderingAPIException, "Unable to set render state for clip planes");
  2175. }
  2176. }
  2177. //---------------------------------------------------------------------
  2178. HRESULT D3D9RenderSystem::__SetRenderState(D3DRENDERSTATETYPE state, DWORD value)
  2179. {
  2180. HRESULT hr;
  2181. DWORD oldVal;
  2182. if ( FAILED( hr = getActiveD3D9Device()->GetRenderState(state, &oldVal) ) )
  2183. return hr;
  2184. if ( oldVal == value )
  2185. return D3D_OK;
  2186. else
  2187. return getActiveD3D9Device()->SetRenderState(state, value);
  2188. }
  2189. //---------------------------------------------------------------------
  2190. HRESULT D3D9RenderSystem::__SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value)
  2191. {
  2192. HRESULT hr;
  2193. DWORD oldVal;
  2194. if ( FAILED( hr = getActiveD3D9Device()->GetSamplerState(sampler, type, &oldVal) ) )
  2195. return hr;
  2196. if ( oldVal == value )
  2197. return D3D_OK;
  2198. else
  2199. return getActiveD3D9Device()->SetSamplerState(sampler, type, value);
  2200. }
  2201. //---------------------------------------------------------------------
  2202. HRESULT D3D9RenderSystem::__SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value)
  2203. {
  2204. HRESULT hr;
  2205. DWORD oldVal;
  2206. // can only set fixed-function texture stage state
  2207. if (stage < 8)
  2208. {
  2209. if ( FAILED( hr = getActiveD3D9Device()->GetTextureStageState(stage, type, &oldVal) ) )
  2210. return hr;
  2211. if ( oldVal == value )
  2212. return D3D_OK;
  2213. else
  2214. return getActiveD3D9Device()->SetTextureStageState(stage, type, value);
  2215. }
  2216. else
  2217. {
  2218. return D3D_OK;
  2219. }
  2220. }
  2221. //---------------------------------------------------------------------
  2222. DWORD D3D9RenderSystem::_getCurrentAnisotropy(UINT32 unit)
  2223. {
  2224. DWORD oldVal;
  2225. getActiveD3D9Device()->GetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, &oldVal);
  2226. return oldVal;
  2227. }
  2228. }
  2229. #undef THROW_IF_NOT_RENDER_THREAD
  2230. #undef THROW_IF_NOT_RENDER_THREAD_STATIC