BsD3D9RenderSystem.cpp 68 KB

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