BsD3D9RenderSystem.cpp 68 KB

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