CmD3D9RenderSystem.cpp 84 KB

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