CmD3D9RenderSystem.cpp 88 KB

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