BsD3D9RenderSystem.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  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. D3D9VertexBufferCore* d3d9buf = static_cast<D3D9VertexBufferCore*>(buffers[i]->getCore());
  959. const VertexBufferProperties& vbProps = d3d9buf->getProperties();
  960. hr = getActiveD3D9Device()->SetStreamSource(
  961. static_cast<UINT>(index + i),
  962. d3d9buf->getD3D9VertexBuffer(),
  963. 0,
  964. static_cast<UINT>(vbProps.getVertexSize()) // stride
  965. );
  966. }
  967. else
  968. {
  969. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(index + i), nullptr, 0, 0);
  970. }
  971. if (FAILED(hr))
  972. BS_EXCEPT(RenderingAPIException, "Unable to set D3D9 stream source for buffer binding");
  973. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  974. }
  975. }
  976. void D3D9RenderSystem::setIndexBuffer(const IndexBufferPtr& buffer)
  977. {
  978. THROW_IF_NOT_CORE_THREAD;
  979. D3D9IndexBufferCore* d3dIdxBuf = static_cast<D3D9IndexBufferCore*>(buffer->getCore());
  980. HRESULT hr = getActiveD3D9Device()->SetIndices( d3dIdxBuf->getD3DIndexBuffer() );
  981. if (FAILED(hr))
  982. BS_EXCEPT(RenderingAPIException, "Failed to set index buffer");
  983. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  984. }
  985. void D3D9RenderSystem::setDrawOperation(DrawOperationType op)
  986. {
  987. THROW_IF_NOT_CORE_THREAD;
  988. mCurrentDrawOperation = op;
  989. }
  990. void D3D9RenderSystem::draw(UINT32 vertexOffset, UINT32 vertexCount)
  991. {
  992. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  993. HRESULT hr = getActiveD3D9Device()->DrawPrimitive(getD3D9PrimitiveType(), static_cast<UINT>(vertexOffset), static_cast<UINT>(primCount));
  994. if(FAILED(hr))
  995. {
  996. String msg = DXGetErrorDescription(hr);
  997. BS_EXCEPT(RenderingAPIException, "Failed to DrawPrimitive : " + msg);
  998. }
  999. BS_INC_RENDER_STAT(NumDrawCalls);
  1000. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1001. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1002. }
  1003. void D3D9RenderSystem::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount)
  1004. {
  1005. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, indexCount);
  1006. // do indexed draw operation
  1007. HRESULT hr = getActiveD3D9Device()->DrawIndexedPrimitive(
  1008. getD3D9PrimitiveType(),
  1009. static_cast<UINT>(vertexOffset),
  1010. 0,
  1011. static_cast<UINT>(vertexCount),
  1012. static_cast<UINT>(startIndex),
  1013. static_cast<UINT>(primCount)
  1014. );
  1015. if(FAILED(hr))
  1016. {
  1017. String msg = DXGetErrorDescription(hr);
  1018. BS_EXCEPT(RenderingAPIException, "Failed to DrawIndexedPrimitive : " + msg);
  1019. }
  1020. BS_INC_RENDER_STAT(NumDrawCalls);
  1021. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1022. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1023. }
  1024. void D3D9RenderSystem::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  1025. {
  1026. THROW_IF_NOT_CORE_THREAD;
  1027. mScissorRect.left = static_cast<LONG>(left);
  1028. mScissorRect.top = static_cast<LONG>(top);
  1029. mScissorRect.bottom = static_cast<LONG>(bottom);
  1030. mScissorRect.right = static_cast<LONG>(right);
  1031. }
  1032. void D3D9RenderSystem::setScissorTestEnable(bool enable)
  1033. {
  1034. THROW_IF_NOT_CORE_THREAD;
  1035. HRESULT hr;
  1036. if (enable)
  1037. {
  1038. if (FAILED(hr = setRenderState(D3DRS_SCISSORTESTENABLE, TRUE)))
  1039. {
  1040. BS_EXCEPT(RenderingAPIException, "Unable to enable scissor rendering state; " + getErrorDescription(hr));
  1041. }
  1042. if (FAILED(hr = getActiveD3D9Device()->SetScissorRect(&mScissorRect)))
  1043. {
  1044. BS_EXCEPT(RenderingAPIException, "Unable to set scissor rectangle; " + getErrorDescription(hr));
  1045. }
  1046. }
  1047. else
  1048. {
  1049. if (FAILED(hr = setRenderState(D3DRS_SCISSORTESTENABLE, FALSE)))
  1050. {
  1051. BS_EXCEPT(RenderingAPIException, "Unable to disable scissor rendering state; " + getErrorDescription(hr));
  1052. }
  1053. }
  1054. }
  1055. void D3D9RenderSystem::setMultisampleAntialiasEnable(bool enable)
  1056. {
  1057. HRESULT hr;
  1058. if(enable)
  1059. {
  1060. if (FAILED(hr = setRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE)))
  1061. {
  1062. BS_EXCEPT(RenderingAPIException, "Unable to enable multisample antialiasing. Error description: " + getErrorDescription(hr));
  1063. }
  1064. }
  1065. else
  1066. {
  1067. if (FAILED(hr = setRenderState(D3DRS_MULTISAMPLEANTIALIAS, FALSE)))
  1068. {
  1069. BS_EXCEPT(RenderingAPIException, "Unable to disable multisample antialiasing. Error description: " + getErrorDescription(hr));
  1070. }
  1071. }
  1072. }
  1073. void D3D9RenderSystem::setAntialiasedLineEnable(bool enable)
  1074. {
  1075. HRESULT hr;
  1076. if(enable)
  1077. {
  1078. if (FAILED(hr = setRenderState(D3DRS_ANTIALIASEDLINEENABLE, TRUE)))
  1079. {
  1080. BS_EXCEPT(RenderingAPIException, "Unable to enable line antialiasing. Error description: " + getErrorDescription(hr));
  1081. }
  1082. }
  1083. else
  1084. {
  1085. if (FAILED(hr = setRenderState(D3DRS_ANTIALIASEDLINEENABLE, FALSE)))
  1086. {
  1087. BS_EXCEPT(RenderingAPIException, "Unable to disable line antialiasing. Error description: " + getErrorDescription(hr));
  1088. }
  1089. }
  1090. }
  1091. void D3D9RenderSystem::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  1092. {
  1093. if(mActiveRenderTarget == nullptr)
  1094. return;
  1095. const RenderTargetProperties& rtProps = mActiveRenderTarget->getCore()->getProperties();
  1096. Rect2I clearRect(0, 0, rtProps.getWidth(), rtProps.getHeight());
  1097. clearArea(buffers, color, depth, stencil, clearRect);
  1098. }
  1099. void D3D9RenderSystem::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  1100. {
  1101. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1102. clearArea(buffers, color, depth, stencil, clearRect);
  1103. }
  1104. void D3D9RenderSystem::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect)
  1105. {
  1106. THROW_IF_NOT_CORE_THREAD;
  1107. if(mActiveRenderTarget == nullptr)
  1108. return;
  1109. DWORD flags = 0;
  1110. if (buffers & FBT_COLOR)
  1111. {
  1112. flags |= D3DCLEAR_TARGET;
  1113. }
  1114. if (buffers & FBT_DEPTH)
  1115. {
  1116. flags |= D3DCLEAR_ZBUFFER;
  1117. }
  1118. // Only try to clear the stencil buffer if supported
  1119. if (buffers & FBT_STENCIL)
  1120. {
  1121. flags |= D3DCLEAR_STENCIL;
  1122. }
  1123. const RenderTargetProperties& rtProps = mActiveRenderTarget->getCore()->getProperties();
  1124. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  1125. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.getWidth() && clearRect.height == rtProps.getHeight());
  1126. if(!clearEntireTarget)
  1127. {
  1128. D3DRECT clearD3DRect;
  1129. clearD3DRect.x1 = (LONG)Math::clamp(clearRect.x, 0, (INT32)rtProps.getWidth() - 1);
  1130. clearD3DRect.x2 = (LONG)Math::clamp((INT32)clearD3DRect.x1 + clearRect.width, 0, (INT32)rtProps.getWidth() - 1);
  1131. clearD3DRect.y1 = (LONG)Math::clamp(clearRect.y, 0, (INT32)rtProps.getHeight() - 1);
  1132. clearD3DRect.y2 = (LONG)Math::clamp((INT32)clearD3DRect.y1 + clearRect.height, 0, (INT32)rtProps.getHeight() - 1);
  1133. HRESULT hr;
  1134. if(FAILED(hr = getActiveD3D9Device()->Clear(1, &clearD3DRect, flags, color.getAsBGRA(), depth, stencil)))
  1135. {
  1136. String msg = DXGetErrorDescription(hr);
  1137. BS_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  1138. }
  1139. }
  1140. else
  1141. {
  1142. HRESULT hr;
  1143. if(FAILED(hr = getActiveD3D9Device()->Clear(0, nullptr, flags, color.getAsBGRA(), depth, stencil)))
  1144. {
  1145. String msg = DXGetErrorDescription(hr);
  1146. BS_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  1147. }
  1148. }
  1149. BS_INC_RENDER_STAT(NumClears);
  1150. }
  1151. IDirect3D9* D3D9RenderSystem::getDirect3D9()
  1152. {
  1153. THROW_IF_NOT_CORE_THREAD;
  1154. return msD3D9RenderSystem->mpD3D;
  1155. }
  1156. UINT D3D9RenderSystem::getResourceCreationDeviceCount()
  1157. {
  1158. THROW_IF_NOT_CORE_THREAD;
  1159. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  1160. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  1161. {
  1162. return 1;
  1163. }
  1164. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  1165. {
  1166. return msD3D9RenderSystem->mDeviceManager->getDeviceCount();
  1167. }
  1168. BS_EXCEPT(InvalidParametersException, "Invalid resource creation policy.");
  1169. return 0;
  1170. }
  1171. IDirect3DDevice9* D3D9RenderSystem::getResourceCreationDevice(UINT index)
  1172. {
  1173. THROW_IF_NOT_CORE_THREAD;
  1174. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  1175. IDirect3DDevice9* d3d9Device = NULL;
  1176. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  1177. {
  1178. d3d9Device = msD3D9RenderSystem->getActiveD3D9Device();
  1179. }
  1180. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  1181. {
  1182. d3d9Device = msD3D9RenderSystem->mDeviceManager->getDevice(index)->getD3D9Device();
  1183. }
  1184. else
  1185. {
  1186. BS_EXCEPT(InvalidParametersException, "Invalid resource creation policy.");
  1187. }
  1188. return d3d9Device;
  1189. }
  1190. IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9Device()
  1191. {
  1192. THROW_IF_NOT_CORE_THREAD;
  1193. D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice();
  1194. IDirect3DDevice9* d3d9Device;
  1195. d3d9Device = activeDevice->getD3D9Device();
  1196. if (d3d9Device == nullptr)
  1197. BS_EXCEPT(InvalidParametersException, "Current d3d9 device is null.");
  1198. return d3d9Device;
  1199. }
  1200. D3D9ResourceManager* D3D9RenderSystem::getResourceManager()
  1201. {
  1202. // No need to check if we're on core thread as this is synced up internally
  1203. return msD3D9RenderSystem->mResourceManager;
  1204. }
  1205. D3D9DeviceManager* D3D9RenderSystem::getDeviceManager()
  1206. {
  1207. THROW_IF_NOT_CORE_THREAD;
  1208. return msD3D9RenderSystem->mDeviceManager;
  1209. }
  1210. /************************************************************************/
  1211. /* UTILITY METHODS */
  1212. /************************************************************************/
  1213. float D3D9RenderSystem::getHorizontalTexelOffset()
  1214. {
  1215. // D3D considers the origin to be in the center of a pixel
  1216. return -0.5f;
  1217. }
  1218. float D3D9RenderSystem::getVerticalTexelOffset()
  1219. {
  1220. // D3D considers the origin to be in the center of a pixel
  1221. return -0.5f;
  1222. }
  1223. float D3D9RenderSystem::getMinimumDepthInputValue()
  1224. {
  1225. // Range [0.0f, 1.0f]
  1226. return 0.0f;
  1227. }
  1228. float D3D9RenderSystem::getMaximumDepthInputValue()
  1229. {
  1230. // Range [0.0f, 1.0f]
  1231. return 1.0f;
  1232. }
  1233. VertexElementType D3D9RenderSystem::getColorVertexElementType() const
  1234. {
  1235. return VET_COLOR_ARGB;
  1236. }
  1237. void D3D9RenderSystem::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  1238. {
  1239. dest = matrix;
  1240. // Convert depth range from [-1,+1] to [0,1]
  1241. dest[2][0] = (dest[2][0] + dest[3][0]) / 2;
  1242. dest[2][1] = (dest[2][1] + dest[3][1]) / 2;
  1243. dest[2][2] = (dest[2][2] + dest[3][2]) / 2;
  1244. dest[2][3] = (dest[2][3] + dest[3][3]) / 2;
  1245. }
  1246. /************************************************************************/
  1247. /* PRIVATE */
  1248. /************************************************************************/
  1249. D3D9DriverList* D3D9RenderSystem::getDirect3DDrivers() const
  1250. {
  1251. if( !mDriverList )
  1252. mDriverList = bs_new<D3D9DriverList>();
  1253. return mDriverList;
  1254. }
  1255. D3DPRIMITIVETYPE D3D9RenderSystem::getD3D9PrimitiveType() const
  1256. {
  1257. switch(mCurrentDrawOperation)
  1258. {
  1259. case DOT_POINT_LIST:
  1260. return D3DPT_POINTLIST;
  1261. case DOT_LINE_LIST:
  1262. return D3DPT_LINELIST;
  1263. case DOT_LINE_STRIP:
  1264. return D3DPT_LINESTRIP;
  1265. case DOT_TRIANGLE_LIST:
  1266. return D3DPT_TRIANGLELIST;
  1267. case DOT_TRIANGLE_STRIP:
  1268. return D3DPT_TRIANGLESTRIP;
  1269. case DOT_TRIANGLE_FAN:
  1270. return D3DPT_TRIANGLEFAN;
  1271. }
  1272. return D3DPT_TRIANGLELIST;
  1273. }
  1274. RenderSystemCapabilities* D3D9RenderSystem::updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow)
  1275. {
  1276. RenderSystemCapabilities* rsc = mCurrentCapabilities;
  1277. if (rsc == nullptr)
  1278. rsc = bs_new<RenderSystemCapabilities>();
  1279. rsc->setDriverVersion(mDriverVersion);
  1280. rsc->setDeviceName(mActiveD3DDriver->getDriverDescription());
  1281. rsc->setRenderSystemName(getName());
  1282. // Init caps to maximum.
  1283. rsc->setCapability(RSC_ANISOTROPY);
  1284. rsc->setCapability(RSC_AUTOMIPMAP);
  1285. rsc->setCapability(RSC_CUBEMAPPING);
  1286. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1287. rsc->setCapability(RSC_STENCIL_WRAP);
  1288. rsc->setCapability(RSC_HWOCCLUSION);
  1289. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1290. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1291. rsc->setCapability(RSC_TEXTURE_3D);
  1292. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1293. rsc->setNumMultiRenderTargets(BS_MAX_MULTIPLE_RENDER_TARGETS);
  1294. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1295. rsc->setCapability(RSC_POINT_SPRITES);
  1296. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1297. rsc->setMaxPointSize(10.0);
  1298. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1299. rsc->setCapability(RSC_PERSTAGECONSTANT);
  1300. rsc->setStencilBufferBitDepth(8);
  1301. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1302. for (UINT32 i=0; i < mDeviceManager->getDeviceCount(); ++i)
  1303. {
  1304. D3D9Device* device = mDeviceManager->getDevice(i);
  1305. IDirect3DDevice9* d3d9Device = device->getD3D9Device();
  1306. IDirect3DSurface9* pSurf;
  1307. // Check for hardware stencil support
  1308. d3d9Device->GetDepthStencilSurface(&pSurf);
  1309. if (pSurf != nullptr)
  1310. {
  1311. D3DSURFACE_DESC surfDesc;
  1312. pSurf->GetDesc(&surfDesc);
  1313. pSurf->Release();
  1314. }
  1315. // Check for hardware occlusion support
  1316. HRESULT hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL);
  1317. if (FAILED(hr))
  1318. rsc->unsetCapability(RSC_HWOCCLUSION);
  1319. }
  1320. // Update RS caps using the minimum value found in adapter list.
  1321. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1322. {
  1323. D3D9Driver* pCurDriver = mDriverList->item(i);
  1324. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  1325. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, 16); // We don't support anything lower than SM3, and 16 is the sampler count determined by the specification
  1326. rsc->setMaxBoundVertexBuffers(static_cast<UINT32>(rkCurCaps.MaxStreams));
  1327. // Check for Anisotropy.
  1328. if (rkCurCaps.MaxAnisotropy <= 1)
  1329. rsc->unsetCapability(RSC_ANISOTROPY);
  1330. // Check automatic mipmap generation.
  1331. if ((rkCurCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) == 0)
  1332. rsc->unsetCapability(RSC_AUTOMIPMAP);
  1333. // Two-sided stencil
  1334. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) == 0)
  1335. rsc->unsetCapability(RSC_TWO_SIDED_STENCIL);
  1336. // stencil wrap
  1337. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_INCR) == 0 ||
  1338. (rkCurCaps.StencilCaps & D3DSTENCILCAPS_DECR) == 0)
  1339. rsc->unsetCapability(RSC_STENCIL_WRAP);
  1340. // User clip planes
  1341. if (rkCurCaps.MaxUserClipPlanes == 0)
  1342. rsc->unsetCapability(RSC_USER_CLIP_PLANES);
  1343. // UBYTE4 type?
  1344. if ((rkCurCaps.DeclTypes & D3DDTCAPS_UBYTE4) == 0)
  1345. rsc->unsetCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1346. // Check cube map support.
  1347. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP) == 0)
  1348. rsc->unsetCapability(RSC_CUBEMAPPING);
  1349. // 3D textures?
  1350. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_VOLUMEMAP) == 0)
  1351. rsc->unsetCapability(RSC_TEXTURE_3D);
  1352. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_POW2)
  1353. {
  1354. // Conditional support for non POW2
  1355. if (!(rkCurCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL))
  1356. rsc->unsetCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1357. }
  1358. // Number of render targets
  1359. if (rkCurCaps.NumSimultaneousRTs < rsc->getNumMultiRenderTargets())
  1360. {
  1361. rsc->setNumMultiRenderTargets(std::min((UINT16)rkCurCaps.NumSimultaneousRTs, (UINT16)BS_MAX_MULTIPLE_RENDER_TARGETS));
  1362. }
  1363. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS) == 0)
  1364. {
  1365. rsc->unsetCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1366. }
  1367. // Point sprites
  1368. if (rkCurCaps.MaxPointSize <= 1.0f)
  1369. {
  1370. rsc->unsetCapability(RSC_POINT_SPRITES);
  1371. // sprites and extended parameters go together in D3D
  1372. rsc->unsetCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1373. }
  1374. // Take the minimum point size.
  1375. if (rkCurCaps.MaxPointSize < rsc->getMaxPointSize())
  1376. rsc->setMaxPointSize(rkCurCaps.MaxPointSize);
  1377. // Mipmap LOD biasing?
  1378. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_MIPMAPLODBIAS) == 0)
  1379. rsc->unsetCapability(RSC_MIPMAP_LOD_BIAS);
  1380. // Do we support per-stage src_manual constants?
  1381. // HACK - ATI drivers seem to be buggy and don't support per-stage constants properly?
  1382. // TODO: move this to RSC
  1383. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_PERSTAGECONSTANT) == 0)
  1384. rsc->unsetCapability(RSC_PERSTAGECONSTANT);
  1385. // Advanced blend operations? min max subtract rev
  1386. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_BLENDOP) == 0)
  1387. rsc->unsetCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1388. }
  1389. // We always support compression, D3DX will decompress if device does not support
  1390. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1391. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1392. updateVertexShaderCaps(rsc);
  1393. updatePixelShaderCaps(rsc);
  1394. // Adapter details
  1395. const D3DADAPTER_IDENTIFIER9& adapterID = mActiveD3DDriver->getAdapterIdentifier();
  1396. // determine vendor
  1397. // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id
  1398. switch(adapterID.VendorId)
  1399. {
  1400. case 0x10DE:
  1401. rsc->setVendor(GPU_NVIDIA);
  1402. break;
  1403. case 0x1002:
  1404. rsc->setVendor(GPU_AMD);
  1405. break;
  1406. case 0x163C:
  1407. case 0x8086:
  1408. rsc->setVendor(GPU_INTEL);
  1409. break;
  1410. default:
  1411. rsc->setVendor(GPU_UNKNOWN);
  1412. break;
  1413. };
  1414. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1415. // We always support rendertextures bigger than the frame buffer
  1416. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1417. // Determine if any floating point texture format is supported
  1418. D3DFORMAT floatFormats[6] = {D3DFMT_R16F, D3DFMT_G16R16F,
  1419. D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F,
  1420. D3DFMT_A32B32G32R32F};
  1421. IDirect3DSurface9* bbSurf;
  1422. renderWindow->getCore()->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  1423. D3DSURFACE_DESC bbSurfDesc;
  1424. bbSurf->GetDesc(&bbSurfDesc);
  1425. for (int i = 0; i < 6; ++i)
  1426. {
  1427. if (SUCCEEDED(mpD3D->CheckDeviceFormat(mActiveD3DDriver->getAdapterNumber(),
  1428. D3DDEVTYPE_HAL, bbSurfDesc.Format,
  1429. 0, D3DRTYPE_TEXTURE, floatFormats[i])))
  1430. {
  1431. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1432. break;
  1433. }
  1434. }
  1435. // Vertex textures
  1436. if (rsc->isShaderProfileSupported("vs_3_0"))
  1437. {
  1438. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1439. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, 4);
  1440. rsc->setNumCombinedTextureUnits(rsc->getNumTextureUnits(GPT_FRAGMENT_PROGRAM) +
  1441. rsc->getNumTextureUnits(GPT_VERTEX_PROGRAM));
  1442. }
  1443. else
  1444. {
  1445. rsc->setNumCombinedTextureUnits(rsc->getNumTextureUnits(GPT_FRAGMENT_PROGRAM));
  1446. }
  1447. // Check alpha to coverage support
  1448. // this varies per vendor! But at least SM3 is required
  1449. if (rsc->isShaderProfileSupported("ps_3_0"))
  1450. {
  1451. // NVIDIA needs a separate check
  1452. if (rsc->getVendor() == GPU_NVIDIA)
  1453. {
  1454. if (mpD3D->CheckDeviceFormat(
  1455. D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
  1456. (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK)
  1457. {
  1458. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1459. }
  1460. }
  1461. else if (rsc->getVendor() == GPU_AMD)
  1462. {
  1463. // There is no check on ATI, we have to assume SM3 == support
  1464. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1465. }
  1466. // no other cards have Dx9 hacks for alpha to coverage, as far as I know
  1467. }
  1468. if (mCurrentCapabilities == nullptr)
  1469. {
  1470. mCurrentCapabilities = rsc;
  1471. mCurrentCapabilities->addShaderProfile("hlsl");
  1472. mCurrentCapabilities->addShaderProfile("cg");
  1473. if (mCurrentCapabilities->isShaderProfileSupported("hlsl"))
  1474. GpuProgramManager::instance().addFactory(mHLSLProgramFactory);
  1475. mNumTexStages = mCurrentCapabilities->getNumCombinedTextureUnits();
  1476. mTexStageDesc = bs_newN<sD3DTextureStageDesc>(mNumTexStages);
  1477. // set stages desc. to defaults
  1478. for (UINT32 n = 0; n < mNumTexStages; n++)
  1479. {
  1480. mTexStageDesc[n].coordIndex = 0;
  1481. mTexStageDesc[n].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  1482. mTexStageDesc[n].pTex = 0;
  1483. mTexStageDesc[n].pVertexTex = 0;
  1484. }
  1485. }
  1486. return rsc;
  1487. }
  1488. void D3D9RenderSystem::updateVertexShaderCaps(RenderSystemCapabilities* rsc) const
  1489. {
  1490. UINT16 major = 0xFF;
  1491. UINT16 minor = 0xFF;
  1492. D3DCAPS9 minVSCaps;
  1493. // Find the device with the lowest vertex shader caps.
  1494. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1495. {
  1496. D3D9Driver* pCurDriver = mDriverList->item(i);
  1497. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  1498. UINT16 currMajor = static_cast<UINT16>((rkCurCaps.VertexShaderVersion & 0x0000FF00) >> 8);
  1499. UINT16 currMinor = static_cast<UINT16>(rkCurCaps.VertexShaderVersion & 0x000000FF);
  1500. if (currMajor < major)
  1501. {
  1502. major = currMajor;
  1503. minor = currMinor;
  1504. minVSCaps = rkCurCaps;
  1505. }
  1506. else if (currMajor == major && currMinor < minor)
  1507. {
  1508. minor = currMinor;
  1509. minVSCaps = rkCurCaps;
  1510. }
  1511. }
  1512. // In case we didn't found any vertex shader support
  1513. // try the IDirect3DDevice9 caps instead of the IDirect3D9
  1514. // software vertex processing is reported there
  1515. if (major == 0 && minor == 0)
  1516. {
  1517. IDirect3DDevice9* lpD3DDevice9 = getActiveD3D9Device();
  1518. D3DCAPS9 d3dDeviceCaps9;
  1519. lpD3DDevice9->GetDeviceCaps(&d3dDeviceCaps9);
  1520. major = static_cast<UINT16>((d3dDeviceCaps9.VertexShaderVersion & 0x0000FF00) >> 8);
  1521. minor = static_cast<UINT16>(d3dDeviceCaps9.VertexShaderVersion & 0x000000FF);
  1522. }
  1523. bool vs2x = false;
  1524. bool vs2a = false;
  1525. // Special case detection for vs_2_x/a support
  1526. if (major >= 2)
  1527. {
  1528. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  1529. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  1530. (minVSCaps.VS20Caps.NumTemps >= 12))
  1531. {
  1532. vs2x = true;
  1533. }
  1534. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  1535. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  1536. (minVSCaps.VS20Caps.NumTemps >= 13))
  1537. {
  1538. vs2a = true;
  1539. }
  1540. }
  1541. // Populate max param count
  1542. switch (major)
  1543. {
  1544. case 1:
  1545. // No boolean params allowed
  1546. rsc->setVertexProgramConstantBoolCount(0);
  1547. // No integer params allowed
  1548. rsc->setVertexProgramConstantIntCount(0);
  1549. // float params, always 4D
  1550. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1551. break;
  1552. case 2:
  1553. // 16 boolean params allowed
  1554. rsc->setVertexProgramConstantBoolCount(16);
  1555. // 16 integer params allowed, 4D
  1556. rsc->setVertexProgramConstantIntCount(16);
  1557. // float params, always 4D
  1558. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1559. break;
  1560. case 3:
  1561. // 16 boolean params allowed
  1562. rsc->setVertexProgramConstantBoolCount(16);
  1563. // 16 integer params allowed, 4D
  1564. rsc->setVertexProgramConstantIntCount(16);
  1565. // float params, always 4D
  1566. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  1567. break;
  1568. }
  1569. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1570. switch(major)
  1571. {
  1572. case 3:
  1573. rsc->addShaderProfile("vs_3_0");
  1574. rsc->addGpuProgramProfile(GPP_VS_3_0, "vs_3_0");
  1575. case 2:
  1576. if (vs2x)
  1577. {
  1578. rsc->addShaderProfile("vs_2_x");
  1579. rsc->addGpuProgramProfile(GPP_VS_2_x, "vs_2_x");
  1580. }
  1581. if (vs2a)
  1582. {
  1583. rsc->addShaderProfile("vs_2_a");
  1584. rsc->addGpuProgramProfile(GPP_VS_2_a, "vs_2_a");
  1585. }
  1586. rsc->addShaderProfile("vs_2_0");
  1587. rsc->addGpuProgramProfile(GPP_VS_2_0, "vs_2_0");
  1588. case 1:
  1589. rsc->addShaderProfile("vs_1_1");
  1590. rsc->addGpuProgramProfile(GPP_VS_1_1, "vs_1_1");
  1591. }
  1592. }
  1593. void D3D9RenderSystem::updatePixelShaderCaps(RenderSystemCapabilities* rsc) const
  1594. {
  1595. UINT16 major = 0xFF;
  1596. UINT16 minor = 0xFF;
  1597. D3DCAPS9 minPSCaps;
  1598. // Find the device with the lowest pixel shader caps.
  1599. for (unsigned int i=0; i < mDriverList->count(); ++i)
  1600. {
  1601. D3D9Driver* pCurDriver = mDriverList->item(i);
  1602. const D3DCAPS9& currCaps = pCurDriver->getD3D9DeviceCaps();
  1603. UINT16 currMajor = static_cast<UINT16>((currCaps.PixelShaderVersion & 0x0000FF00) >> 8);
  1604. UINT16 currMinor = static_cast<UINT16>(currCaps.PixelShaderVersion & 0x000000FF);
  1605. if (currMajor < major)
  1606. {
  1607. major = currMajor;
  1608. minor = currMinor;
  1609. minPSCaps = currCaps;
  1610. }
  1611. else if (currMajor == major && currMinor < minor)
  1612. {
  1613. minor = currMinor;
  1614. minPSCaps = currCaps;
  1615. }
  1616. }
  1617. bool ps2a = false;
  1618. bool ps2b = false;
  1619. bool ps2x = false;
  1620. // Special case detection for ps_2_x/a/b support
  1621. if (major >= 2)
  1622. {
  1623. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1624. (minPSCaps.PS20Caps.NumTemps >= 32))
  1625. {
  1626. ps2b = true;
  1627. }
  1628. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1629. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NODEPENDENTREADLIMIT) &&
  1630. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_ARBITRARYSWIZZLE) &&
  1631. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) &&
  1632. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_PREDICATION) &&
  1633. (minPSCaps.PS20Caps.NumTemps >= 22))
  1634. {
  1635. ps2a = true;
  1636. }
  1637. // Does this enough?
  1638. if (ps2a || ps2b)
  1639. {
  1640. ps2x = true;
  1641. }
  1642. }
  1643. switch (major)
  1644. {
  1645. case 1:
  1646. // no boolean params allowed
  1647. rsc->setFragmentProgramConstantBoolCount(0);
  1648. // no integer params allowed
  1649. rsc->setFragmentProgramConstantIntCount(0);
  1650. // float params, always 4D
  1651. rsc->setFragmentProgramConstantFloatCount(8);
  1652. break;
  1653. case 2:
  1654. // 16 boolean params allowed
  1655. rsc->setFragmentProgramConstantBoolCount(16);
  1656. // 16 integer params allowed, 4D
  1657. rsc->setFragmentProgramConstantIntCount(16);
  1658. // float params, always 4D
  1659. rsc->setFragmentProgramConstantFloatCount(32);
  1660. break;
  1661. case 3:
  1662. // 16 boolean params allowed
  1663. rsc->setFragmentProgramConstantBoolCount(16);
  1664. // 16 integer params allowed, 4D
  1665. rsc->setFragmentProgramConstantIntCount(16);
  1666. // float params, always 4D
  1667. rsc->setFragmentProgramConstantFloatCount(224);
  1668. break;
  1669. }
  1670. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1671. switch(major)
  1672. {
  1673. case 3:
  1674. if (minor > 0)
  1675. {
  1676. rsc->addShaderProfile("ps_3_x");
  1677. rsc->addGpuProgramProfile(GPP_FS_3_x, "ps_3_x");
  1678. }
  1679. rsc->addShaderProfile("ps_3_0");
  1680. rsc->addGpuProgramProfile(GPP_FS_3_0, "ps_3_0");
  1681. case 2:
  1682. if (ps2x)
  1683. {
  1684. rsc->addShaderProfile("ps_2_x");
  1685. rsc->addGpuProgramProfile(GPP_FS_2_x, "ps_2_x");
  1686. }
  1687. if (ps2a)
  1688. {
  1689. rsc->addShaderProfile("ps_2_a");
  1690. rsc->addGpuProgramProfile(GPP_FS_2_a, "ps_2_a");
  1691. }
  1692. if (ps2b)
  1693. {
  1694. rsc->addShaderProfile("ps_2_b");
  1695. rsc->addGpuProgramProfile(GPP_FS_2_b, "ps_2_b");
  1696. }
  1697. rsc->addShaderProfile("ps_2_0");
  1698. rsc->addGpuProgramProfile(GPP_FS_2_0, "ps_2_0");
  1699. case 1:
  1700. if (major > 1 || minor >= 4)
  1701. {
  1702. rsc->addShaderProfile("ps_1_4");
  1703. rsc->addGpuProgramProfile(GPP_FS_1_4, "ps_1_4");
  1704. }
  1705. if (major > 1 || minor >= 3)
  1706. {
  1707. rsc->addShaderProfile("ps_1_3");
  1708. rsc->addGpuProgramProfile(GPP_FS_1_3, "ps_1_3");
  1709. }
  1710. if (major > 1 || minor >= 2)
  1711. {
  1712. rsc->addShaderProfile("ps_1_2");
  1713. rsc->addGpuProgramProfile(GPP_FS_1_2, "ps_1_2");
  1714. }
  1715. rsc->addShaderProfile("ps_1_1");
  1716. rsc->addGpuProgramProfile(GPP_FS_1_1, "ps_1_1");
  1717. }
  1718. }
  1719. String D3D9RenderSystem::getErrorDescription(long errorNumber) const
  1720. {
  1721. const String errMsg = DXGetErrorDescription(errorNumber);
  1722. return errMsg;
  1723. }
  1724. void D3D9RenderSystem::setClipPlane (UINT16 index, float A, float B, float C, float D)
  1725. {
  1726. float plane[4] = { A, B, C, D };
  1727. getActiveD3D9Device()->SetClipPlane (index, plane);
  1728. }
  1729. void D3D9RenderSystem::enableClipPlane (UINT16 index, bool enable)
  1730. {
  1731. DWORD prev;
  1732. getActiveD3D9Device()->GetRenderState(D3DRS_CLIPPLANEENABLE, &prev);
  1733. setRenderState(D3DRS_CLIPPLANEENABLE, enable?
  1734. (prev | (1 << index)) : (prev & ~(1 << index)));
  1735. }
  1736. void D3D9RenderSystem::notifyOnDeviceLost(D3D9Device* device)
  1737. {
  1738. if (mIsFrameInProgress)
  1739. {
  1740. endFrame();
  1741. mRestoreFrameOnReset = true;
  1742. }
  1743. }
  1744. void D3D9RenderSystem::notifyOnDeviceReset(D3D9Device* device)
  1745. {
  1746. // Reset state attributes.
  1747. mVertexProgramBound = false;
  1748. mFragmentProgramBound = false;
  1749. if (mRestoreFrameOnReset)
  1750. {
  1751. beginFrame();
  1752. mRestoreFrameOnReset = false;
  1753. }
  1754. }
  1755. void D3D9RenderSystem::determineMultisampleSettings(IDirect3DDevice9* d3d9Device, UINT32 multisampleCount, D3DFORMAT d3dPixelFormat,
  1756. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality) const
  1757. {
  1758. bool tryCSAA = false; // Note: Disabled for now, but leaving the code for later so it might be useful
  1759. enum CSAAMode { CSAA_Normal, CSAA_Quality };
  1760. CSAAMode csaaMode = CSAA_Normal;
  1761. D3D9DriverList* driverList = getDirect3DDrivers();
  1762. D3D9Driver* deviceDriver = mActiveD3DDriver;
  1763. D3D9Device* device = mDeviceManager->getDeviceFromD3D9Device(d3d9Device);
  1764. for (UINT32 i = 0; i < driverList->count(); ++i)
  1765. {
  1766. D3D9Driver* currDriver = driverList->item(i);
  1767. if (currDriver->getAdapterNumber() == device->getAdapterNumber())
  1768. {
  1769. deviceDriver = currDriver;
  1770. break;
  1771. }
  1772. }
  1773. UINT32 origNumSamples = multisampleCount;
  1774. bool foundValid = false;
  1775. while (!foundValid)
  1776. {
  1777. // Deal with special cases
  1778. if (tryCSAA)
  1779. {
  1780. switch(multisampleCount)
  1781. {
  1782. case 8:
  1783. if (csaaMode == CSAA_Quality)
  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 (csaaMode == CSAA_Quality)
  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. foundValid = 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 (csaaMode == CSAA_Quality)
  1835. {
  1836. // Drop quality first
  1837. csaaMode = CSAA_Normal;
  1838. }
  1839. else
  1840. {
  1841. // Drop CSAA entirely
  1842. tryCSAA = false;
  1843. }
  1844. // Return to original requested samples
  1845. multisampleCount = origNumSamples;
  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. foundValid = true;
  1856. }
  1857. }
  1858. }
  1859. }
  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. }