BsD3D9RenderSystem.cpp 69 KB

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