CmD3D9RenderSystem.cpp 84 KB

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