CmD3D9RenderSystem.cpp 84 KB

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