CmD3D9RenderSystem.cpp 96 KB

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