CmD3D9RenderSystem.cpp 84 KB

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