CmD3D9RenderSystem.cpp 83 KB

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