CmD3D9RenderSystem.cpp 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784
  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 "CmD3D9HardwareBufferManager.h"
  35. #include "CmD3D9HardwareIndexBuffer.h"
  36. #include "CmD3D9HardwareVertexBuffer.h"
  37. #include "CmD3D9VertexDeclaration.h"
  38. #include "CmD3D9GpuProgram.h"
  39. #include "CmD3D9GpuProgramManager.h"
  40. #include "CmD3D9HLSLProgramFactory.h"
  41. #include "CmD3D9HardwareOcclusionQuery.h"
  42. #include "CmFrustum.h"
  43. #include "CmD3D9MultiRenderTarget.h"
  44. #include "CmD3D9DeviceManager.h"
  45. #include "CmD3D9ResourceManager.h"
  46. #include "CmHighLevelGpuProgramManager.h"
  47. #define FLOAT2DWORD(f) *((DWORD*)&f)
  48. namespace CamelotEngine
  49. {
  50. D3D9RenderSystem* D3D9RenderSystem::msD3D9RenderSystem = NULL;
  51. //---------------------------------------------------------------------
  52. D3D9RenderSystem::D3D9RenderSystem( HINSTANCE hInstance )
  53. {
  54. // update singleton access pointer.
  55. msD3D9RenderSystem = this;
  56. // set the instance being passed
  57. mhInstance = hInstance;
  58. // set pointers to NULL
  59. mpD3D = NULL;
  60. mDriverList = NULL;
  61. mActiveD3DDriver = NULL;
  62. mUseNVPerfHUD = false;
  63. mHLSLProgramFactory = NULL;
  64. mCgProgramFactory = NULL;
  65. mDeviceManager = NULL;
  66. // Create the resource manager.
  67. mResourceManager = new D3D9ResourceManager();
  68. // Create our Direct3D object
  69. if( NULL == (mpD3D = Direct3DCreate9(D3D_SDK_VERSION)) )
  70. CM_EXCEPT(InternalErrorException, "Failed to create Direct3D9 object");
  71. // set config options defaults
  72. initConfigOptions();
  73. // fsaa options
  74. mFSAAHint = "";
  75. mFSAASamples = 0;
  76. // set stages desc. to defaults
  77. for (size_t n = 0; n < CM_MAX_TEXTURE_LAYERS; n++)
  78. {
  79. mTexStageDesc[n].autoTexCoordType = TEXCALC_NONE;
  80. mTexStageDesc[n].coordIndex = 0;
  81. mTexStageDesc[n].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  82. mTexStageDesc[n].pTex = 0;
  83. mTexStageDesc[n].pVertexTex = 0;
  84. }
  85. mLastVertexSourceCount = 0;
  86. mCurrentLights.clear();
  87. // Enumerate events
  88. mEventNames.push_back("DeviceLost");
  89. mEventNames.push_back("DeviceRestored");
  90. }
  91. //---------------------------------------------------------------------
  92. D3D9RenderSystem::~D3D9RenderSystem()
  93. {
  94. shutdown();
  95. // Deleting the HLSL program factory
  96. if (mHLSLProgramFactory)
  97. {
  98. HighLevelGpuProgramManager::instance().removeFactory(mHLSLProgramFactory);
  99. delete mHLSLProgramFactory;
  100. mHLSLProgramFactory = 0;
  101. }
  102. if(mCgProgramFactory)
  103. {
  104. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  105. delete mCgProgramFactory;
  106. mCgProgramFactory = 0;
  107. }
  108. SAFE_RELEASE( mpD3D );
  109. SAFE_DELETE ( mResourceManager );
  110. msD3D9RenderSystem = NULL;
  111. }
  112. //---------------------------------------------------------------------
  113. const String& D3D9RenderSystem::getName() const
  114. {
  115. static String strName( "Direct3D9 Rendering Subsystem");
  116. return strName;
  117. }
  118. //---------------------------------------------------------------------
  119. D3D9DriverList* D3D9RenderSystem::getDirect3DDrivers()
  120. {
  121. if( !mDriverList )
  122. mDriverList = new D3D9DriverList();
  123. return mDriverList;
  124. }
  125. //---------------------------------------------------------------------
  126. bool D3D9RenderSystem::_checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen)
  127. {
  128. HRESULT hr;
  129. hr = mpD3D->CheckDeviceMultiSampleType(
  130. adapterNum,
  131. deviceType,
  132. format,
  133. fullScreen,
  134. type,
  135. outQuality);
  136. if (SUCCEEDED(hr))
  137. return true;
  138. else
  139. return false;
  140. }
  141. //---------------------------------------------------------------------
  142. void D3D9RenderSystem::initConfigOptions()
  143. {
  144. D3D9DriverList* driverList;
  145. D3D9Driver* driver;
  146. ConfigOption optDevice;
  147. ConfigOption optVideoMode;
  148. ConfigOption optFullScreen;
  149. ConfigOption optVSync;
  150. ConfigOption optVSyncInterval;
  151. ConfigOption optAA;
  152. ConfigOption optFPUMode;
  153. ConfigOption optNVPerfHUD;
  154. ConfigOption optSRGB;
  155. ConfigOption optResourceCeationPolicy;
  156. driverList = this->getDirect3DDrivers();
  157. optDevice.name = "Rendering Device";
  158. optDevice.currentValue.clear();
  159. optDevice.possibleValues.clear();
  160. optDevice.immutable = false;
  161. optVideoMode.name = "Video Mode";
  162. optVideoMode.currentValue = "800 x 600 @ 32-bit colour";
  163. optVideoMode.immutable = false;
  164. optFullScreen.name = "Full Screen";
  165. optFullScreen.possibleValues.push_back( "Yes" );
  166. optFullScreen.possibleValues.push_back( "No" );
  167. optFullScreen.currentValue = "Yes";
  168. optFullScreen.immutable = false;
  169. optResourceCeationPolicy.name = "Resource Creation Policy";
  170. optResourceCeationPolicy.possibleValues.push_back( "Create on all devices" );
  171. optResourceCeationPolicy.possibleValues.push_back( "Create on active device" );
  172. if (mResourceManager->getCreationPolicy() == RCP_CREATE_ON_ACTIVE_DEVICE)
  173. optResourceCeationPolicy.currentValue = "Create on active device";
  174. else if (mResourceManager->getCreationPolicy() == RCP_CREATE_ON_ALL_DEVICES)
  175. optResourceCeationPolicy.currentValue = "Create on all devices";
  176. else
  177. optResourceCeationPolicy.currentValue = "N/A";
  178. optResourceCeationPolicy.immutable = false;
  179. for( unsigned j=0; j < driverList->count(); j++ )
  180. {
  181. driver = driverList->item(j);
  182. optDevice.possibleValues.push_back( driver->DriverDescription() );
  183. // Make first one default
  184. if( j==0 )
  185. optDevice.currentValue = driver->DriverDescription();
  186. }
  187. optVSync.name = "VSync";
  188. optVSync.immutable = false;
  189. optVSync.possibleValues.push_back( "Yes" );
  190. optVSync.possibleValues.push_back( "No" );
  191. optVSync.currentValue = "No";
  192. optVSyncInterval.name = "VSync Interval";
  193. optVSyncInterval.immutable = false;
  194. optVSyncInterval.possibleValues.push_back( "1" );
  195. optVSyncInterval.possibleValues.push_back( "2" );
  196. optVSyncInterval.possibleValues.push_back( "3" );
  197. optVSyncInterval.possibleValues.push_back( "4" );
  198. optVSyncInterval.currentValue = "1";
  199. optAA.name = "FSAA";
  200. optAA.immutable = false;
  201. optAA.possibleValues.push_back( "None" );
  202. optAA.currentValue = "None";
  203. optFPUMode.name = "Floating-point mode";
  204. #if OGRE_DOUBLE_PRECISION
  205. optFPUMode.currentValue = "Consistent";
  206. #else
  207. optFPUMode.currentValue = "Fastest";
  208. #endif
  209. optFPUMode.possibleValues.clear();
  210. optFPUMode.possibleValues.push_back("Fastest");
  211. optFPUMode.possibleValues.push_back("Consistent");
  212. optFPUMode.immutable = false;
  213. optNVPerfHUD.currentValue = "No";
  214. optNVPerfHUD.immutable = false;
  215. optNVPerfHUD.name = "Allow NVPerfHUD";
  216. optNVPerfHUD.possibleValues.push_back( "Yes" );
  217. optNVPerfHUD.possibleValues.push_back( "No" );
  218. // SRGB on auto window
  219. optSRGB.name = "sRGB Gamma Conversion";
  220. optSRGB.possibleValues.push_back("Yes");
  221. optSRGB.possibleValues.push_back("No");
  222. optSRGB.currentValue = "No";
  223. optSRGB.immutable = false;
  224. mOptions[optDevice.name] = optDevice;
  225. mOptions[optVideoMode.name] = optVideoMode;
  226. mOptions[optFullScreen.name] = optFullScreen;
  227. mOptions[optVSync.name] = optVSync;
  228. mOptions[optVSyncInterval.name] = optVSyncInterval;
  229. mOptions[optAA.name] = optAA;
  230. mOptions[optFPUMode.name] = optFPUMode;
  231. mOptions[optNVPerfHUD.name] = optNVPerfHUD;
  232. mOptions[optSRGB.name] = optSRGB;
  233. mOptions[optResourceCeationPolicy.name] = optResourceCeationPolicy;
  234. refreshD3DSettings();
  235. }
  236. //---------------------------------------------------------------------
  237. void D3D9RenderSystem::refreshD3DSettings()
  238. {
  239. ConfigOption* optVideoMode;
  240. D3D9Driver* driver = 0;
  241. D3D9VideoMode* videoMode;
  242. ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" );
  243. if( opt != mOptions.end() )
  244. {
  245. for( unsigned j=0; j < getDirect3DDrivers()->count(); j++ )
  246. {
  247. D3D9Driver* curDriver = getDirect3DDrivers()->item(j);
  248. if( curDriver->DriverDescription() == opt->second.currentValue )
  249. {
  250. driver = curDriver;
  251. break;
  252. }
  253. }
  254. if (driver)
  255. {
  256. opt = mOptions.find( "Video Mode" );
  257. optVideoMode = &opt->second;
  258. optVideoMode->possibleValues.clear();
  259. // get vide modes for this device
  260. for( unsigned k=0; k < driver->getVideoModeList()->count(); k++ )
  261. {
  262. videoMode = driver->getVideoModeList()->item( k );
  263. optVideoMode->possibleValues.push_back( videoMode->getDescription() );
  264. }
  265. // Reset video mode to default if previous doesn't avail in new possible values
  266. std::vector<CamelotEngine::String>::const_iterator itValue =
  267. std::find(optVideoMode->possibleValues.begin(),
  268. optVideoMode->possibleValues.end(),
  269. optVideoMode->currentValue);
  270. if (itValue == optVideoMode->possibleValues.end())
  271. {
  272. optVideoMode->currentValue = "800 x 600 @ 32-bit colour";
  273. }
  274. // Also refresh FSAA options
  275. refreshFSAAOptions();
  276. }
  277. }
  278. }
  279. //---------------------------------------------------------------------
  280. void D3D9RenderSystem::setConfigOption( const String &name, const String &value )
  281. {
  282. bool viewModeChanged = false;
  283. // Find option
  284. ConfigOptionMap::iterator it = mOptions.find( name );
  285. // Update
  286. if( it != mOptions.end() )
  287. it->second.currentValue = value;
  288. else
  289. {
  290. StringUtil::StrStreamType str;
  291. str << "Option named '" << name << "' does not exist.";
  292. CM_EXCEPT(InvalidParametersException, str.str() );
  293. }
  294. // Refresh other options if D3DDriver changed
  295. if( name == "Rendering Device" )
  296. refreshD3DSettings();
  297. if( name == "Full Screen" )
  298. {
  299. // Video mode is applicable
  300. it = mOptions.find( "Video Mode" );
  301. if (it->second.currentValue.empty())
  302. {
  303. it->second.currentValue = "800 x 600 @ 32-bit colour";
  304. viewModeChanged = true;
  305. }
  306. }
  307. if( name == "FSAA" )
  308. {
  309. std::vector<CamelotEngine::String> values = StringUtil::split(value, " ", 1);
  310. mFSAASamples = parseUnsignedInt(values[0]);
  311. if (values.size() > 1)
  312. mFSAAHint = values[1];
  313. }
  314. if( name == "VSync" )
  315. {
  316. if (value == "Yes")
  317. mVSync = true;
  318. else
  319. mVSync = false;
  320. }
  321. if( name == "VSync Interval" )
  322. {
  323. mVSyncInterval = parseUnsignedInt(value);
  324. }
  325. if( name == "Allow NVPerfHUD" )
  326. {
  327. if (value == "Yes")
  328. mUseNVPerfHUD = true;
  329. else
  330. mUseNVPerfHUD = false;
  331. }
  332. if (viewModeChanged || name == "Video Mode")
  333. {
  334. refreshFSAAOptions();
  335. }
  336. if (name == "Resource Creation Policy")
  337. {
  338. if (value == "Create on active device")
  339. mResourceManager->setCreationPolicy(RCP_CREATE_ON_ACTIVE_DEVICE);
  340. else if (value == "Create on all devices")
  341. mResourceManager->setCreationPolicy(RCP_CREATE_ON_ALL_DEVICES);
  342. }
  343. }
  344. //---------------------------------------------------------------------
  345. void D3D9RenderSystem::refreshFSAAOptions()
  346. {
  347. ConfigOptionMap::iterator it = mOptions.find( "FSAA" );
  348. ConfigOption* optFSAA = &it->second;
  349. optFSAA->possibleValues.clear();
  350. optFSAA->possibleValues.push_back("0");
  351. it = mOptions.find("Rendering Device");
  352. D3D9Driver *driver = getDirect3DDrivers()->item(it->second.currentValue);
  353. if (driver)
  354. {
  355. it = mOptions.find("Video Mode");
  356. D3D9VideoMode *videoMode = driver->getVideoModeList()->item(it->second.currentValue);
  357. if (videoMode)
  358. {
  359. DWORD numLevels = 0;
  360. bool bOK;
  361. for (unsigned int n = 2; n < 25; n++)
  362. {
  363. bOK = this->_checkMultiSampleQuality(
  364. (D3DMULTISAMPLE_TYPE)n,
  365. &numLevels,
  366. videoMode->getFormat(),
  367. driver->getAdapterNumber(),
  368. D3DDEVTYPE_HAL,
  369. TRUE);
  370. if (bOK)
  371. {
  372. optFSAA->possibleValues.push_back(toString(n));
  373. if (n >= 8)
  374. optFSAA->possibleValues.push_back(toString(n) + " [Quality]");
  375. }
  376. }
  377. }
  378. }
  379. // Reset FSAA to none if previous doesn't avail in new possible values
  380. std::vector<CamelotEngine::String>::const_iterator itValue =
  381. std::find(optFSAA->possibleValues.begin(),
  382. optFSAA->possibleValues.end(),
  383. optFSAA->currentValue);
  384. if (itValue == optFSAA->possibleValues.end())
  385. {
  386. optFSAA->currentValue = "0";
  387. }
  388. }
  389. //---------------------------------------------------------------------
  390. String D3D9RenderSystem::validateConfigOptions()
  391. {
  392. ConfigOptionMap::iterator it;
  393. // check if video mode is selected
  394. it = mOptions.find( "Video Mode" );
  395. if (it->second.currentValue.empty())
  396. return "A video mode must be selected.";
  397. it = mOptions.find( "Rendering Device" );
  398. bool foundDriver = false;
  399. D3D9DriverList* driverList = getDirect3DDrivers();
  400. for( UINT16 j=0; j < driverList->count(); j++ )
  401. {
  402. if( driverList->item(j)->DriverDescription() == it->second.currentValue )
  403. {
  404. foundDriver = true;
  405. break;
  406. }
  407. }
  408. if (!foundDriver)
  409. {
  410. // Just pick the first driver
  411. setConfigOption("Rendering Device", driverList->item(0)->DriverDescription());
  412. return "Your DirectX driver name has changed since the last time you ran OGRE; "
  413. "the 'Rendering Device' has been changed.";
  414. }
  415. it = mOptions.find( "VSync" );
  416. if( it->second.currentValue == "Yes" )
  417. mVSync = true;
  418. else
  419. mVSync = false;
  420. return StringUtil::BLANK;
  421. }
  422. //---------------------------------------------------------------------
  423. RenderWindow* D3D9RenderSystem::_initialise( bool autoCreateWindow, const String& windowTitle )
  424. {
  425. RenderWindow* autoWindow = NULL;
  426. // Init using current settings
  427. mActiveD3DDriver = NULL;
  428. ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" );
  429. for( UINT32 j=0; j < getDirect3DDrivers()->count(); j++ )
  430. {
  431. if( getDirect3DDrivers()->item(j)->DriverDescription() == opt->second.currentValue )
  432. {
  433. mActiveD3DDriver = getDirect3DDrivers()->item(j);
  434. break;
  435. }
  436. }
  437. if( !mActiveD3DDriver )
  438. CM_EXCEPT(InvalidParametersException, "Problems finding requested Direct3D driver!" );
  439. // get driver version
  440. mDriverVersion.major = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  441. mDriverVersion.minor = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart);
  442. mDriverVersion.release = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  443. mDriverVersion.build = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart);
  444. // Create the device manager.
  445. mDeviceManager = new D3D9DeviceManager();
  446. // Create the texture manager for use by others
  447. TextureManager::startUp(new D3D9TextureManager());
  448. // Also create hardware buffer manager
  449. HardwareBufferManager::startUp(new D3D9HardwareBufferManager());
  450. // Create the GPU program manager
  451. GpuProgramManager::startUp(new D3D9GpuProgramManager());
  452. // Create & register HLSL factory
  453. mHLSLProgramFactory = new D3D9HLSLProgramFactory();
  454. // Create & register Cg factory
  455. mCgProgramFactory = new CgProgramFactory();
  456. if( autoCreateWindow )
  457. {
  458. bool fullScreen;
  459. opt = mOptions.find( "Full Screen" );
  460. if( opt == mOptions.end() )
  461. CM_EXCEPT(InternalErrorException, "Can't find full screen option!");
  462. fullScreen = opt->second.currentValue == "Yes";
  463. D3D9VideoMode* videoMode = NULL;
  464. unsigned int width, height;
  465. String temp;
  466. opt = mOptions.find( "Video Mode" );
  467. if( opt == mOptions.end() )
  468. CM_EXCEPT(InternalErrorException, "Can't find Video Mode option!");
  469. // The string we are manipulating looks like this :width x height @ colourDepth
  470. // Pull out the colour depth by getting what comes after the @ and a space
  471. String colourDepth = opt->second.currentValue.substr(opt->second.currentValue.rfind('@')+1);
  472. // Now we know that the width starts a 0, so if we can find the end we can parse that out
  473. String::size_type widthEnd = opt->second.currentValue.find(' ');
  474. // we know that the height starts 3 characters after the width and goes until the next space
  475. String::size_type heightEnd = opt->second.currentValue.find(' ', widthEnd+3);
  476. // Now we can parse out the values
  477. width = parseInt(opt->second.currentValue.substr(0, widthEnd));
  478. height = parseInt(opt->second.currentValue.substr(widthEnd+3, heightEnd));
  479. for( unsigned j=0; j < mActiveD3DDriver->getVideoModeList()->count(); j++ )
  480. {
  481. temp = mActiveD3DDriver->getVideoModeList()->item(j)->getDescription();
  482. // In full screen we only want to allow supported resolutions, so temp and opt->second.currentValue need to
  483. // match exactly, but in windowed mode we can allow for arbitrary window sized, so we only need
  484. // to match the colour values
  485. if(fullScreen && (temp == opt->second.currentValue) ||
  486. !fullScreen && (temp.substr(temp.rfind('@')+1) == colourDepth))
  487. {
  488. videoMode = mActiveD3DDriver->getVideoModeList()->item(j);
  489. break;
  490. }
  491. }
  492. if( !videoMode )
  493. CM_EXCEPT(InternalErrorException, "Can't find requested video mode.");
  494. // sRGB window option
  495. bool hwGamma = false;
  496. opt = mOptions.find( "sRGB Gamma Conversion" );
  497. if( opt == mOptions.end() )
  498. CM_EXCEPT(InternalErrorException, "Can't find sRGB option!");
  499. hwGamma = opt->second.currentValue == "Yes";
  500. NameValuePairList miscParams;
  501. miscParams["colourDepth"] = toString(videoMode->getColourDepth());
  502. miscParams["FSAA"] = toString(mFSAASamples);
  503. miscParams["FSAAHint"] = mFSAAHint;
  504. miscParams["vsync"] = toString(mVSync);
  505. miscParams["vsyncInterval"] = toString(mVSyncInterval);
  506. miscParams["useNVPerfHUD"] = toString(mUseNVPerfHUD);
  507. miscParams["gamma"] = toString(hwGamma);
  508. miscParams["monitorIndex"] = toString(static_cast<int>(mActiveD3DDriver->getAdapterNumber()));
  509. autoWindow = _createRenderWindow( windowTitle, width, height,
  510. fullScreen, &miscParams );
  511. // If we have 16bit depth buffer enable w-buffering.
  512. assert( autoWindow );
  513. if ( autoWindow->getColourDepth() == 16 )
  514. {
  515. mWBuffer = true;
  516. }
  517. else
  518. {
  519. mWBuffer = false;
  520. }
  521. }
  522. // call superclass method
  523. RenderSystem::_initialise( autoCreateWindow );
  524. return autoWindow;
  525. }
  526. //---------------------------------------------------------------------
  527. void D3D9RenderSystem::reinitialise()
  528. {
  529. this->shutdown();
  530. this->_initialise( true );
  531. }
  532. //---------------------------------------------------------------------
  533. void D3D9RenderSystem::shutdown()
  534. {
  535. RenderSystem::shutdown();
  536. SAFE_DELETE( mDeviceManager );
  537. SAFE_DELETE( mDriverList );
  538. mActiveD3DDriver = NULL;
  539. TextureManager::shutDown();
  540. HardwareBufferManager::shutDown();
  541. GpuProgramManager::shutDown();
  542. }
  543. //---------------------------------------------------------------------
  544. RenderWindow* D3D9RenderSystem::_createRenderWindow(const String &name,
  545. unsigned int width, unsigned int height, bool fullScreen,
  546. const NameValuePairList *miscParams)
  547. {
  548. // Log a message
  549. StringStream ss;
  550. ss << "D3D9RenderSystem::_createRenderWindow \"" << name << "\", " <<
  551. width << "x" << height << " ";
  552. if(fullScreen)
  553. ss << "fullscreen ";
  554. else
  555. ss << "windowed ";
  556. if(miscParams)
  557. {
  558. ss << " miscParams: ";
  559. NameValuePairList::const_iterator it;
  560. for(it=miscParams->begin(); it!=miscParams->end(); ++it)
  561. {
  562. ss << it->first << "=" << it->second << " ";
  563. }
  564. }
  565. String msg;
  566. // Make sure we don't already have a render target of the
  567. // same name as the one supplied
  568. if( mRenderTargets.find( name ) != mRenderTargets.end() )
  569. {
  570. msg = "A render target of the same name '" + name + "' already "
  571. "exists. You cannot create a new window with this name.";
  572. CM_EXCEPT(InternalErrorException, msg);
  573. }
  574. D3D9RenderWindow* renderWindow = new D3D9RenderWindow(mhInstance);
  575. renderWindow->create(name, width, height, fullScreen, miscParams);
  576. mResourceManager->lockDeviceAccess();
  577. try
  578. {
  579. mDeviceManager->linkRenderWindow(renderWindow);
  580. }
  581. catch (const CamelotEngine::RenderingAPIException&)
  582. {
  583. // after catching the exception, clean up
  584. mResourceManager->unlockDeviceAccess();
  585. renderWindow->destroy();
  586. // re-throw
  587. throw;
  588. }
  589. mResourceManager->unlockDeviceAccess();
  590. mRenderWindows.push_back(renderWindow);
  591. updateRenderSystemCapabilities(renderWindow);
  592. attachRenderTarget( *renderWindow );
  593. return renderWindow;
  594. }
  595. //---------------------------------------------------------------------
  596. bool D3D9RenderSystem::_createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
  597. RenderWindowList& createdWindows)
  598. {
  599. // Call base render system method.
  600. if (false == RenderSystem::_createRenderWindows(renderWindowDescriptions, createdWindows))
  601. return false;
  602. // Simply call _createRenderWindow in a loop.
  603. for (size_t i = 0; i < renderWindowDescriptions.size(); ++i)
  604. {
  605. const RenderWindowDescription& curRenderWindowDescription = renderWindowDescriptions[i];
  606. RenderWindow* curWindow = NULL;
  607. curWindow = _createRenderWindow(curRenderWindowDescription.name,
  608. curRenderWindowDescription.width,
  609. curRenderWindowDescription.height,
  610. curRenderWindowDescription.useFullScreen,
  611. &curRenderWindowDescription.miscParams);
  612. createdWindows.push_back(curWindow);
  613. }
  614. return true;
  615. }
  616. //---------------------------------------------------------------------
  617. RenderSystemCapabilities* D3D9RenderSystem::updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow)
  618. {
  619. RenderSystemCapabilities* rsc = mRealCapabilities;
  620. if (rsc == NULL)
  621. rsc = new RenderSystemCapabilities();
  622. rsc->setCategoryRelevant(CAPS_CATEGORY_D3D9, true);
  623. rsc->setDriverVersion(mDriverVersion);
  624. rsc->setDeviceName(mActiveD3DDriver->DriverDescription());
  625. rsc->setRenderSystemName(getName());
  626. // Supports fixed-function
  627. rsc->setCapability(RSC_FIXED_FUNCTION);
  628. // Init caps to maximum.
  629. rsc->setNumTextureUnits(1024);
  630. rsc->setCapability(RSC_ANISOTROPY);
  631. rsc->setCapability(RSC_AUTOMIPMAP);
  632. rsc->setCapability(RSC_DOT3);
  633. rsc->setCapability(RSC_CUBEMAPPING);
  634. rsc->setCapability(RSC_SCISSOR_TEST);
  635. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  636. rsc->setCapability(RSC_STENCIL_WRAP);
  637. rsc->setCapability(RSC_HWOCCLUSION);
  638. rsc->setCapability(RSC_USER_CLIP_PLANES);
  639. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  640. rsc->setCapability(RSC_TEXTURE_3D);
  641. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  642. rsc->setNonPOW2TexturesLimited(false);
  643. rsc->setNumMultiRenderTargets(CM_MAX_MULTIPLE_RENDER_TARGETS);
  644. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  645. rsc->setCapability(RSC_POINT_SPRITES);
  646. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  647. rsc->setMaxPointSize(10.0);
  648. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  649. rsc->setCapability(RSC_PERSTAGECONSTANT);
  650. rsc->setCapability(RSC_HWSTENCIL);
  651. rsc->setStencilBufferBitDepth(8);
  652. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  653. for (UINT32 i=0; i < mDeviceManager->getDeviceCount(); ++i)
  654. {
  655. D3D9Device* device = mDeviceManager->getDevice(i);
  656. IDirect3DDevice9* d3d9Device = device->getD3D9Device();
  657. IDirect3DSurface9* pSurf;
  658. // Check for hardware stencil support
  659. d3d9Device->GetDepthStencilSurface(&pSurf);
  660. if (pSurf != NULL)
  661. {
  662. D3DSURFACE_DESC surfDesc;
  663. pSurf->GetDesc(&surfDesc);
  664. pSurf->Release();
  665. if (surfDesc.Format != D3DFMT_D15S1 &&
  666. surfDesc.Format != D3DFMT_D24S8 &&
  667. surfDesc.Format != D3DFMT_D24X4S4 &&
  668. surfDesc.Format != D3DFMT_D24FS8)
  669. rsc->unsetCapability(RSC_HWSTENCIL);
  670. }
  671. // Check for hardware occlusion support
  672. HRESULT hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL);
  673. if (FAILED(hr))
  674. rsc->unsetCapability(RSC_HWOCCLUSION);
  675. }
  676. // Update RS caps using the minimum value found in adapter list.
  677. for (unsigned int i=0; i < mDriverList->count(); ++i)
  678. {
  679. D3D9Driver* pCurDriver = mDriverList->item(i);
  680. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  681. if (rkCurCaps.MaxSimultaneousTextures < rsc->getNumTextureUnits())
  682. {
  683. rsc->setNumTextureUnits(static_cast<UINT16>(rkCurCaps.MaxSimultaneousTextures));
  684. }
  685. // Check for Anisotropy.
  686. if (rkCurCaps.MaxAnisotropy <= 1)
  687. rsc->unsetCapability(RSC_ANISOTROPY);
  688. // Check automatic mipmap generation.
  689. if ((rkCurCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) == 0)
  690. rsc->unsetCapability(RSC_AUTOMIPMAP);
  691. // Check Dot product 3.
  692. if ((rkCurCaps.TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) == 0)
  693. rsc->unsetCapability(RSC_DOT3);
  694. // Scissor test
  695. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST) == 0)
  696. rsc->unsetCapability(RSC_SCISSOR_TEST);
  697. // Two-sided stencil
  698. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) == 0)
  699. rsc->unsetCapability(RSC_TWO_SIDED_STENCIL);
  700. // stencil wrap
  701. if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_INCR) == 0 ||
  702. (rkCurCaps.StencilCaps & D3DSTENCILCAPS_DECR) == 0)
  703. rsc->unsetCapability(RSC_STENCIL_WRAP);
  704. // User clip planes
  705. if (rkCurCaps.MaxUserClipPlanes == 0)
  706. rsc->unsetCapability(RSC_USER_CLIP_PLANES);
  707. // UBYTE4 type?
  708. if ((rkCurCaps.DeclTypes & D3DDTCAPS_UBYTE4) == 0)
  709. rsc->unsetCapability(RSC_VERTEX_FORMAT_UBYTE4);
  710. // Check cube map support.
  711. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP) == 0)
  712. rsc->unsetCapability(RSC_CUBEMAPPING);
  713. // 3D textures?
  714. if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_VOLUMEMAP) == 0)
  715. rsc->unsetCapability(RSC_TEXTURE_3D);
  716. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_POW2)
  717. {
  718. // Conditional support for non POW2
  719. if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL)
  720. rsc->setNonPOW2TexturesLimited(true);
  721. // Only power of 2 supported.
  722. else
  723. rsc->unsetCapability(RSC_NON_POWER_OF_2_TEXTURES);
  724. }
  725. // Number of render targets
  726. if (rkCurCaps.NumSimultaneousRTs < rsc->getNumMultiRenderTargets())
  727. {
  728. rsc->setNumMultiRenderTargets(std::min((UINT16)rkCurCaps.NumSimultaneousRTs, (UINT16)CM_MAX_MULTIPLE_RENDER_TARGETS));
  729. }
  730. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS) == 0)
  731. {
  732. rsc->unsetCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  733. }
  734. // Point sprites
  735. if (rkCurCaps.MaxPointSize <= 1.0f)
  736. {
  737. rsc->unsetCapability(RSC_POINT_SPRITES);
  738. // sprites and extended parameters go together in D3D
  739. rsc->unsetCapability(RSC_POINT_EXTENDED_PARAMETERS);
  740. }
  741. // Take the minimum point size.
  742. if (rkCurCaps.MaxPointSize < rsc->getMaxPointSize())
  743. rsc->setMaxPointSize(rkCurCaps.MaxPointSize);
  744. // Mipmap LOD biasing?
  745. if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_MIPMAPLODBIAS) == 0)
  746. rsc->unsetCapability(RSC_MIPMAP_LOD_BIAS);
  747. // Do we support per-stage src_manual constants?
  748. // HACK - ATI drivers seem to be buggy and don't support per-stage constants properly?
  749. // TODO: move this to RSC
  750. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_PERSTAGECONSTANT) == 0)
  751. rsc->unsetCapability(RSC_PERSTAGECONSTANT);
  752. // Advanced blend operations? min max subtract rev
  753. if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_BLENDOP) == 0)
  754. rsc->unsetCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  755. }
  756. // Blending between stages supported
  757. rsc->setCapability(RSC_BLENDING);
  758. // We always support compression, D3DX will decompress if device does not support
  759. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  760. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  761. // We always support VBOs
  762. rsc->setCapability(RSC_VBO);
  763. convertVertexShaderCaps(rsc);
  764. convertPixelShaderCaps(rsc);
  765. // Adapter details
  766. const D3DADAPTER_IDENTIFIER9& adapterID = mActiveD3DDriver->getAdapterIdentifier();
  767. // determine vendor
  768. // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id
  769. switch(adapterID.VendorId)
  770. {
  771. case 0x10DE:
  772. rsc->setVendor(GPU_NVIDIA);
  773. break;
  774. case 0x1002:
  775. rsc->setVendor(GPU_ATI);
  776. break;
  777. case 0x163C:
  778. case 0x8086:
  779. rsc->setVendor(GPU_INTEL);
  780. break;
  781. case 0x5333:
  782. rsc->setVendor(GPU_S3);
  783. break;
  784. case 0x3D3D:
  785. rsc->setVendor(GPU_3DLABS);
  786. break;
  787. case 0x102B:
  788. rsc->setVendor(GPU_MATROX);
  789. break;
  790. case 0x1039:
  791. rsc->setVendor(GPU_SIS);
  792. break;
  793. default:
  794. rsc->setVendor(GPU_UNKNOWN);
  795. break;
  796. };
  797. // Infinite projection?
  798. // We have no capability for this, so we have to base this on our
  799. // experience and reports from users
  800. // Non-vertex program capable hardware does not appear to support it
  801. if (rsc->hasCapability(RSC_VERTEX_PROGRAM))
  802. {
  803. // GeForce4 Ti (and presumably GeForce3) does not
  804. // render infinite projection properly, even though it does in GL
  805. // So exclude all cards prior to the FX range from doing infinite
  806. if (rsc->getVendor() != GPU_NVIDIA || // not nVidia
  807. !((adapterID.DeviceId >= 0x200 && adapterID.DeviceId <= 0x20F) || //gf3
  808. (adapterID.DeviceId >= 0x250 && adapterID.DeviceId <= 0x25F) || //gf4ti
  809. (adapterID.DeviceId >= 0x280 && adapterID.DeviceId <= 0x28F) || //gf4ti
  810. (adapterID.DeviceId >= 0x170 && adapterID.DeviceId <= 0x18F) || //gf4 go
  811. (adapterID.DeviceId >= 0x280 && adapterID.DeviceId <= 0x28F))) //gf4ti go
  812. {
  813. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  814. }
  815. }
  816. // We always support rendertextures bigger than the frame buffer
  817. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  818. // Determine if any floating point texture format is supported
  819. D3DFORMAT floatFormats[6] = {D3DFMT_R16F, D3DFMT_G16R16F,
  820. D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F,
  821. D3DFMT_A32B32G32R32F};
  822. IDirect3DSurface9* bbSurf;
  823. renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  824. D3DSURFACE_DESC bbSurfDesc;
  825. bbSurf->GetDesc(&bbSurfDesc);
  826. for (int i = 0; i < 6; ++i)
  827. {
  828. if (SUCCEEDED(mpD3D->CheckDeviceFormat(mActiveD3DDriver->getAdapterNumber(),
  829. D3DDEVTYPE_HAL, bbSurfDesc.Format,
  830. 0, D3DRTYPE_TEXTURE, floatFormats[i])))
  831. {
  832. rsc->setCapability(RSC_TEXTURE_FLOAT);
  833. break;
  834. }
  835. }
  836. // TODO: make convertVertex/Fragment fill in rsc
  837. // TODO: update the below line to use rsc
  838. // Vertex textures
  839. if (rsc->isShaderProfileSupported("vs_3_0"))
  840. {
  841. // Run through all the texture formats looking for any which support
  842. // vertex texture fetching. Must have at least one!
  843. // All ATI Radeon up to X1n00 say they support vs_3_0,
  844. // but they support no texture formats for vertex texture fetch (cheaters!)
  845. if (checkVertexTextureFormats(renderWindow))
  846. {
  847. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  848. // always 4 vertex texture units in vs_3_0, and never shared
  849. rsc->setNumVertexTextureUnits(4);
  850. rsc->setVertexTextureUnitsShared(false);
  851. }
  852. }
  853. // Check alpha to coverage support
  854. // this varies per vendor! But at least SM3 is required
  855. if (rsc->isShaderProfileSupported("ps_3_0"))
  856. {
  857. // NVIDIA needs a separate check
  858. if (rsc->getVendor() == GPU_NVIDIA)
  859. {
  860. if (mpD3D->CheckDeviceFormat(
  861. D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE,
  862. (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK)
  863. {
  864. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  865. }
  866. }
  867. else if (rsc->getVendor() == GPU_ATI)
  868. {
  869. // There is no check on ATI, we have to assume SM3 == support
  870. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  871. }
  872. // no other cards have Dx9 hacks for alpha to coverage, as far as I know
  873. }
  874. if (mRealCapabilities == NULL)
  875. {
  876. mRealCapabilities = rsc;
  877. mRealCapabilities->addShaderProfile("hlsl");
  878. mRealCapabilities->addShaderProfile("cg");
  879. // if we are using custom capabilities, then
  880. // mCurrentCapabilities has already been loaded
  881. if(!mUseCustomCapabilities)
  882. mCurrentCapabilities = mRealCapabilities;
  883. initialiseFromRenderSystemCapabilities(mCurrentCapabilities, renderWindow);
  884. }
  885. return rsc;
  886. }
  887. //---------------------------------------------------------------------
  888. void D3D9RenderSystem::convertVertexShaderCaps(RenderSystemCapabilities* rsc) const
  889. {
  890. UINT16 major = 0xFF;
  891. UINT16 minor = 0xFF;
  892. D3DCAPS9 minVSCaps;
  893. // Find the device with the lowest vertex shader caps.
  894. for (unsigned int i=0; i < mDriverList->count(); ++i)
  895. {
  896. D3D9Driver* pCurDriver = mDriverList->item(i);
  897. const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps();
  898. UINT16 currMajor = static_cast<UINT16>((rkCurCaps.VertexShaderVersion & 0x0000FF00) >> 8);
  899. UINT16 currMinor = static_cast<UINT16>(rkCurCaps.VertexShaderVersion & 0x000000FF);
  900. if (currMajor < major)
  901. {
  902. major = currMajor;
  903. minor = currMinor;
  904. minVSCaps = rkCurCaps;
  905. }
  906. else if (currMajor == major && currMinor < minor)
  907. {
  908. minor = currMinor;
  909. minVSCaps = rkCurCaps;
  910. }
  911. }
  912. // In case we didn't found any vertex shader support
  913. // try the IDirect3DDevice9 caps instead of the IDirect3D9
  914. // software vertex processing is reported there
  915. if (major == 0 && minor == 0)
  916. {
  917. IDirect3DDevice9* lpD3DDevice9 = getActiveD3D9Device();
  918. D3DCAPS9 d3dDeviceCaps9;
  919. lpD3DDevice9->GetDeviceCaps(&d3dDeviceCaps9);
  920. major = static_cast<UINT16>((d3dDeviceCaps9.VertexShaderVersion & 0x0000FF00) >> 8);
  921. minor = static_cast<UINT16>(d3dDeviceCaps9.VertexShaderVersion & 0x000000FF);
  922. }
  923. bool vs2x = false;
  924. bool vs2a = false;
  925. // Special case detection for vs_2_x/a support
  926. if (major >= 2)
  927. {
  928. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  929. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  930. (minVSCaps.VS20Caps.NumTemps >= 12))
  931. {
  932. vs2x = true;
  933. }
  934. if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) &&
  935. (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) &&
  936. (minVSCaps.VS20Caps.NumTemps >= 13))
  937. {
  938. vs2a = true;
  939. }
  940. }
  941. // Populate max param count
  942. switch (major)
  943. {
  944. case 1:
  945. // No boolean params allowed
  946. rsc->setVertexProgramConstantBoolCount(0);
  947. // No integer params allowed
  948. rsc->setVertexProgramConstantIntCount(0);
  949. // float params, always 4D
  950. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  951. break;
  952. case 2:
  953. // 16 boolean params allowed
  954. rsc->setVertexProgramConstantBoolCount(16);
  955. // 16 integer params allowed, 4D
  956. rsc->setVertexProgramConstantIntCount(16);
  957. // float params, always 4D
  958. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  959. break;
  960. case 3:
  961. // 16 boolean params allowed
  962. rsc->setVertexProgramConstantBoolCount(16);
  963. // 16 integer params allowed, 4D
  964. rsc->setVertexProgramConstantIntCount(16);
  965. // float params, always 4D
  966. rsc->setVertexProgramConstantFloatCount(static_cast<UINT16>(minVSCaps.MaxVertexShaderConst));
  967. break;
  968. }
  969. // populate syntax codes in program manager (no breaks in this one so it falls through)
  970. switch(major)
  971. {
  972. case 3:
  973. rsc->addShaderProfile("vs_3_0");
  974. case 2:
  975. if (vs2x)
  976. rsc->addShaderProfile("vs_2_x");
  977. if (vs2a)
  978. rsc->addShaderProfile("vs_2_a");
  979. rsc->addShaderProfile("vs_2_0");
  980. case 1:
  981. rsc->addShaderProfile("vs_1_1");
  982. rsc->setCapability(RSC_VERTEX_PROGRAM);
  983. }
  984. }
  985. //---------------------------------------------------------------------
  986. void D3D9RenderSystem::convertPixelShaderCaps(RenderSystemCapabilities* rsc) const
  987. {
  988. UINT16 major = 0xFF;
  989. UINT16 minor = 0xFF;
  990. D3DCAPS9 minPSCaps;
  991. // Find the device with the lowest pixel shader caps.
  992. for (unsigned int i=0; i < mDriverList->count(); ++i)
  993. {
  994. D3D9Driver* pCurDriver = mDriverList->item(i);
  995. const D3DCAPS9& currCaps = pCurDriver->getD3D9DeviceCaps();
  996. UINT16 currMajor = static_cast<UINT16>((currCaps.PixelShaderVersion & 0x0000FF00) >> 8);
  997. UINT16 currMinor = static_cast<UINT16>(currCaps.PixelShaderVersion & 0x000000FF);
  998. if (currMajor < major)
  999. {
  1000. major = currMajor;
  1001. minor = currMinor;
  1002. minPSCaps = currCaps;
  1003. }
  1004. else if (currMajor == major && currMinor < minor)
  1005. {
  1006. minor = currMinor;
  1007. minPSCaps = currCaps;
  1008. }
  1009. }
  1010. bool ps2a = false;
  1011. bool ps2b = false;
  1012. bool ps2x = false;
  1013. // Special case detection for ps_2_x/a/b support
  1014. if (major >= 2)
  1015. {
  1016. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1017. (minPSCaps.PS20Caps.NumTemps >= 32))
  1018. {
  1019. ps2b = true;
  1020. }
  1021. if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) &&
  1022. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NODEPENDENTREADLIMIT) &&
  1023. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_ARBITRARYSWIZZLE) &&
  1024. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) &&
  1025. (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_PREDICATION) &&
  1026. (minPSCaps.PS20Caps.NumTemps >= 22))
  1027. {
  1028. ps2a = true;
  1029. }
  1030. // Does this enough?
  1031. if (ps2a || ps2b)
  1032. {
  1033. ps2x = true;
  1034. }
  1035. }
  1036. switch (major)
  1037. {
  1038. case 1:
  1039. // no boolean params allowed
  1040. rsc->setFragmentProgramConstantBoolCount(0);
  1041. // no integer params allowed
  1042. rsc->setFragmentProgramConstantIntCount(0);
  1043. // float params, always 4D
  1044. // NB in ps_1_x these are actually stored as fixed point values,
  1045. // but they are entered as floats
  1046. rsc->setFragmentProgramConstantFloatCount(8);
  1047. break;
  1048. case 2:
  1049. // 16 boolean params allowed
  1050. rsc->setFragmentProgramConstantBoolCount(16);
  1051. // 16 integer params allowed, 4D
  1052. rsc->setFragmentProgramConstantIntCount(16);
  1053. // float params, always 4D
  1054. rsc->setFragmentProgramConstantFloatCount(32);
  1055. break;
  1056. case 3:
  1057. // 16 boolean params allowed
  1058. rsc->setFragmentProgramConstantBoolCount(16);
  1059. // 16 integer params allowed, 4D
  1060. rsc->setFragmentProgramConstantIntCount(16);
  1061. // float params, always 4D
  1062. rsc->setFragmentProgramConstantFloatCount(224);
  1063. break;
  1064. }
  1065. // populate syntax codes in program manager (no breaks in this one so it falls through)
  1066. switch(major)
  1067. {
  1068. case 3:
  1069. if (minor > 0)
  1070. rsc->addShaderProfile("ps_3_x");
  1071. rsc->addShaderProfile("ps_3_0");
  1072. case 2:
  1073. if (ps2x)
  1074. rsc->addShaderProfile("ps_2_x");
  1075. if (ps2a)
  1076. rsc->addShaderProfile("ps_2_a");
  1077. if (ps2b)
  1078. rsc->addShaderProfile("ps_2_b");
  1079. rsc->addShaderProfile("ps_2_0");
  1080. case 1:
  1081. if (major > 1 || minor >= 4)
  1082. rsc->addShaderProfile("ps_1_4");
  1083. if (major > 1 || minor >= 3)
  1084. rsc->addShaderProfile("ps_1_3");
  1085. if (major > 1 || minor >= 2)
  1086. rsc->addShaderProfile("ps_1_2");
  1087. rsc->addShaderProfile("ps_1_1");
  1088. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  1089. }
  1090. }
  1091. //-----------------------------------------------------------------------
  1092. bool D3D9RenderSystem::checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const
  1093. {
  1094. bool anySupported = false;
  1095. IDirect3DSurface9* bbSurf;
  1096. renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf);
  1097. D3DSURFACE_DESC bbSurfDesc;
  1098. bbSurf->GetDesc(&bbSurfDesc);
  1099. for (UINT32 ipf = static_cast<UINT32>(PF_L8); ipf < static_cast<UINT32>(PF_COUNT); ++ipf)
  1100. {
  1101. PixelFormat pf = (PixelFormat)ipf;
  1102. D3DFORMAT fmt =
  1103. D3D9Mappings::_getPF(D3D9Mappings::_getClosestSupportedPF(pf));
  1104. if (SUCCEEDED(mpD3D->CheckDeviceFormat(
  1105. mActiveD3DDriver->getAdapterNumber(), D3DDEVTYPE_HAL, bbSurfDesc.Format,
  1106. D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, fmt)))
  1107. {
  1108. // cool, at least one supported
  1109. anySupported = true;
  1110. }
  1111. }
  1112. return anySupported;
  1113. }
  1114. //-----------------------------------------------------------------------
  1115. void D3D9RenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary)
  1116. {
  1117. if (caps->getRenderSystemName() != getName())
  1118. {
  1119. CM_EXCEPT(InvalidParametersException,
  1120. "Trying to initialize D3D9RenderSystem from RenderSystemCapabilities that do not support Direct3D9");
  1121. }
  1122. if (caps->isShaderProfileSupported("hlsl"))
  1123. HighLevelGpuProgramManager::instance().addFactory(mHLSLProgramFactory);
  1124. if (caps->isShaderProfileSupported("cg"))
  1125. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  1126. }
  1127. //-----------------------------------------------------------------------
  1128. bool D3D9RenderSystem::_checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage)
  1129. {
  1130. // Gets D3D format
  1131. D3DFORMAT d3dPF = D3D9Mappings::_getPF(format);
  1132. if (d3dPF == D3DFMT_UNKNOWN)
  1133. return false;
  1134. for (UINT32 i = 0; i < mDeviceManager->getDeviceCount(); ++i)
  1135. {
  1136. D3D9Device* currDevice = mDeviceManager->getDevice(i);
  1137. D3D9RenderWindow* currDevicePrimaryWindow = currDevice->getPrimaryWindow();
  1138. IDirect3DSurface9* pSurface = currDevicePrimaryWindow->getRenderSurface();
  1139. D3DSURFACE_DESC srfDesc;
  1140. // Get surface desc
  1141. if (FAILED(pSurface->GetDesc(&srfDesc)))
  1142. return false;
  1143. // Calculate usage
  1144. DWORD d3dusage = D3DUSAGE_QUERY_FILTER;
  1145. if (usage & TU_RENDERTARGET)
  1146. d3dusage |= D3DUSAGE_RENDERTARGET;
  1147. if (usage & TU_DYNAMIC)
  1148. d3dusage |= D3DUSAGE_DYNAMIC;
  1149. // Detect resource type
  1150. D3DRESOURCETYPE rtype;
  1151. switch(ttype)
  1152. {
  1153. case TEX_TYPE_1D:
  1154. case TEX_TYPE_2D:
  1155. rtype = D3DRTYPE_TEXTURE;
  1156. break;
  1157. case TEX_TYPE_3D:
  1158. rtype = D3DRTYPE_VOLUMETEXTURE;
  1159. break;
  1160. case TEX_TYPE_CUBE_MAP:
  1161. rtype = D3DRTYPE_CUBETEXTURE;
  1162. break;
  1163. default:
  1164. return false;
  1165. }
  1166. HRESULT hr = mpD3D->CheckDeviceFormat(
  1167. currDevice->getAdapterNumber(),
  1168. currDevice->getDeviceType(),
  1169. srfDesc.Format,
  1170. d3dusage,
  1171. rtype,
  1172. d3dPF);
  1173. if (FAILED(hr))
  1174. return false;
  1175. }
  1176. return true;
  1177. }
  1178. //-----------------------------------------------------------------------
  1179. MultiRenderTarget * D3D9RenderSystem::createMultiRenderTarget(const String & name)
  1180. {
  1181. MultiRenderTarget *retval;
  1182. retval = new D3D9MultiRenderTarget(name);
  1183. attachRenderTarget(*retval);
  1184. return retval;
  1185. }
  1186. //---------------------------------------------------------------------
  1187. void D3D9RenderSystem::destroyRenderTarget(const String& name)
  1188. {
  1189. D3D9RenderWindow* renderWindow = NULL;
  1190. // Check render windows
  1191. D3D9RenderWindowList::iterator sw;
  1192. for (sw = mRenderWindows.begin(); sw != mRenderWindows.end(); ++sw)
  1193. {
  1194. if ((*sw)->getName() == name)
  1195. {
  1196. renderWindow = (*sw);
  1197. mRenderWindows.erase(sw);
  1198. break;
  1199. }
  1200. }
  1201. // Do the real removal
  1202. RenderSystem::destroyRenderTarget(name);
  1203. }
  1204. //---------------------------------------------------------------------
  1205. String D3D9RenderSystem::getErrorDescription( long errorNumber ) const
  1206. {
  1207. const String errMsg = DXGetErrorDescription( errorNumber );
  1208. return errMsg;
  1209. }
  1210. //---------------------------------------------------------------------
  1211. VertexElementType D3D9RenderSystem::getColourVertexElementType() const
  1212. {
  1213. return VET_COLOUR_ARGB;
  1214. }
  1215. //---------------------------------------------------------------------
  1216. void D3D9RenderSystem::_convertProjectionMatrix(const Matrix4& matrix,
  1217. Matrix4& dest, bool forGpuProgram)
  1218. {
  1219. dest = matrix;
  1220. // Convert depth range from [-1,+1] to [0,1]
  1221. dest[2][0] = (dest[2][0] + dest[3][0]) / 2;
  1222. dest[2][1] = (dest[2][1] + dest[3][1]) / 2;
  1223. dest[2][2] = (dest[2][2] + dest[3][2]) / 2;
  1224. dest[2][3] = (dest[2][3] + dest[3][3]) / 2;
  1225. if (!forGpuProgram)
  1226. {
  1227. // Convert right-handed to left-handed
  1228. dest[0][2] = -dest[0][2];
  1229. dest[1][2] = -dest[1][2];
  1230. dest[2][2] = -dest[2][2];
  1231. dest[3][2] = -dest[3][2];
  1232. }
  1233. }
  1234. //---------------------------------------------------------------------
  1235. void D3D9RenderSystem::_makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane,
  1236. float farPlane, Matrix4& dest, bool forGpuProgram)
  1237. {
  1238. Radian theta ( fovy * 0.5 );
  1239. float h = 1 / Math::Tan(theta);
  1240. float w = h / aspect;
  1241. float q, qn;
  1242. if (farPlane == 0)
  1243. {
  1244. q = 1 - Frustum::INFINITE_FAR_PLANE_ADJUST;
  1245. qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 1);
  1246. }
  1247. else
  1248. {
  1249. q = farPlane / ( farPlane - nearPlane );
  1250. qn = -q * nearPlane;
  1251. }
  1252. dest = Matrix4::ZERO;
  1253. dest[0][0] = w;
  1254. dest[1][1] = h;
  1255. if (forGpuProgram)
  1256. {
  1257. dest[2][2] = -q;
  1258. dest[3][2] = -1.0f;
  1259. }
  1260. else
  1261. {
  1262. dest[2][2] = q;
  1263. dest[3][2] = 1.0f;
  1264. }
  1265. dest[2][3] = qn;
  1266. }
  1267. //---------------------------------------------------------------------
  1268. void D3D9RenderSystem::_makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane,
  1269. Matrix4& dest, bool forGpuProgram )
  1270. {
  1271. Radian thetaY (fovy / 2.0f);
  1272. float tanThetaY = Math::Tan(thetaY);
  1273. //float thetaX = thetaY * aspect;
  1274. float tanThetaX = tanThetaY * aspect; //Math::Tan(thetaX);
  1275. float half_w = tanThetaX * nearPlane;
  1276. float half_h = tanThetaY * nearPlane;
  1277. float iw = static_cast<float>(1.0 / half_w);
  1278. float ih = static_cast<float>(1.0 / half_h);
  1279. float q;
  1280. if (farPlane == 0)
  1281. {
  1282. q = 0;
  1283. }
  1284. else
  1285. {
  1286. q = static_cast<float>(1.0 / (farPlane - nearPlane));
  1287. }
  1288. dest = Matrix4::ZERO;
  1289. dest[0][0] = iw;
  1290. dest[1][1] = ih;
  1291. dest[2][2] = q;
  1292. dest[2][3] = -nearPlane / (farPlane - nearPlane);
  1293. dest[3][3] = 1;
  1294. if (forGpuProgram)
  1295. {
  1296. dest[2][2] = -dest[2][2];
  1297. }
  1298. }
  1299. //---------------------------------------------------------------------
  1300. void D3D9RenderSystem::setAmbientLight( float r, float g, float b )
  1301. {
  1302. HRESULT hr = __SetRenderState( D3DRS_AMBIENT, D3DCOLOR_COLORVALUE( r, g, b, 1.0f ) );
  1303. if( FAILED( hr ) )
  1304. CM_EXCEPT(RenderingAPIException, "Failed to set render stat D3DRS_AMBIENT");
  1305. }
  1306. //---------------------------------------------------------------------
  1307. void D3D9RenderSystem::setShadingType( ShadeOptions so )
  1308. {
  1309. HRESULT hr = __SetRenderState( D3DRS_SHADEMODE, D3D9Mappings::get(so) );
  1310. if( FAILED( hr ) )
  1311. CM_EXCEPT(RenderingAPIException, "Failed to set render stat D3DRS_SHADEMODE");
  1312. }
  1313. //---------------------------------------------------------------------
  1314. void D3D9RenderSystem::setLightingEnabled( bool enabled )
  1315. {
  1316. HRESULT hr;
  1317. if( FAILED( hr = __SetRenderState( D3DRS_LIGHTING, enabled ) ) )
  1318. CM_EXCEPT(RenderingAPIException, "Failed to set render state D3DRS_LIGHTING");
  1319. }
  1320. //---------------------------------------------------------------------
  1321. void D3D9RenderSystem::_setViewMatrix( const Matrix4 &m )
  1322. {
  1323. // save latest view matrix
  1324. mViewMatrix = m;
  1325. mViewMatrix[2][0] = -mViewMatrix[2][0];
  1326. mViewMatrix[2][1] = -mViewMatrix[2][1];
  1327. mViewMatrix[2][2] = -mViewMatrix[2][2];
  1328. mViewMatrix[2][3] = -mViewMatrix[2][3];
  1329. mDxViewMat = D3D9Mappings::makeD3DXMatrix( mViewMatrix );
  1330. HRESULT hr;
  1331. if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_VIEW, &mDxViewMat ) ) )
  1332. CM_EXCEPT(RenderingAPIException, "Cannot set D3D9 view matrix");
  1333. // also mark clip planes dirty
  1334. if (!mClipPlanes.empty())
  1335. mClipPlanesDirty = true;
  1336. }
  1337. //---------------------------------------------------------------------
  1338. void D3D9RenderSystem::_setProjectionMatrix( const Matrix4 &m )
  1339. {
  1340. // save latest matrix
  1341. mDxProjMat = D3D9Mappings::makeD3DXMatrix( m );
  1342. if( mActiveRenderTarget->requiresTextureFlipping() )
  1343. {
  1344. // Invert transformed y
  1345. mDxProjMat._12 = - mDxProjMat._12;
  1346. mDxProjMat._22 = - mDxProjMat._22;
  1347. mDxProjMat._32 = - mDxProjMat._32;
  1348. mDxProjMat._42 = - mDxProjMat._42;
  1349. }
  1350. HRESULT hr;
  1351. if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_PROJECTION, &mDxProjMat ) ) )
  1352. CM_EXCEPT(RenderingAPIException, "Cannot set D3D9 projection matrix");
  1353. // also mark clip planes dirty
  1354. if (!mClipPlanes.empty())
  1355. mClipPlanesDirty = true;
  1356. }
  1357. //---------------------------------------------------------------------
  1358. void D3D9RenderSystem::_setWorldMatrix( const Matrix4 &m )
  1359. {
  1360. // save latest matrix
  1361. mDxWorldMat = D3D9Mappings::makeD3DXMatrix( m );
  1362. HRESULT hr;
  1363. if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_WORLD, &mDxWorldMat ) ) )
  1364. CM_EXCEPT(RenderingAPIException, "Cannot set D3D9 world matrix");
  1365. }
  1366. //---------------------------------------------------------------------
  1367. void D3D9RenderSystem::_setSurfaceParams( const Color &ambient, const Color &diffuse,
  1368. const Color &specular, const Color &emissive, float shininess,
  1369. TrackVertexColourType tracking )
  1370. {
  1371. D3DMATERIAL9 material;
  1372. material.Diffuse = D3DXCOLOR( diffuse.r, diffuse.g, diffuse.b, diffuse.a );
  1373. material.Ambient = D3DXCOLOR( ambient.r, ambient.g, ambient.b, ambient.a );
  1374. material.Specular = D3DXCOLOR( specular.r, specular.g, specular.b, specular.a );
  1375. material.Emissive = D3DXCOLOR( emissive.r, emissive.g, emissive.b, emissive.a );
  1376. material.Power = shininess;
  1377. HRESULT hr = getActiveD3D9Device()->SetMaterial( &material );
  1378. if( FAILED( hr ) )
  1379. CM_EXCEPT(RenderingAPIException, "Error setting D3D material");
  1380. if(tracking != TVC_NONE)
  1381. {
  1382. __SetRenderState(D3DRS_COLORVERTEX, TRUE);
  1383. __SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, (tracking&TVC_AMBIENT)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1384. __SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, (tracking&TVC_DIFFUSE)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1385. __SetRenderState(D3DRS_SPECULARMATERIALSOURCE, (tracking&TVC_SPECULAR)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1386. __SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, (tracking&TVC_EMISSIVE)?D3DMCS_COLOR1:D3DMCS_MATERIAL);
  1387. }
  1388. else
  1389. {
  1390. __SetRenderState(D3DRS_COLORVERTEX, FALSE);
  1391. }
  1392. }
  1393. //---------------------------------------------------------------------
  1394. void D3D9RenderSystem::_setPointParameters(float size,
  1395. bool attenuationEnabled, float constant, float linear, float quadratic,
  1396. float minSize, float maxSize)
  1397. {
  1398. if(attenuationEnabled)
  1399. {
  1400. // scaling required
  1401. __SetRenderState(D3DRS_POINTSCALEENABLE, TRUE);
  1402. __SetFloatRenderState(D3DRS_POINTSCALE_A, constant);
  1403. __SetFloatRenderState(D3DRS_POINTSCALE_B, linear);
  1404. __SetFloatRenderState(D3DRS_POINTSCALE_C, quadratic);
  1405. }
  1406. else
  1407. {
  1408. // no scaling required
  1409. __SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);
  1410. }
  1411. __SetFloatRenderState(D3DRS_POINTSIZE, size);
  1412. __SetFloatRenderState(D3DRS_POINTSIZE_MIN, minSize);
  1413. if (maxSize == 0.0f)
  1414. maxSize = mCurrentCapabilities->getMaxPointSize();
  1415. __SetFloatRenderState(D3DRS_POINTSIZE_MAX, maxSize);
  1416. }
  1417. //---------------------------------------------------------------------
  1418. void D3D9RenderSystem::_setPointSpritesEnabled(bool enabled)
  1419. {
  1420. if (enabled)
  1421. {
  1422. __SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
  1423. }
  1424. else
  1425. {
  1426. __SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
  1427. }
  1428. }
  1429. //---------------------------------------------------------------------
  1430. void D3D9RenderSystem::_setTexture( size_t stage, bool enabled, const TexturePtr& tex )
  1431. {
  1432. HRESULT hr;
  1433. D3D9TexturePtr dt = std::static_pointer_cast<D3D9Texture>(tex);
  1434. if (enabled && (dt != nullptr))
  1435. {
  1436. IDirect3DBaseTexture9 *pTex = dt->getTexture();
  1437. if (mTexStageDesc[stage].pTex != pTex)
  1438. {
  1439. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(stage), pTex);
  1440. if( hr != S_OK )
  1441. {
  1442. String str = "Unable to set texture in D3D9";
  1443. CM_EXCEPT(RenderingAPIException, str);
  1444. }
  1445. // set stage desc.
  1446. mTexStageDesc[stage].pTex = pTex;
  1447. mTexStageDesc[stage].texType = D3D9Mappings::get(dt->getTextureType());
  1448. // Set gamma now too
  1449. if (dt->isHardwareGammaReadToBeUsed())
  1450. {
  1451. __SetSamplerState(static_cast<DWORD>(stage), D3DSAMP_SRGBTEXTURE, TRUE);
  1452. }
  1453. else
  1454. {
  1455. __SetSamplerState(static_cast<DWORD>(stage), D3DSAMP_SRGBTEXTURE, FALSE);
  1456. }
  1457. }
  1458. }
  1459. else
  1460. {
  1461. if (mTexStageDesc[stage].pTex != 0)
  1462. {
  1463. hr = getActiveD3D9Device()->SetTexture(static_cast<DWORD>(stage), 0);
  1464. if( hr != S_OK )
  1465. {
  1466. String str = "Unable to disable texture '" + toString(stage) + "' in D3D9";
  1467. CM_EXCEPT(RenderingAPIException, str);
  1468. }
  1469. }
  1470. hr = __SetTextureStageState(static_cast<DWORD>(stage), D3DTSS_COLOROP, D3DTOP_DISABLE);
  1471. if( hr != S_OK )
  1472. {
  1473. String str = "Unable to disable texture '" + toString(stage) + "' in D3D9";
  1474. CM_EXCEPT(RenderingAPIException, str);
  1475. }
  1476. // set stage desc. to defaults
  1477. mTexStageDesc[stage].pTex = 0;
  1478. mTexStageDesc[stage].autoTexCoordType = TEXCALC_NONE;
  1479. mTexStageDesc[stage].coordIndex = 0;
  1480. mTexStageDesc[stage].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL;
  1481. }
  1482. }
  1483. //---------------------------------------------------------------------
  1484. void D3D9RenderSystem::_setVertexTexture(size_t stage, const TexturePtr& tex)
  1485. {
  1486. if (tex == nullptr)
  1487. {
  1488. if (mTexStageDesc[stage].pVertexTex != 0)
  1489. {
  1490. HRESULT hr = getActiveD3D9Device()->SetTexture(D3DVERTEXTEXTURESAMPLER0 + static_cast<DWORD>(stage), 0);
  1491. if( hr != S_OK )
  1492. {
  1493. String str = "Unable to disable vertex texture '"
  1494. + toString(stage) + "' in D3D9";
  1495. CM_EXCEPT(RenderingAPIException, str);
  1496. }
  1497. }
  1498. // set stage desc. to defaults
  1499. mTexStageDesc[stage].pVertexTex = 0;
  1500. }
  1501. else
  1502. {
  1503. D3D9TexturePtr dt = std::static_pointer_cast<D3D9Texture>(tex);
  1504. IDirect3DBaseTexture9 *pTex = dt->getTexture();
  1505. if (mTexStageDesc[stage].pVertexTex != pTex)
  1506. {
  1507. HRESULT hr = getActiveD3D9Device()->SetTexture(D3DVERTEXTEXTURESAMPLER0 + static_cast<DWORD>(stage), pTex);
  1508. if( hr != S_OK )
  1509. {
  1510. String str = "Unable to set vertex texture in D3D9";
  1511. CM_EXCEPT(RenderingAPIException, str);
  1512. }
  1513. // set stage desc.
  1514. mTexStageDesc[stage].pVertexTex = pTex;
  1515. }
  1516. }
  1517. }
  1518. //---------------------------------------------------------------------
  1519. void D3D9RenderSystem::_disableTextureUnit(size_t texUnit)
  1520. {
  1521. RenderSystem::_disableTextureUnit(texUnit);
  1522. // also disable vertex texture unit
  1523. static TexturePtr nullPtr;
  1524. _setVertexTexture(texUnit, nullPtr);
  1525. }
  1526. //---------------------------------------------------------------------
  1527. void D3D9RenderSystem::_setTextureCoordSet( size_t stage, size_t index )
  1528. {
  1529. // if vertex shader is being used, stage and index must match
  1530. if (mVertexProgramBound)
  1531. index = stage;
  1532. HRESULT hr;
  1533. // Record settings
  1534. mTexStageDesc[stage].coordIndex = index;
  1535. hr = __SetTextureStageState( static_cast<DWORD>(stage), D3DTSS_TEXCOORDINDEX, D3D9Mappings::get(mTexStageDesc[stage].autoTexCoordType, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) | index );
  1536. if( FAILED( hr ) )
  1537. CM_EXCEPT(RenderingAPIException, "Unable to set texture coord. set index");
  1538. }
  1539. //---------------------------------------------------------------------
  1540. void D3D9RenderSystem::_setTextureCoordCalculation( size_t stage, TexCoordCalcMethod m,
  1541. const Frustum* frustum)
  1542. {
  1543. HRESULT hr;
  1544. // record the stage state
  1545. mTexStageDesc[stage].autoTexCoordType = m;
  1546. mTexStageDesc[stage].frustum = frustum;
  1547. hr = __SetTextureStageState( static_cast<DWORD>(stage), D3DTSS_TEXCOORDINDEX, D3D9Mappings::get(m, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) | mTexStageDesc[stage].coordIndex );
  1548. if(FAILED(hr))
  1549. CM_EXCEPT(RenderingAPIException, "Unable to set texture auto tex.coord. generation mode");
  1550. }
  1551. //---------------------------------------------------------------------
  1552. void D3D9RenderSystem::_setTextureMipmapBias(size_t unit, float bias)
  1553. {
  1554. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  1555. {
  1556. // ugh - have to pass float data through DWORD with no conversion
  1557. HRESULT hr = __SetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MIPMAPLODBIAS,
  1558. *(DWORD*)&bias);
  1559. if(FAILED(hr))
  1560. CM_EXCEPT(RenderingAPIException, "Unable to set texture mipmap bias");
  1561. }
  1562. }
  1563. //---------------------------------------------------------------------
  1564. void D3D9RenderSystem::_setTextureMatrix( size_t stage, const Matrix4& xForm )
  1565. {
  1566. HRESULT hr;
  1567. D3DXMATRIX d3dMat; // the matrix we'll maybe apply
  1568. Matrix4 newMat = xForm; // the matrix we'll apply after conv. to D3D format
  1569. // Cache texcoord calc method to register
  1570. TexCoordCalcMethod autoTexCoordType = mTexStageDesc[stage].autoTexCoordType;
  1571. // if a vertex program is bound, we mustn't set texture transforms
  1572. if (mVertexProgramBound)
  1573. {
  1574. hr = __SetTextureStageState( static_cast<DWORD>(stage), D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
  1575. if( FAILED( hr ) )
  1576. CM_EXCEPT(RenderingAPIException, "Unable to disable texture coordinate transform");
  1577. return;
  1578. }
  1579. if (autoTexCoordType == TEXCALC_ENVIRONMENT_MAP)
  1580. {
  1581. if (mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().VertexProcessingCaps & D3DVTXPCAPS_TEXGEN_SPHEREMAP)
  1582. {
  1583. /** Invert the texture for the spheremap */
  1584. Matrix4 ogreMatEnvMap = Matrix4::IDENTITY;
  1585. // set env_map values
  1586. ogreMatEnvMap[1][1] = -1.0f;
  1587. // concatenate with the xForm
  1588. newMat = newMat.concatenate(ogreMatEnvMap);
  1589. }
  1590. else
  1591. {
  1592. /* If envmap is applied, but device doesn't support spheremap,
  1593. then we have to use texture transform to make the camera space normal
  1594. reference the envmap properly. This isn't exactly the same as spheremap
  1595. (it looks nasty on flat areas because the camera space normals are the same)
  1596. but it's the best approximation we have in the absence of a proper spheremap */
  1597. // concatenate with the xForm
  1598. newMat = newMat.concatenate(Matrix4::CLIPSPACE2DTOIMAGESPACE);
  1599. }
  1600. }
  1601. // If this is a cubic reflection, we need to modify using the view matrix
  1602. if (autoTexCoordType == TEXCALC_ENVIRONMENT_MAP_REFLECTION)
  1603. {
  1604. // Get transposed 3x3
  1605. // We want to transpose since that will invert an orthonormal matrix ie rotation
  1606. Matrix4 ogreViewTransposed;
  1607. ogreViewTransposed[0][0] = mViewMatrix[0][0];
  1608. ogreViewTransposed[0][1] = mViewMatrix[1][0];
  1609. ogreViewTransposed[0][2] = mViewMatrix[2][0];
  1610. ogreViewTransposed[0][3] = 0.0f;
  1611. ogreViewTransposed[1][0] = mViewMatrix[0][1];
  1612. ogreViewTransposed[1][1] = mViewMatrix[1][1];
  1613. ogreViewTransposed[1][2] = mViewMatrix[2][1];
  1614. ogreViewTransposed[1][3] = 0.0f;
  1615. ogreViewTransposed[2][0] = mViewMatrix[0][2];
  1616. ogreViewTransposed[2][1] = mViewMatrix[1][2];
  1617. ogreViewTransposed[2][2] = mViewMatrix[2][2];
  1618. ogreViewTransposed[2][3] = 0.0f;
  1619. ogreViewTransposed[3][0] = 0.0f;
  1620. ogreViewTransposed[3][1] = 0.0f;
  1621. ogreViewTransposed[3][2] = 0.0f;
  1622. ogreViewTransposed[3][3] = 1.0f;
  1623. newMat = newMat.concatenate(ogreViewTransposed);
  1624. }
  1625. if (autoTexCoordType == TEXCALC_PROJECTIVE_TEXTURE)
  1626. {
  1627. // Derive camera space to projector space transform
  1628. // To do this, we need to undo the camera view matrix, then
  1629. // apply the projector view & projection matrices
  1630. newMat = mViewMatrix.inverse();
  1631. if(mTexProjRelative)
  1632. {
  1633. Matrix4 viewMatrix;
  1634. mTexStageDesc[stage].frustum->calcViewMatrixRelative(mTexProjRelativeOrigin, viewMatrix);
  1635. newMat = viewMatrix * newMat;
  1636. }
  1637. else
  1638. {
  1639. newMat = mTexStageDesc[stage].frustum->getViewMatrix() * newMat;
  1640. }
  1641. newMat = mTexStageDesc[stage].frustum->getProjectionMatrix() * newMat;
  1642. newMat = Matrix4::CLIPSPACE2DTOIMAGESPACE * newMat;
  1643. newMat = xForm * newMat;
  1644. }
  1645. // need this if texture is a cube map, to invert D3D's z coord
  1646. if (autoTexCoordType != TEXCALC_NONE &&
  1647. autoTexCoordType != TEXCALC_PROJECTIVE_TEXTURE)
  1648. {
  1649. newMat[2][0] = -newMat[2][0];
  1650. newMat[2][1] = -newMat[2][1];
  1651. newMat[2][2] = -newMat[2][2];
  1652. newMat[2][3] = -newMat[2][3];
  1653. }
  1654. // convert our matrix to D3D format
  1655. d3dMat = D3D9Mappings::makeD3DXMatrix(newMat);
  1656. // set the matrix if it's not the identity
  1657. if (!D3DXMatrixIsIdentity(&d3dMat))
  1658. {
  1659. /* It's seems D3D automatically add a texture coordinate with value 1,
  1660. and fill up the remaining texture coordinates with 0 for the input
  1661. texture coordinates before pass to texture coordinate transformation.
  1662. NOTE: It's difference with D3DDECLTYPE enumerated type expand in
  1663. DirectX SDK documentation!
  1664. So we should prepare the texcoord transform, make the transformation
  1665. just like standardized vector expand, thus, fill w with value 1 and
  1666. others with 0.
  1667. */
  1668. if (autoTexCoordType == TEXCALC_NONE)
  1669. {
  1670. /* FIXME: The actually input texture coordinate dimensions should
  1671. be determine by texture coordinate vertex element. Now, just trust
  1672. user supplied texture type matchs texture coordinate vertex element.
  1673. */
  1674. if (mTexStageDesc[stage].texType == D3D9Mappings::D3D_TEX_TYPE_NORMAL)
  1675. {
  1676. /* It's 2D input texture coordinate:
  1677. texcoord in vertex buffer D3D expanded to We are adjusted to
  1678. --> -->
  1679. (u, v) (u, v, 1, 0) (u, v, 0, 1)
  1680. */
  1681. std::swap(d3dMat._31, d3dMat._41);
  1682. std::swap(d3dMat._32, d3dMat._42);
  1683. std::swap(d3dMat._33, d3dMat._43);
  1684. std::swap(d3dMat._34, d3dMat._44);
  1685. }
  1686. }
  1687. else
  1688. {
  1689. // All texgen generate 3D input texture coordinates.
  1690. }
  1691. // tell D3D the dimension of tex. coord.
  1692. int texCoordDim = D3DTTFF_COUNT2;
  1693. if (mTexStageDesc[stage].autoTexCoordType == TEXCALC_PROJECTIVE_TEXTURE)
  1694. {
  1695. /* We want texcoords (u, v, w, q) always get divided by q, but D3D
  1696. projected texcoords is divided by the last element (in the case of
  1697. 2D texcoord, is w). So we tweak the transform matrix, transform the
  1698. texcoords with w and q swapped: (u, v, q, w), and then D3D will
  1699. divide u, v by q. The w and q just ignored as it wasn't used by
  1700. rasterizer.
  1701. */
  1702. switch (mTexStageDesc[stage].texType)
  1703. {
  1704. case D3D9Mappings::D3D_TEX_TYPE_NORMAL:
  1705. std::swap(d3dMat._13, d3dMat._14);
  1706. std::swap(d3dMat._23, d3dMat._24);
  1707. std::swap(d3dMat._33, d3dMat._34);
  1708. std::swap(d3dMat._43, d3dMat._44);
  1709. texCoordDim = D3DTTFF_PROJECTED | D3DTTFF_COUNT3;
  1710. break;
  1711. case D3D9Mappings::D3D_TEX_TYPE_CUBE:
  1712. case D3D9Mappings::D3D_TEX_TYPE_VOLUME:
  1713. // Yes, we support 3D projective texture.
  1714. texCoordDim = D3DTTFF_PROJECTED | D3DTTFF_COUNT4;
  1715. break;
  1716. }
  1717. }
  1718. else
  1719. {
  1720. switch (mTexStageDesc[stage].texType)
  1721. {
  1722. case D3D9Mappings::D3D_TEX_TYPE_NORMAL:
  1723. texCoordDim = D3DTTFF_COUNT2;
  1724. break;
  1725. case D3D9Mappings::D3D_TEX_TYPE_CUBE:
  1726. case D3D9Mappings::D3D_TEX_TYPE_VOLUME:
  1727. texCoordDim = D3DTTFF_COUNT3;
  1728. break;
  1729. }
  1730. }
  1731. hr = __SetTextureStageState( static_cast<DWORD>(stage), D3DTSS_TEXTURETRANSFORMFLAGS, texCoordDim );
  1732. if (FAILED(hr))
  1733. CM_EXCEPT(RenderingAPIException, "Unable to set texture coord. dimension");
  1734. hr = getActiveD3D9Device()->SetTransform( (D3DTRANSFORMSTATETYPE)(D3DTS_TEXTURE0 + stage), &d3dMat );
  1735. if (FAILED(hr))
  1736. CM_EXCEPT(RenderingAPIException, "Unable to set texture matrix");
  1737. }
  1738. else
  1739. {
  1740. // disable all of this
  1741. hr = __SetTextureStageState( static_cast<DWORD>(stage), D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );
  1742. if( FAILED( hr ) )
  1743. CM_EXCEPT(RenderingAPIException, "Unable to disable texture coordinate transform");
  1744. // Needless to sets texture transform here, it's never used at all
  1745. }
  1746. }
  1747. //---------------------------------------------------------------------
  1748. void D3D9RenderSystem::_setTextureAddressingMode( size_t stage,
  1749. const TextureState::UVWAddressingMode& uvw )
  1750. {
  1751. HRESULT hr;
  1752. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSU, D3D9Mappings::get(uvw.u, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  1753. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for U" );
  1754. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSV, D3D9Mappings::get(uvw.v, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  1755. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for V");
  1756. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_ADDRESSW, D3D9Mappings::get(uvw.w, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ) ) )
  1757. CM_EXCEPT(RenderingAPIException, "Failed to set texture addressing mode for W");
  1758. }
  1759. //-----------------------------------------------------------------------------
  1760. void D3D9RenderSystem::_setTextureBorderColour(size_t stage,
  1761. const Color& colour)
  1762. {
  1763. HRESULT hr;
  1764. if( FAILED( hr = __SetSamplerState( static_cast<DWORD>(stage), D3DSAMP_BORDERCOLOR, colour.getAsARGB()) ) )
  1765. CM_EXCEPT(RenderingAPIException, "Failed to set texture border colour");
  1766. }
  1767. //---------------------------------------------------------------------
  1768. void D3D9RenderSystem::_setSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op )
  1769. {
  1770. HRESULT hr;
  1771. if( sourceFactor == SBF_ONE && destFactor == SBF_ZERO)
  1772. {
  1773. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  1774. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1775. }
  1776. else
  1777. {
  1778. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  1779. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1780. if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE)))
  1781. CM_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  1782. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  1783. CM_EXCEPT(RenderingAPIException, "Failed to set source blend");
  1784. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  1785. CM_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  1786. }
  1787. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  1788. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  1789. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(op))))
  1790. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  1791. }
  1792. //---------------------------------------------------------------------
  1793. void D3D9RenderSystem::_setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha,
  1794. SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp )
  1795. {
  1796. HRESULT hr;
  1797. if( sourceFactor == SBF_ONE && destFactor == SBF_ZERO &&
  1798. sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO)
  1799. {
  1800. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE)))
  1801. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1802. }
  1803. else
  1804. {
  1805. if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE)))
  1806. CM_EXCEPT(RenderingAPIException, "Failed to set alpha blending option");
  1807. if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE)))
  1808. CM_EXCEPT(RenderingAPIException, "Failed to set separate alpha blending option");
  1809. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(sourceFactor) ) ) )
  1810. CM_EXCEPT(RenderingAPIException, "Failed to set source blend");
  1811. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(destFactor) ) ) )
  1812. CM_EXCEPT(RenderingAPIException, "Failed to set destination blend");
  1813. if( FAILED( hr = __SetRenderState( D3DRS_SRCBLENDALPHA, D3D9Mappings::get(sourceFactorAlpha) ) ) )
  1814. CM_EXCEPT(RenderingAPIException, "Failed to set alpha source blend");
  1815. if( FAILED( hr = __SetRenderState( D3DRS_DESTBLENDALPHA, D3D9Mappings::get(destFactorAlpha) ) ) )
  1816. CM_EXCEPT(RenderingAPIException, "Failed to set alpha destination blend");
  1817. }
  1818. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(op))))
  1819. CM_EXCEPT(RenderingAPIException, "Failed to set scene blending operation option");
  1820. if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(alphaOp))))
  1821. CM_EXCEPT(RenderingAPIException, "Failed to set alpha scene blending operation option");
  1822. }
  1823. //---------------------------------------------------------------------
  1824. void D3D9RenderSystem::_setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage )
  1825. {
  1826. HRESULT hr;
  1827. bool a2c = false;
  1828. static bool lasta2c = false;
  1829. if (func != CMPF_ALWAYS_PASS)
  1830. {
  1831. if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ) ) )
  1832. CM_EXCEPT(RenderingAPIException, "Failed to enable alpha testing");
  1833. a2c = alphaToCoverage;
  1834. }
  1835. else
  1836. {
  1837. if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ) ) )
  1838. CM_EXCEPT(RenderingAPIException, "Failed to disable alpha testing");
  1839. }
  1840. // Set always just be sure
  1841. if( FAILED( hr = __SetRenderState( D3DRS_ALPHAFUNC, D3D9Mappings::get(func) ) ) )
  1842. CM_EXCEPT(RenderingAPIException, "Failed to set alpha reject function");
  1843. if( FAILED( hr = __SetRenderState( D3DRS_ALPHAREF, value ) ) )
  1844. CM_EXCEPT(RenderingAPIException, "Failed to set render state D3DRS_ALPHAREF");
  1845. // Alpha to coverage
  1846. if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  1847. {
  1848. // Vendor-specific hacks on renderstate, gotta love 'em
  1849. if (getCapabilities()->getVendor() == GPU_NVIDIA)
  1850. {
  1851. if (a2c)
  1852. {
  1853. if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C') ) ) )
  1854. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1855. }
  1856. else
  1857. {
  1858. if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, D3DFMT_UNKNOWN ) ) )
  1859. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1860. }
  1861. }
  1862. else if ((getCapabilities()->getVendor() == GPU_ATI))
  1863. {
  1864. if (a2c)
  1865. {
  1866. if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','1') ) ) )
  1867. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1868. }
  1869. else
  1870. {
  1871. // discovered this through trial and error, seems to work
  1872. if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','0') ) ) )
  1873. CM_EXCEPT(RenderingAPIException, "Failed to set alpha to coverage option");
  1874. }
  1875. }
  1876. // no hacks available for any other vendors?
  1877. lasta2c = a2c;
  1878. }
  1879. }
  1880. //---------------------------------------------------------------------
  1881. void D3D9RenderSystem::_setCullingMode( CullingMode mode )
  1882. {
  1883. mCullingMode = mode;
  1884. HRESULT hr;
  1885. bool flip = ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1886. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding));
  1887. if( FAILED (hr = __SetRenderState(D3DRS_CULLMODE,
  1888. D3D9Mappings::get(mode, flip))) )
  1889. CM_EXCEPT(RenderingAPIException, "Failed to set culling mode");
  1890. }
  1891. //---------------------------------------------------------------------
  1892. void D3D9RenderSystem::_setDepthBufferParams( bool depthTest, bool depthWrite, CompareFunction depthFunction )
  1893. {
  1894. _setDepthBufferCheckEnabled( depthTest );
  1895. _setDepthBufferWriteEnabled( depthWrite );
  1896. _setDepthBufferFunction( depthFunction );
  1897. }
  1898. //---------------------------------------------------------------------
  1899. void D3D9RenderSystem::_setDepthBufferCheckEnabled( bool enabled )
  1900. {
  1901. HRESULT hr;
  1902. if( enabled )
  1903. {
  1904. // Use w-buffer if available and enabled
  1905. if( mWBuffer && mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_WBUFFER )
  1906. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_USEW );
  1907. else
  1908. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE );
  1909. }
  1910. else
  1911. hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE );
  1912. if( FAILED( hr ) )
  1913. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer test state");
  1914. }
  1915. //---------------------------------------------------------------------
  1916. void D3D9RenderSystem::_setDepthBufferWriteEnabled( bool enabled )
  1917. {
  1918. HRESULT hr;
  1919. if( FAILED( hr = __SetRenderState( D3DRS_ZWRITEENABLE, enabled ) ) )
  1920. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer write state");
  1921. }
  1922. //---------------------------------------------------------------------
  1923. void D3D9RenderSystem::_setDepthBufferFunction( CompareFunction func )
  1924. {
  1925. HRESULT hr;
  1926. if( FAILED( hr = __SetRenderState( D3DRS_ZFUNC, D3D9Mappings::get(func) ) ) )
  1927. CM_EXCEPT(RenderingAPIException, "Error setting depth buffer test function");
  1928. }
  1929. //---------------------------------------------------------------------
  1930. void D3D9RenderSystem::_setDepthBias(float constantBias, float slopeScaleBias)
  1931. {
  1932. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_DEPTHBIAS) != 0)
  1933. {
  1934. // Negate bias since D3D is backward
  1935. // D3D also expresses the constant bias as an absolute value, rather than
  1936. // relative to minimum depth unit, so scale to fit
  1937. constantBias = -constantBias / 250000.0f;
  1938. HRESULT hr = __SetRenderState(D3DRS_DEPTHBIAS, FLOAT2DWORD(constantBias));
  1939. if (FAILED(hr))
  1940. CM_EXCEPT(RenderingAPIException, "Error setting constant depth bias");
  1941. }
  1942. if ((mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS) != 0)
  1943. {
  1944. // Negate bias since D3D is backward
  1945. slopeScaleBias = -slopeScaleBias;
  1946. HRESULT hr = __SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, FLOAT2DWORD(slopeScaleBias));
  1947. if (FAILED(hr))
  1948. CM_EXCEPT(RenderingAPIException, "Error setting slope scale depth bias");
  1949. }
  1950. }
  1951. //---------------------------------------------------------------------
  1952. void D3D9RenderSystem::_setColourBufferWriteEnabled(bool red, bool green,
  1953. bool blue, bool alpha)
  1954. {
  1955. DWORD val = 0;
  1956. if (red)
  1957. val |= D3DCOLORWRITEENABLE_RED;
  1958. if (green)
  1959. val |= D3DCOLORWRITEENABLE_GREEN;
  1960. if (blue)
  1961. val |= D3DCOLORWRITEENABLE_BLUE;
  1962. if (alpha)
  1963. val |= D3DCOLORWRITEENABLE_ALPHA;
  1964. HRESULT hr = __SetRenderState(D3DRS_COLORWRITEENABLE, val);
  1965. if (FAILED(hr))
  1966. CM_EXCEPT(RenderingAPIException, "Error setting colour write enable flags");
  1967. }
  1968. //---------------------------------------------------------------------
  1969. void D3D9RenderSystem::_setFog( FogMode mode, const Color& colour, float densitiy, float start, float end )
  1970. {
  1971. HRESULT hr;
  1972. D3DRENDERSTATETYPE fogType, fogTypeNot;
  1973. if (mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_FOGTABLE)
  1974. {
  1975. fogType = D3DRS_FOGTABLEMODE;
  1976. fogTypeNot = D3DRS_FOGVERTEXMODE;
  1977. }
  1978. else
  1979. {
  1980. fogType = D3DRS_FOGVERTEXMODE;
  1981. fogTypeNot = D3DRS_FOGTABLEMODE;
  1982. }
  1983. if( mode == FOG_NONE)
  1984. {
  1985. // just disable
  1986. hr = __SetRenderState(fogType, D3DFOG_NONE );
  1987. hr = __SetRenderState(D3DRS_FOGENABLE, FALSE);
  1988. }
  1989. else
  1990. {
  1991. // Allow fog
  1992. hr = __SetRenderState( D3DRS_FOGENABLE, TRUE );
  1993. hr = __SetRenderState( fogTypeNot, D3DFOG_NONE );
  1994. hr = __SetRenderState( fogType, D3D9Mappings::get(mode) );
  1995. hr = __SetRenderState( D3DRS_FOGCOLOR, colour.getAsARGB() );
  1996. hr = __SetFloatRenderState( D3DRS_FOGSTART, start );
  1997. hr = __SetFloatRenderState( D3DRS_FOGEND, end );
  1998. hr = __SetFloatRenderState( D3DRS_FOGDENSITY, densitiy );
  1999. }
  2000. if( FAILED( hr ) )
  2001. CM_EXCEPT(RenderingAPIException, "Error setting render state");
  2002. }
  2003. //---------------------------------------------------------------------
  2004. void D3D9RenderSystem::_setPolygonMode(PolygonMode level)
  2005. {
  2006. HRESULT hr = __SetRenderState(D3DRS_FILLMODE, D3D9Mappings::get(level));
  2007. if (FAILED(hr))
  2008. CM_EXCEPT(RenderingAPIException, "Error setting polygon mode.");
  2009. }
  2010. //---------------------------------------------------------------------
  2011. void D3D9RenderSystem::setStencilCheckEnabled(bool enabled)
  2012. {
  2013. // Allow stencilling
  2014. HRESULT hr = __SetRenderState(D3DRS_STENCILENABLE, enabled);
  2015. if (FAILED(hr))
  2016. CM_EXCEPT(RenderingAPIException, "Error enabling / disabling stencilling.");
  2017. }
  2018. //---------------------------------------------------------------------
  2019. void D3D9RenderSystem::setStencilBufferParams(CompareFunction func,
  2020. UINT32 refValue, UINT32 mask, StencilOperation stencilFailOp,
  2021. StencilOperation depthFailOp, StencilOperation passOp,
  2022. bool twoSidedOperation)
  2023. {
  2024. HRESULT hr;
  2025. bool flip;
  2026. // 2-sided operation
  2027. if (twoSidedOperation)
  2028. {
  2029. if (!mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  2030. CM_EXCEPT(InvalidParametersException, "2-sided stencils are not supported");
  2031. hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
  2032. if (FAILED(hr))
  2033. CM_EXCEPT(RenderingAPIException, "Error setting 2-sided stencil mode.");
  2034. // NB: We should always treat CCW as front face for consistent with default
  2035. // culling mode. Therefore, we must take care with two-sided stencil settings.
  2036. flip = (mInvertVertexWinding && mActiveRenderTarget->requiresTextureFlipping()) ||
  2037. (!mInvertVertexWinding && !mActiveRenderTarget->requiresTextureFlipping());
  2038. // Set alternative versions of ops
  2039. // fail op
  2040. hr = __SetRenderState(D3DRS_CCW_STENCILFAIL, D3D9Mappings::get(stencilFailOp, !flip));
  2041. if (FAILED(hr))
  2042. CM_EXCEPT(RenderingAPIException, "Error setting stencil fail operation (2-sided).");
  2043. // depth fail op
  2044. hr = __SetRenderState(D3DRS_CCW_STENCILZFAIL, D3D9Mappings::get(depthFailOp, !flip));
  2045. if (FAILED(hr))
  2046. CM_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation (2-sided).");
  2047. // pass op
  2048. hr = __SetRenderState(D3DRS_CCW_STENCILPASS, D3D9Mappings::get(passOp, !flip));
  2049. if (FAILED(hr))
  2050. CM_EXCEPT(RenderingAPIException, "Error setting stencil pass operation (2-sided).");
  2051. }
  2052. else
  2053. {
  2054. hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
  2055. if (FAILED(hr))
  2056. CM_EXCEPT(RenderingAPIException, "Error setting 1-sided stencil mode.");
  2057. flip = false;
  2058. }
  2059. // func
  2060. hr = __SetRenderState(D3DRS_STENCILFUNC, D3D9Mappings::get(func));
  2061. if (FAILED(hr))
  2062. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer test function.");
  2063. // reference value
  2064. hr = __SetRenderState(D3DRS_STENCILREF, refValue);
  2065. if (FAILED(hr))
  2066. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer reference value.");
  2067. // mask
  2068. hr = __SetRenderState(D3DRS_STENCILMASK, mask);
  2069. if (FAILED(hr))
  2070. CM_EXCEPT(RenderingAPIException, "Error setting stencil buffer mask.");
  2071. // fail op
  2072. hr = __SetRenderState(D3DRS_STENCILFAIL, D3D9Mappings::get(stencilFailOp, flip));
  2073. if (FAILED(hr))
  2074. CM_EXCEPT(RenderingAPIException, "Error setting stencil fail operation.");
  2075. // depth fail op
  2076. hr = __SetRenderState(D3DRS_STENCILZFAIL, D3D9Mappings::get(depthFailOp, flip));
  2077. if (FAILED(hr))
  2078. CM_EXCEPT(RenderingAPIException, "Error setting stencil depth fail operation.");
  2079. // pass op
  2080. hr = __SetRenderState(D3DRS_STENCILPASS, D3D9Mappings::get(passOp, flip));
  2081. if (FAILED(hr))
  2082. CM_EXCEPT(RenderingAPIException, "Error setting stencil pass operation.");
  2083. }
  2084. //---------------------------------------------------------------------
  2085. void D3D9RenderSystem::_setTextureUnitFiltering(size_t unit, FilterType ftype,
  2086. FilterOptions filter)
  2087. {
  2088. HRESULT hr;
  2089. D3D9Mappings::eD3DTexType texType = mTexStageDesc[unit].texType;
  2090. hr = __SetSamplerState( static_cast<DWORD>(unit), D3D9Mappings::get(ftype),
  2091. D3D9Mappings::get(ftype, filter, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps(), texType));
  2092. if (FAILED(hr))
  2093. CM_EXCEPT(RenderingAPIException, "Failed to set texture filter ");
  2094. }
  2095. //---------------------------------------------------------------------
  2096. DWORD D3D9RenderSystem::_getCurrentAnisotropy(size_t unit)
  2097. {
  2098. DWORD oldVal;
  2099. getActiveD3D9Device()->GetSamplerState(static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, &oldVal);
  2100. return oldVal;
  2101. }
  2102. //---------------------------------------------------------------------
  2103. void D3D9RenderSystem::_setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy)
  2104. {
  2105. if (static_cast<DWORD>(maxAnisotropy) > mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy)
  2106. maxAnisotropy = mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().MaxAnisotropy;
  2107. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  2108. __SetSamplerState( static_cast<DWORD>(unit), D3DSAMP_MAXANISOTROPY, maxAnisotropy );
  2109. }
  2110. //---------------------------------------------------------------------
  2111. HRESULT D3D9RenderSystem::__SetRenderState(D3DRENDERSTATETYPE state, DWORD value)
  2112. {
  2113. HRESULT hr;
  2114. DWORD oldVal;
  2115. if ( FAILED( hr = getActiveD3D9Device()->GetRenderState(state, &oldVal) ) )
  2116. return hr;
  2117. if ( oldVal == value )
  2118. return D3D_OK;
  2119. else
  2120. return getActiveD3D9Device()->SetRenderState(state, value);
  2121. }
  2122. //---------------------------------------------------------------------
  2123. HRESULT D3D9RenderSystem::__SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value)
  2124. {
  2125. HRESULT hr;
  2126. DWORD oldVal;
  2127. if ( FAILED( hr = getActiveD3D9Device()->GetSamplerState(sampler, type, &oldVal) ) )
  2128. return hr;
  2129. if ( oldVal == value )
  2130. return D3D_OK;
  2131. else
  2132. return getActiveD3D9Device()->SetSamplerState(sampler, type, value);
  2133. }
  2134. //---------------------------------------------------------------------
  2135. HRESULT D3D9RenderSystem::__SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value)
  2136. {
  2137. HRESULT hr;
  2138. DWORD oldVal;
  2139. // can only set fixed-function texture stage state
  2140. if (stage < 8)
  2141. {
  2142. if ( FAILED( hr = getActiveD3D9Device()->GetTextureStageState(stage, type, &oldVal) ) )
  2143. return hr;
  2144. if ( oldVal == value )
  2145. return D3D_OK;
  2146. else
  2147. return getActiveD3D9Device()->SetTextureStageState(stage, type, value);
  2148. }
  2149. else
  2150. {
  2151. return D3D_OK;
  2152. }
  2153. }
  2154. //---------------------------------------------------------------------
  2155. void D3D9RenderSystem::_setRenderTarget(RenderTarget *target)
  2156. {
  2157. mActiveRenderTarget = target;
  2158. HRESULT hr;
  2159. // If this is called without going through RenderWindow::update, then
  2160. // the device will not have been set. Calling it twice is safe, the
  2161. // implementation ensures nothing happens if the same device is set twice
  2162. if (std::find(mRenderWindows.begin(), mRenderWindows.end(), target) != mRenderWindows.end())
  2163. {
  2164. D3D9RenderWindow *window = static_cast<D3D9RenderWindow*>(target);
  2165. mDeviceManager->setActiveRenderTargetDevice(window->getDevice());
  2166. // also make sure we validate the device; if this never went
  2167. // through update() it won't be set
  2168. window->_validateDevice();
  2169. }
  2170. // Retrieve render surfaces (up to CM_MAX_MULTIPLE_RENDER_TARGETS)
  2171. IDirect3DSurface9* pBack[CM_MAX_MULTIPLE_RENDER_TARGETS];
  2172. memset(pBack, 0, sizeof(pBack));
  2173. target->getCustomAttribute( "DDBACKBUFFER", &pBack );
  2174. if (!pBack[0])
  2175. return;
  2176. IDirect3DSurface9* pDepth = NULL;
  2177. //Check if we saved a depth buffer for this target
  2178. TargetDepthStencilMap::iterator savedTexture = mCheckedOutTextures.find(target);
  2179. if (savedTexture != mCheckedOutTextures.end())
  2180. {
  2181. pDepth = savedTexture->second.surface;
  2182. }
  2183. if (!pDepth)
  2184. target->getCustomAttribute( "D3DZBUFFER", &pDepth );
  2185. if (!pDepth)
  2186. {
  2187. /// No depth buffer provided, use our own
  2188. /// Request a depth stencil that is compatible with the format, multisample type and
  2189. /// dimensions of the render target.
  2190. D3DSURFACE_DESC srfDesc;
  2191. if(FAILED(pBack[0]->GetDesc(&srfDesc)))
  2192. return; // ?
  2193. pDepth = _getDepthStencilFor(srfDesc.Format, srfDesc.MultiSampleType, srfDesc.MultiSampleQuality, srfDesc.Width, srfDesc.Height);
  2194. }
  2195. // Bind render targets
  2196. UINT32 count = mCurrentCapabilities->getNumMultiRenderTargets();
  2197. for(UINT32 x=0; x<count; ++x)
  2198. {
  2199. hr = getActiveD3D9Device()->SetRenderTarget(x, pBack[x]);
  2200. if (FAILED(hr))
  2201. {
  2202. String msg = DXGetErrorDescription(hr);
  2203. CM_EXCEPT(RenderingAPIException, "Failed to setRenderTarget : " + msg);
  2204. }
  2205. }
  2206. hr = getActiveD3D9Device()->SetDepthStencilSurface(pDepth);
  2207. if (FAILED(hr))
  2208. {
  2209. String msg = DXGetErrorDescription(hr);
  2210. CM_EXCEPT(RenderingAPIException, "Failed to setDepthStencil : " + msg);
  2211. }
  2212. }
  2213. //---------------------------------------------------------------------
  2214. void D3D9RenderSystem::_setViewport( Viewport *vp )
  2215. {
  2216. if( vp != mActiveViewport)
  2217. {
  2218. mActiveViewport = vp;
  2219. // ok, it's different, time to set render target and viewport params
  2220. D3DVIEWPORT9 d3dvp;
  2221. HRESULT hr;
  2222. // Set render target
  2223. RenderTarget* target = vp->getTarget();
  2224. _setRenderTarget(target);
  2225. _setCullingMode( mCullingMode );
  2226. // set viewport dimensions
  2227. d3dvp.X = vp->getActualLeft();
  2228. d3dvp.Y = vp->getActualTop();
  2229. d3dvp.Width = vp->getActualWidth();
  2230. d3dvp.Height = vp->getActualHeight();
  2231. if (target->requiresTextureFlipping())
  2232. {
  2233. // Convert "top-left" to "bottom-left"
  2234. d3dvp.Y = target->getHeight() - d3dvp.Height - d3dvp.Y;
  2235. }
  2236. // Z-values from 0.0 to 1.0 (TODO: standardise with OpenGL)
  2237. d3dvp.MinZ = 0.0f;
  2238. d3dvp.MaxZ = 1.0f;
  2239. if( FAILED( hr = getActiveD3D9Device()->SetViewport( &d3dvp ) ) )
  2240. CM_EXCEPT(RenderingAPIException, "Failed to set viewport.");
  2241. // Set sRGB write mode
  2242. __SetRenderState(D3DRS_SRGBWRITEENABLE, target->isHardwareGammaEnabled());
  2243. }
  2244. }
  2245. //---------------------------------------------------------------------
  2246. void D3D9RenderSystem::_beginFrame()
  2247. {
  2248. HRESULT hr;
  2249. if( !mActiveViewport )
  2250. CM_EXCEPT(InternalErrorException, "Cannot begin frame - no viewport selected.");
  2251. if( FAILED( hr = getActiveD3D9Device()->BeginScene() ) )
  2252. {
  2253. String msg = DXGetErrorDescription(hr);
  2254. CM_EXCEPT(RenderingAPIException, "Error beginning frame :" + msg);
  2255. }
  2256. mLastVertexSourceCount = 0;
  2257. // Clear left overs of previous viewport.
  2258. // I.E: Viewport A can use 3 different textures and light states
  2259. // When trying to render viewport B these settings should be cleared, otherwise
  2260. // graphical artifacts might occur.
  2261. mDeviceManager->getActiveDevice()->clearDeviceStreams();
  2262. }
  2263. //---------------------------------------------------------------------
  2264. void D3D9RenderSystem::_endFrame()
  2265. {
  2266. HRESULT hr;
  2267. if( FAILED( hr = getActiveD3D9Device()->EndScene() ) )
  2268. CM_EXCEPT(RenderingAPIException, "Error ending frame");
  2269. mDeviceManager->destroyInactiveRenderDevices();
  2270. }
  2271. //---------------------------------------------------------------------
  2272. struct D3D9RenderContext : public RenderSystem::RenderSystemContext
  2273. {
  2274. RenderTarget* target;
  2275. };
  2276. //---------------------------------------------------------------------
  2277. D3D9RenderSystem::ZBufferIdentifier D3D9RenderSystem::getZBufferIdentifier(RenderTarget* rt)
  2278. {
  2279. // Retrieve render surfaces (up to CM_MAX_MULTIPLE_RENDER_TARGETS)
  2280. IDirect3DSurface9* pBack[CM_MAX_MULTIPLE_RENDER_TARGETS];
  2281. memset(pBack, 0, sizeof(pBack));
  2282. rt->getCustomAttribute( "DDBACKBUFFER", &pBack );
  2283. assert(pBack[0]);
  2284. /// Request a depth stencil that is compatible with the format, multisample type and
  2285. /// dimensions of the render target.
  2286. D3DSURFACE_DESC srfDesc;
  2287. HRESULT hr = pBack[0]->GetDesc(&srfDesc);
  2288. assert(!(FAILED(hr)));
  2289. D3DFORMAT dsfmt = _getDepthStencilFormatFor(srfDesc.Format);
  2290. assert(dsfmt != D3DFMT_UNKNOWN);
  2291. /// Build identifier and return
  2292. ZBufferIdentifier zBufferIdentifier;
  2293. zBufferIdentifier.format = dsfmt;
  2294. zBufferIdentifier.multisampleType = srfDesc.MultiSampleType;
  2295. zBufferIdentifier.device = getActiveD3D9Device();
  2296. return zBufferIdentifier;
  2297. }
  2298. //---------------------------------------------------------------------
  2299. RenderSystem::RenderSystemContext* D3D9RenderSystem::_pauseFrame(void)
  2300. {
  2301. //Stop rendering
  2302. _endFrame();
  2303. D3D9RenderContext* context = new D3D9RenderContext;
  2304. context->target = mActiveRenderTarget;
  2305. //Don't do this to backbuffers. Is there a more elegant way to check?
  2306. if (!dynamic_cast<D3D9RenderWindow*>(mActiveRenderTarget))
  2307. {
  2308. //Get the matching z buffer identifier and queue
  2309. ZBufferIdentifier zBufferIdentifier = getZBufferIdentifier(mActiveRenderTarget);
  2310. ZBufferRefQueue& zBuffers = mZBufferHash[zBufferIdentifier];
  2311. #ifdef CM_DEBUG_MODE
  2312. //Check that queue handling works as expected
  2313. IDirect3DSurface9* pDepth;
  2314. getActiveD3D9Device()->GetDepthStencilSurface(&pDepth);
  2315. // Release immediately -> each get increase the ref count.
  2316. if (pDepth != NULL)
  2317. pDepth->Release();
  2318. assert(zBuffers.front().surface == pDepth);
  2319. #endif
  2320. //Store the depth buffer in the side and remove it from the queue
  2321. mCheckedOutTextures[mActiveRenderTarget] = zBuffers.front();
  2322. zBuffers.pop_front();
  2323. }
  2324. return context;
  2325. }
  2326. //---------------------------------------------------------------------
  2327. void D3D9RenderSystem::_resumeFrame(RenderSystemContext* context)
  2328. {
  2329. //Resume rendering
  2330. _beginFrame();
  2331. D3D9RenderContext* d3dContext = static_cast<D3D9RenderContext*>(context);
  2332. //Don't do this to backbuffers. Is there a more elegant way to check?
  2333. if (!dynamic_cast<D3D9RenderWindow*>(d3dContext->target))
  2334. {
  2335. ///Find the stored depth buffer
  2336. ZBufferIdentifier zBufferIdentifier = getZBufferIdentifier(d3dContext->target);
  2337. ZBufferRefQueue& zBuffers = mZBufferHash[zBufferIdentifier];
  2338. assert(mCheckedOutTextures.find(d3dContext->target) != mCheckedOutTextures.end());
  2339. //Return it to the general queue
  2340. zBuffers.push_front(mCheckedOutTextures[d3dContext->target]);
  2341. mCheckedOutTextures.erase(d3dContext->target);
  2342. }
  2343. delete context;
  2344. }
  2345. //---------------------------------------------------------------------
  2346. void D3D9RenderSystem::setVertexDeclaration(VertexDeclaration* decl)
  2347. {
  2348. HRESULT hr;
  2349. D3D9VertexDeclaration* d3ddecl =
  2350. static_cast<D3D9VertexDeclaration*>(decl);
  2351. if (FAILED(hr = getActiveD3D9Device()->SetVertexDeclaration(d3ddecl->getD3DVertexDeclaration())))
  2352. {
  2353. CM_EXCEPT(RenderingAPIException, "Unable to set D3D9 vertex declaration");
  2354. }
  2355. }
  2356. //---------------------------------------------------------------------
  2357. void D3D9RenderSystem::setVertexBufferBinding(VertexBufferBinding* binding)
  2358. {
  2359. HRESULT hr;
  2360. // TODO: attempt to detect duplicates
  2361. const VertexBufferBinding::VertexBufferBindingMap& binds = binding->getBindings();
  2362. VertexBufferBinding::VertexBufferBindingMap::const_iterator i, iend;
  2363. size_t source = 0;
  2364. iend = binds.end();
  2365. for (i = binds.begin(); i != iend; ++i, ++source)
  2366. {
  2367. // Unbind gap sources
  2368. for ( ; source < i->first; ++source)
  2369. {
  2370. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(source), NULL, 0, 0);
  2371. if (FAILED(hr))
  2372. {
  2373. CM_EXCEPT(RenderingAPIException, "Unable to reset unused D3D9 stream source");
  2374. }
  2375. }
  2376. D3D9HardwareVertexBuffer* d3d9buf =
  2377. static_cast<D3D9HardwareVertexBuffer*>(i->second.get());
  2378. hr = getActiveD3D9Device()->SetStreamSource(
  2379. static_cast<UINT>(source),
  2380. d3d9buf->getD3D9VertexBuffer(),
  2381. 0, // no stream offset, this is handled in _render instead
  2382. static_cast<UINT>(d3d9buf->getVertexSize()) // stride
  2383. );
  2384. if (FAILED(hr))
  2385. {
  2386. CM_EXCEPT(RenderingAPIException, "Unable to set D3D9 stream source for buffer binding");
  2387. }
  2388. }
  2389. // Unbind any unused sources
  2390. for (size_t unused = source; unused < mLastVertexSourceCount; ++unused)
  2391. {
  2392. hr = getActiveD3D9Device()->SetStreamSource(static_cast<UINT>(unused), NULL, 0, 0);
  2393. if (FAILED(hr))
  2394. {
  2395. CM_EXCEPT(RenderingAPIException, "Unable to reset unused D3D9 stream source");
  2396. }
  2397. }
  2398. mLastVertexSourceCount = source;
  2399. }
  2400. //---------------------------------------------------------------------
  2401. void D3D9RenderSystem::_render(const RenderOperation& op)
  2402. {
  2403. // Exit immediately if there is nothing to render
  2404. // This caused a problem on FireGL 8800
  2405. if (op.vertexData->vertexCount == 0)
  2406. return;
  2407. // Call super class
  2408. RenderSystem::_render(op);
  2409. // To think about: possibly remove setVertexDeclaration and
  2410. // setVertexBufferBinding from RenderSystem since the sequence is
  2411. // a bit too D3D9-specific?
  2412. setVertexDeclaration(op.vertexData->vertexDeclaration);
  2413. setVertexBufferBinding(op.vertexData->vertexBufferBinding);
  2414. // Determine rendering operation
  2415. D3DPRIMITIVETYPE primType = D3DPT_TRIANGLELIST;
  2416. DWORD primCount = 0;
  2417. switch( op.operationType )
  2418. {
  2419. case RenderOperation::OT_POINT_LIST:
  2420. primType = D3DPT_POINTLIST;
  2421. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount);
  2422. break;
  2423. case RenderOperation::OT_LINE_LIST:
  2424. primType = D3DPT_LINELIST;
  2425. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2;
  2426. break;
  2427. case RenderOperation::OT_LINE_STRIP:
  2428. primType = D3DPT_LINESTRIP;
  2429. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1;
  2430. break;
  2431. case RenderOperation::OT_TRIANGLE_LIST:
  2432. primType = D3DPT_TRIANGLELIST;
  2433. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3;
  2434. break;
  2435. case RenderOperation::OT_TRIANGLE_STRIP:
  2436. primType = D3DPT_TRIANGLESTRIP;
  2437. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2;
  2438. break;
  2439. case RenderOperation::OT_TRIANGLE_FAN:
  2440. primType = D3DPT_TRIANGLEFAN;
  2441. primCount = static_cast<DWORD>(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2;
  2442. break;
  2443. }
  2444. if (!primCount)
  2445. return;
  2446. // Issue the op
  2447. HRESULT hr;
  2448. if( op.useIndexes )
  2449. {
  2450. D3D9HardwareIndexBuffer* d3dIdxBuf =
  2451. static_cast<D3D9HardwareIndexBuffer*>(op.indexData->indexBuffer.get());
  2452. hr = getActiveD3D9Device()->SetIndices( d3dIdxBuf->getD3DIndexBuffer() );
  2453. if (FAILED(hr))
  2454. {
  2455. CM_EXCEPT(RenderingAPIException, "Failed to set index buffer");
  2456. }
  2457. do
  2458. {
  2459. // Update derived depth bias
  2460. if (mDerivedDepthBias && mCurrentPassIterationNum > 0)
  2461. {
  2462. _setDepthBias(mDerivedDepthBiasBase +
  2463. mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
  2464. mDerivedDepthBiasSlopeScale);
  2465. }
  2466. // do indexed draw operation
  2467. hr = getActiveD3D9Device()->DrawIndexedPrimitive(
  2468. primType,
  2469. static_cast<INT>(op.vertexData->vertexStart),
  2470. 0, // Min vertex index - assume we can go right down to 0
  2471. static_cast<UINT>(op.vertexData->vertexCount),
  2472. static_cast<UINT>(op.indexData->indexStart),
  2473. static_cast<UINT>(primCount)
  2474. );
  2475. } while (updatePassIterationRenderState());
  2476. }
  2477. else
  2478. {
  2479. // nfz: gpu_iterate
  2480. do
  2481. {
  2482. // Update derived depth bias
  2483. if (mDerivedDepthBias && mCurrentPassIterationNum > 0)
  2484. {
  2485. _setDepthBias(mDerivedDepthBiasBase +
  2486. mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
  2487. mDerivedDepthBiasSlopeScale);
  2488. }
  2489. // Unindexed, a little simpler!
  2490. hr = getActiveD3D9Device()->DrawPrimitive(
  2491. primType,
  2492. static_cast<UINT>(op.vertexData->vertexStart),
  2493. static_cast<UINT>(primCount)
  2494. );
  2495. } while (updatePassIterationRenderState());
  2496. }
  2497. if( FAILED( hr ) )
  2498. {
  2499. String msg = DXGetErrorDescription(hr);
  2500. CM_EXCEPT(RenderingAPIException, "Failed to DrawPrimitive : " + msg);
  2501. }
  2502. }
  2503. //---------------------------------------------------------------------
  2504. void D3D9RenderSystem::setNormaliseNormals(bool normalise)
  2505. {
  2506. __SetRenderState(D3DRS_NORMALIZENORMALS,
  2507. normalise ? TRUE : FALSE);
  2508. }
  2509. //---------------------------------------------------------------------
  2510. void D3D9RenderSystem::bindGpuProgram(GpuProgram* prg)
  2511. {
  2512. HRESULT hr;
  2513. switch (prg->getType())
  2514. {
  2515. case GPT_VERTEX_PROGRAM:
  2516. hr = getActiveD3D9Device()->SetVertexShader(
  2517. static_cast<D3D9GpuVertexProgram*>(prg)->getVertexShader());
  2518. if (FAILED(hr))
  2519. {
  2520. CM_EXCEPT(RenderingAPIException, "Error calling SetVertexShader");
  2521. }
  2522. break;
  2523. case GPT_FRAGMENT_PROGRAM:
  2524. hr = getActiveD3D9Device()->SetPixelShader(
  2525. static_cast<D3D9GpuFragmentProgram*>(prg)->getPixelShader());
  2526. if (FAILED(hr))
  2527. {
  2528. CM_EXCEPT(RenderingAPIException, "Error calling SetPixelShader");
  2529. }
  2530. break;
  2531. };
  2532. // Make sure texcoord index is equal to stage value, As SDK Doc suggests:
  2533. // "When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value."
  2534. // This solves such an errors when working with the Debug runtime -
  2535. // "Direct3D9: (ERROR) :Stage 1 - Texture coordinate index in the stage must be equal to the stage index when programmable vertex pipeline is used".
  2536. for (unsigned int nStage=0; nStage < 8; ++nStage)
  2537. __SetTextureStageState(nStage, D3DTSS_TEXCOORDINDEX, nStage);
  2538. RenderSystem::bindGpuProgram(prg);
  2539. }
  2540. //---------------------------------------------------------------------
  2541. void D3D9RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  2542. {
  2543. HRESULT hr;
  2544. switch(gptype)
  2545. {
  2546. case GPT_VERTEX_PROGRAM:
  2547. mActiveVertexGpuProgramParameters = nullptr;
  2548. hr = getActiveD3D9Device()->SetVertexShader(NULL);
  2549. if (FAILED(hr))
  2550. {
  2551. CM_EXCEPT(RenderingAPIException, "Error resetting SetVertexShader to NULL");
  2552. }
  2553. break;
  2554. case GPT_FRAGMENT_PROGRAM:
  2555. mActiveFragmentGpuProgramParameters = nullptr;
  2556. hr = getActiveD3D9Device()->SetPixelShader(NULL);
  2557. if (FAILED(hr))
  2558. {
  2559. CM_EXCEPT(RenderingAPIException, "Error resetting SetPixelShader to NULL");
  2560. }
  2561. break;
  2562. };
  2563. RenderSystem::unbindGpuProgram(gptype);
  2564. }
  2565. //---------------------------------------------------------------------
  2566. void D3D9RenderSystem::bindGpuProgramParameters(GpuProgramType gptype,
  2567. GpuProgramParametersSharedPtr params, UINT16 variability)
  2568. {
  2569. // special case pass iteration
  2570. if (variability == (UINT16)GPV_PASS_ITERATION_NUMBER)
  2571. {
  2572. bindGpuProgramPassIterationParameters(gptype);
  2573. return;
  2574. }
  2575. if (variability & (UINT16)GPV_GLOBAL)
  2576. {
  2577. // D3D9 doesn't support shared constant buffers, so use copy routine
  2578. params->_copySharedParams();
  2579. }
  2580. HRESULT hr;
  2581. GpuLogicalBufferStructPtr floatLogical = params->getFloatLogicalBufferStruct();
  2582. GpuLogicalBufferStructPtr intLogical = params->getIntLogicalBufferStruct();
  2583. switch(gptype)
  2584. {
  2585. case GPT_VERTEX_PROGRAM:
  2586. mActiveVertexGpuProgramParameters = params;
  2587. {
  2588. CM_LOCK_MUTEX(floatLogical->mutex)
  2589. for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin();
  2590. i != floatLogical->map.end(); ++i)
  2591. {
  2592. if (i->second.variability & variability)
  2593. {
  2594. size_t logicalIndex = i->first;
  2595. const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
  2596. size_t slotCount = i->second.currentSize / 4;
  2597. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2598. "elements less than 4 wide for D3D9");
  2599. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantF(
  2600. (UINT)logicalIndex, pFloat, (UINT)slotCount)))
  2601. {
  2602. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader float parameters");
  2603. }
  2604. }
  2605. }
  2606. }
  2607. // bind ints
  2608. {
  2609. CM_LOCK_MUTEX(intLogical->mutex)
  2610. for (GpuLogicalIndexUseMap::const_iterator i = intLogical->map.begin();
  2611. i != intLogical->map.end(); ++i)
  2612. {
  2613. if (i->second.variability & variability)
  2614. {
  2615. size_t logicalIndex = i->first;
  2616. const int* pInt = params->getIntPointer(i->second.physicalIndex);
  2617. size_t slotCount = i->second.currentSize / 4;
  2618. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2619. "elements less than 4 wide for D3D9");
  2620. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantI(
  2621. static_cast<UINT>(logicalIndex), pInt, static_cast<UINT>(slotCount))))
  2622. {
  2623. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader int parameters");
  2624. }
  2625. }
  2626. }
  2627. }
  2628. break;
  2629. case GPT_FRAGMENT_PROGRAM:
  2630. mActiveFragmentGpuProgramParameters = params;
  2631. {
  2632. CM_LOCK_MUTEX(floatLogical->mutex)
  2633. for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin();
  2634. i != floatLogical->map.end(); ++i)
  2635. {
  2636. if (i->second.variability & variability)
  2637. {
  2638. size_t logicalIndex = i->first;
  2639. const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
  2640. size_t slotCount = i->second.currentSize / 4;
  2641. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2642. "elements less than 4 wide for D3D9");
  2643. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantF(
  2644. static_cast<UINT>(logicalIndex), pFloat, static_cast<UINT>(slotCount))))
  2645. {
  2646. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader float parameters");
  2647. }
  2648. }
  2649. }
  2650. }
  2651. // bind ints
  2652. {
  2653. CM_LOCK_MUTEX(intLogical->mutex)
  2654. for (GpuLogicalIndexUseMap::const_iterator i = intLogical->map.begin();
  2655. i != intLogical->map.end(); ++i)
  2656. {
  2657. if (i->second.variability & variability)
  2658. {
  2659. size_t logicalIndex = i->first;
  2660. const int* pInt = params->getIntPointer(i->second.physicalIndex);
  2661. size_t slotCount = i->second.currentSize / 4;
  2662. assert (i->second.currentSize % 4 == 0 && "Should not have any "
  2663. "elements less than 4 wide for D3D9");
  2664. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantI(
  2665. static_cast<UINT>(logicalIndex), pInt, static_cast<UINT>(slotCount))))
  2666. {
  2667. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader int parameters");
  2668. }
  2669. }
  2670. }
  2671. }
  2672. break;
  2673. };
  2674. }
  2675. //---------------------------------------------------------------------
  2676. void D3D9RenderSystem::bindGpuProgramPassIterationParameters(GpuProgramType gptype)
  2677. {
  2678. HRESULT hr;
  2679. size_t physicalIndex = 0;
  2680. size_t logicalIndex = 0;
  2681. const float* pFloat;
  2682. switch(gptype)
  2683. {
  2684. case GPT_VERTEX_PROGRAM:
  2685. if (mActiveVertexGpuProgramParameters->hasPassIterationNumber())
  2686. {
  2687. physicalIndex = mActiveVertexGpuProgramParameters->getPassIterationNumberIndex();
  2688. logicalIndex = mActiveVertexGpuProgramParameters->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
  2689. pFloat = mActiveVertexGpuProgramParameters->getFloatPointer(physicalIndex);
  2690. if (FAILED(hr = getActiveD3D9Device()->SetVertexShaderConstantF(
  2691. static_cast<UINT>(logicalIndex), pFloat, 1)))
  2692. {
  2693. CM_EXCEPT(RenderingAPIException, "Unable to upload vertex shader multi pass parameters");
  2694. }
  2695. }
  2696. break;
  2697. case GPT_FRAGMENT_PROGRAM:
  2698. if (mActiveFragmentGpuProgramParameters->hasPassIterationNumber())
  2699. {
  2700. physicalIndex = mActiveFragmentGpuProgramParameters->getPassIterationNumberIndex();
  2701. logicalIndex = mActiveFragmentGpuProgramParameters->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
  2702. pFloat = mActiveFragmentGpuProgramParameters->getFloatPointer(physicalIndex);
  2703. if (FAILED(hr = getActiveD3D9Device()->SetPixelShaderConstantF(
  2704. static_cast<UINT>(logicalIndex), pFloat, 1)))
  2705. {
  2706. CM_EXCEPT(RenderingAPIException, "Unable to upload pixel shader multi pass parameters");
  2707. }
  2708. }
  2709. break;
  2710. }
  2711. }
  2712. //---------------------------------------------------------------------
  2713. void D3D9RenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  2714. {
  2715. size_t i;
  2716. size_t numClipPlanes;
  2717. D3DXPLANE dx9ClipPlane;
  2718. DWORD mask = 0;
  2719. HRESULT hr;
  2720. numClipPlanes = clipPlanes.size();
  2721. for (i = 0; i < numClipPlanes; ++i)
  2722. {
  2723. const Plane& plane = clipPlanes[i];
  2724. dx9ClipPlane.a = plane.normal.x;
  2725. dx9ClipPlane.b = plane.normal.y;
  2726. dx9ClipPlane.c = plane.normal.z;
  2727. dx9ClipPlane.d = plane.d;
  2728. if (mVertexProgramBound)
  2729. {
  2730. // programmable clips in clip space (ugh)
  2731. // must transform worldspace planes by view/proj
  2732. D3DXMATRIX xform;
  2733. D3DXMatrixMultiply(&xform, &mDxViewMat, &mDxProjMat);
  2734. D3DXMatrixInverse(&xform, NULL, &xform);
  2735. D3DXMatrixTranspose(&xform, &xform);
  2736. D3DXPlaneTransform(&dx9ClipPlane, &dx9ClipPlane, &xform);
  2737. }
  2738. hr = getActiveD3D9Device()->SetClipPlane(static_cast<DWORD>(i), dx9ClipPlane);
  2739. if (FAILED(hr))
  2740. {
  2741. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  2742. }
  2743. mask |= (1 << i);
  2744. }
  2745. hr = __SetRenderState(D3DRS_CLIPPLANEENABLE, mask);
  2746. if (FAILED(hr))
  2747. {
  2748. CM_EXCEPT(RenderingAPIException, "Unable to set render state for clip planes");
  2749. }
  2750. }
  2751. //---------------------------------------------------------------------
  2752. void D3D9RenderSystem::setScissorTest(bool enabled, size_t left, size_t top, size_t right,
  2753. size_t bottom)
  2754. {
  2755. HRESULT hr;
  2756. if (enabled)
  2757. {
  2758. if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE)))
  2759. {
  2760. CM_EXCEPT(RenderingAPIException, "Unable to enable scissor rendering state; " + getErrorDescription(hr));
  2761. }
  2762. RECT rect;
  2763. rect.left = static_cast<LONG>(left);
  2764. rect.top = static_cast<LONG>(top);
  2765. rect.bottom = static_cast<LONG>(bottom);
  2766. rect.right = static_cast<LONG>(right);
  2767. if (FAILED(hr = getActiveD3D9Device()->SetScissorRect(&rect)))
  2768. {
  2769. CM_EXCEPT(RenderingAPIException, "Unable to set scissor rectangle; " + getErrorDescription(hr));
  2770. }
  2771. }
  2772. else
  2773. {
  2774. if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE)))
  2775. {
  2776. CM_EXCEPT(RenderingAPIException, "Unable to disable scissor rendering state; " + getErrorDescription(hr));
  2777. }
  2778. }
  2779. }
  2780. //---------------------------------------------------------------------
  2781. void D3D9RenderSystem::clearFrameBuffer(unsigned int buffers,
  2782. const Color& colour, float depth, unsigned short stencil)
  2783. {
  2784. DWORD flags = 0;
  2785. if (buffers & FBT_COLOUR)
  2786. {
  2787. flags |= D3DCLEAR_TARGET;
  2788. }
  2789. if (buffers & FBT_DEPTH)
  2790. {
  2791. flags |= D3DCLEAR_ZBUFFER;
  2792. }
  2793. // Only try to clear the stencil buffer if supported
  2794. if (buffers & FBT_STENCIL && mCurrentCapabilities->hasCapability(RSC_HWSTENCIL))
  2795. {
  2796. flags |= D3DCLEAR_STENCIL;
  2797. }
  2798. HRESULT hr;
  2799. if( FAILED( hr = getActiveD3D9Device()->Clear(
  2800. 0,
  2801. NULL,
  2802. flags,
  2803. colour.getAsARGB(),
  2804. depth,
  2805. stencil ) ) )
  2806. {
  2807. String msg = DXGetErrorDescription(hr);
  2808. CM_EXCEPT(RenderingAPIException, "Error clearing frame buffer : " + msg);
  2809. }
  2810. }
  2811. //---------------------------------------------------------------------
  2812. void D3D9RenderSystem::_makeProjectionMatrix(float left, float right,
  2813. float bottom, float top, float nearPlane, float farPlane, Matrix4& dest,
  2814. bool forGpuProgram)
  2815. {
  2816. // Correct position for off-axis projection matrix
  2817. if (!forGpuProgram)
  2818. {
  2819. float offsetX = left + right;
  2820. float offsetY = top + bottom;
  2821. left -= offsetX;
  2822. right -= offsetX;
  2823. top -= offsetY;
  2824. bottom -= offsetY;
  2825. }
  2826. float width = right - left;
  2827. float height = top - bottom;
  2828. float q, qn;
  2829. if (farPlane == 0)
  2830. {
  2831. q = 1 - Frustum::INFINITE_FAR_PLANE_ADJUST;
  2832. qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 1);
  2833. }
  2834. else
  2835. {
  2836. q = farPlane / ( farPlane - nearPlane );
  2837. qn = -q * nearPlane;
  2838. }
  2839. dest = Matrix4::ZERO;
  2840. dest[0][0] = 2 * nearPlane / width;
  2841. dest[0][2] = (right+left) / width;
  2842. dest[1][1] = 2 * nearPlane / height;
  2843. dest[1][2] = (top+bottom) / height;
  2844. if (forGpuProgram)
  2845. {
  2846. dest[2][2] = -q;
  2847. dest[3][2] = -1.0f;
  2848. }
  2849. else
  2850. {
  2851. dest[2][2] = q;
  2852. dest[3][2] = 1.0f;
  2853. }
  2854. dest[2][3] = qn;
  2855. }
  2856. // ------------------------------------------------------------------
  2857. void D3D9RenderSystem::setClipPlane (UINT16 index, float A, float B, float C, float D)
  2858. {
  2859. float plane[4] = { A, B, C, D };
  2860. getActiveD3D9Device()->SetClipPlane (index, plane);
  2861. }
  2862. // ------------------------------------------------------------------
  2863. void D3D9RenderSystem::enableClipPlane (UINT16 index, bool enable)
  2864. {
  2865. DWORD prev;
  2866. getActiveD3D9Device()->GetRenderState(D3DRS_CLIPPLANEENABLE, &prev);
  2867. __SetRenderState(D3DRS_CLIPPLANEENABLE, enable?
  2868. (prev | (1 << index)) : (prev & ~(1 << index)));
  2869. }
  2870. //---------------------------------------------------------------------
  2871. HardwareOcclusionQuery* D3D9RenderSystem::createHardwareOcclusionQuery()
  2872. {
  2873. D3D9HardwareOcclusionQuery* ret = new D3D9HardwareOcclusionQuery();
  2874. mHwOcclusionQueries.push_back(ret);
  2875. return ret;
  2876. }
  2877. //---------------------------------------------------------------------
  2878. float D3D9RenderSystem::getHorizontalTexelOffset()
  2879. {
  2880. // D3D considers the origin to be in the center of a pixel
  2881. return -0.5f;
  2882. }
  2883. //---------------------------------------------------------------------
  2884. float D3D9RenderSystem::getVerticalTexelOffset()
  2885. {
  2886. // D3D considers the origin to be in the center of a pixel
  2887. return -0.5f;
  2888. }
  2889. //---------------------------------------------------------------------
  2890. void D3D9RenderSystem::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane,
  2891. bool forGpuProgram)
  2892. {
  2893. // Thanks to Eric Lenyel for posting this calculation at www.terathon.com
  2894. // Calculate the clip-space corner point opposite the clipping plane
  2895. // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
  2896. // transform it into camera space by multiplying it
  2897. // by the inverse of the projection matrix
  2898. /* generalised version
  2899. Vector4 q = matrix.inverse() *
  2900. Vector4(Math::Sign(plane.normal.x), Math::Sign(plane.normal.y), 1.0f, 1.0f);
  2901. */
  2902. Vector4 q;
  2903. q.x = Math::Sign(plane.normal.x) / matrix[0][0];
  2904. q.y = Math::Sign(plane.normal.y) / matrix[1][1];
  2905. q.z = 1.0F;
  2906. // flip the next bit from Lengyel since we're right-handed
  2907. if (forGpuProgram)
  2908. {
  2909. q.w = (1.0F - matrix[2][2]) / matrix[2][3];
  2910. }
  2911. else
  2912. {
  2913. q.w = (1.0F + matrix[2][2]) / matrix[2][3];
  2914. }
  2915. // Calculate the scaled plane vector
  2916. Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d);
  2917. Vector4 c = clipPlane4d * (1.0F / (clipPlane4d.dotProduct(q)));
  2918. // Replace the third row of the projection matrix
  2919. matrix[2][0] = c.x;
  2920. matrix[2][1] = c.y;
  2921. // flip the next bit from Lengyel since we're right-handed
  2922. if (forGpuProgram)
  2923. {
  2924. matrix[2][2] = c.z;
  2925. }
  2926. else
  2927. {
  2928. matrix[2][2] = -c.z;
  2929. }
  2930. matrix[2][3] = c.w;
  2931. }
  2932. //---------------------------------------------------------------------
  2933. float D3D9RenderSystem::getMinimumDepthInputValue()
  2934. {
  2935. // Range [0.0f, 1.0f]
  2936. return 0.0f;
  2937. }
  2938. //---------------------------------------------------------------------
  2939. float D3D9RenderSystem::getMaximumDepthInputValue()
  2940. {
  2941. // Range [0.0f, 1.0f]
  2942. // D3D inverts even identity view matrices, so maximum INPUT is -1.0
  2943. return -1.0f;
  2944. }
  2945. //---------------------------------------------------------------------
  2946. IDirect3D9* D3D9RenderSystem::getDirect3D9()
  2947. {
  2948. IDirect3D9* pDirect3D9 = msD3D9RenderSystem->mpD3D;
  2949. if (pDirect3D9 == NULL)
  2950. {
  2951. CM_EXCEPT(InvalidParametersException, "Direct3D9 interface is NULL !!!");
  2952. }
  2953. return pDirect3D9;
  2954. }
  2955. //---------------------------------------------------------------------
  2956. UINT D3D9RenderSystem::getResourceCreationDeviceCount()
  2957. {
  2958. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  2959. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  2960. {
  2961. return 1;
  2962. }
  2963. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  2964. {
  2965. return msD3D9RenderSystem->mDeviceManager->getDeviceCount();
  2966. }
  2967. CM_EXCEPT(InvalidParametersException, "Invalid resource creation policy !!!" );
  2968. return 0;
  2969. }
  2970. //---------------------------------------------------------------------
  2971. IDirect3DDevice9* D3D9RenderSystem::getResourceCreationDevice(UINT index)
  2972. {
  2973. D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy();
  2974. IDirect3DDevice9* d3d9Device = NULL;
  2975. if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE)
  2976. {
  2977. d3d9Device = msD3D9RenderSystem->getActiveD3D9Device();
  2978. }
  2979. else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES)
  2980. {
  2981. d3d9Device = msD3D9RenderSystem->mDeviceManager->getDevice(index)->getD3D9Device();
  2982. }
  2983. else
  2984. {
  2985. CM_EXCEPT(InvalidParametersException, "Invalid resource creation policy !!!" );
  2986. }
  2987. return d3d9Device;
  2988. }
  2989. //---------------------------------------------------------------------
  2990. IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9Device()
  2991. {
  2992. D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice();
  2993. IDirect3DDevice9* d3d9Device;
  2994. d3d9Device = activeDevice->getD3D9Device();
  2995. if (d3d9Device == NULL)
  2996. {
  2997. CM_EXCEPT(InvalidParametersException, "Current d3d9 device is NULL !!!" );
  2998. }
  2999. return d3d9Device;
  3000. }
  3001. //---------------------------------------------------------------------
  3002. // Formats to try, in decreasing order of preference
  3003. D3DFORMAT ddDepthStencilFormats[]={
  3004. D3DFMT_D24FS8,
  3005. D3DFMT_D24S8,
  3006. D3DFMT_D24X4S4,
  3007. D3DFMT_D24X8,
  3008. D3DFMT_D15S1,
  3009. D3DFMT_D16,
  3010. D3DFMT_D32
  3011. };
  3012. #define NDSFORMATS (sizeof(ddDepthStencilFormats)/sizeof(D3DFORMAT))
  3013. D3DFORMAT D3D9RenderSystem::_getDepthStencilFormatFor(D3DFORMAT fmt)
  3014. {
  3015. /// Check if result is cached
  3016. DepthStencilHash::iterator i = mDepthStencilHash.find((unsigned int)fmt);
  3017. if(i != mDepthStencilHash.end())
  3018. return i->second;
  3019. /// If not, probe with CheckDepthStencilMatch
  3020. D3DFORMAT dsfmt = D3DFMT_UNKNOWN;
  3021. /// Get description of primary render target
  3022. D3D9Device* activeDevice = mDeviceManager->getActiveDevice();
  3023. IDirect3DSurface9* mSurface = activeDevice->getPrimaryWindow()->getRenderSurface();
  3024. D3DSURFACE_DESC srfDesc;
  3025. if(!FAILED(mSurface->GetDesc(&srfDesc)))
  3026. {
  3027. /// Probe all depth stencil formats
  3028. /// Break on first one that matches
  3029. for(size_t x=0; x<NDSFORMATS; ++x)
  3030. {
  3031. // Verify that the depth format exists
  3032. if (mpD3D->CheckDeviceFormat(
  3033. activeDevice->getAdapterNumber(),
  3034. activeDevice->getDeviceType(),
  3035. srfDesc.Format,
  3036. D3DUSAGE_DEPTHSTENCIL,
  3037. D3DRTYPE_SURFACE,
  3038. ddDepthStencilFormats[x]) != D3D_OK)
  3039. {
  3040. continue;
  3041. }
  3042. // Verify that the depth format is compatible
  3043. if(mpD3D->CheckDepthStencilMatch(
  3044. activeDevice->getAdapterNumber(),
  3045. activeDevice->getDeviceType(),
  3046. srfDesc.Format,
  3047. fmt, ddDepthStencilFormats[x]) == D3D_OK)
  3048. {
  3049. dsfmt = ddDepthStencilFormats[x];
  3050. break;
  3051. }
  3052. }
  3053. }
  3054. /// Cache result
  3055. mDepthStencilHash[(unsigned int)fmt] = dsfmt;
  3056. return dsfmt;
  3057. }
  3058. IDirect3DSurface9* D3D9RenderSystem::_getDepthStencilFor(D3DFORMAT fmt,
  3059. D3DMULTISAMPLE_TYPE multisample, DWORD multisample_quality, size_t width, size_t height)
  3060. {
  3061. D3DFORMAT dsfmt = _getDepthStencilFormatFor(fmt);
  3062. if(dsfmt == D3DFMT_UNKNOWN)
  3063. return 0;
  3064. IDirect3DSurface9 *surface = 0;
  3065. /// Check if result is cached
  3066. ZBufferIdentifier zBufferIdentifer;
  3067. zBufferIdentifer.format = dsfmt;
  3068. zBufferIdentifer.multisampleType = multisample;
  3069. zBufferIdentifer.device = getActiveD3D9Device();
  3070. ZBufferRefQueue& zBuffers = mZBufferHash[zBufferIdentifer];
  3071. if(!zBuffers.empty())
  3072. {
  3073. const ZBufferRef& zBuffer = zBuffers.front();
  3074. /// Check if size is larger or equal
  3075. if(zBuffer.width >= width && zBuffer.height >= height)
  3076. {
  3077. surface = zBuffer.surface;
  3078. }
  3079. else
  3080. {
  3081. /// If not, destroy current buffer
  3082. zBuffer.surface->Release();
  3083. zBuffers.pop_front();
  3084. }
  3085. }
  3086. if(!surface)
  3087. {
  3088. /// If not, create the depthstencil surface
  3089. HRESULT hr = getActiveD3D9Device()->CreateDepthStencilSurface(
  3090. static_cast<UINT>(width),
  3091. static_cast<UINT>(height),
  3092. dsfmt,
  3093. multisample,
  3094. multisample_quality,
  3095. TRUE, // discard true or false?
  3096. &surface,
  3097. NULL);
  3098. if(FAILED(hr))
  3099. {
  3100. String msg = DXGetErrorDescription(hr);
  3101. CM_EXCEPT(InvalidParametersException, "Error CreateDepthStencilSurface : " + msg);
  3102. }
  3103. /// And cache it
  3104. ZBufferRef zb;
  3105. zb.surface = surface;
  3106. zb.width = width;
  3107. zb.height = height;
  3108. zBuffers.push_front(zb);
  3109. }
  3110. return surface;
  3111. }
  3112. //---------------------------------------------------------------------
  3113. void D3D9RenderSystem::_cleanupDepthStencils(IDirect3DDevice9* d3d9Device)
  3114. {
  3115. for(ZBufferHash::iterator i = mZBufferHash.begin(); i != mZBufferHash.end();)
  3116. {
  3117. /// Release buffer
  3118. if (i->first.device == d3d9Device)
  3119. {
  3120. while (!i->second.empty())
  3121. {
  3122. IDirect3DSurface9* surface = i->second.front().surface;
  3123. surface->Release();
  3124. i->second.pop_front();
  3125. }
  3126. ZBufferHash::iterator deadi = i++;
  3127. mZBufferHash.erase(deadi);
  3128. }
  3129. else
  3130. {
  3131. ++i;
  3132. }
  3133. }
  3134. }
  3135. //---------------------------------------------------------------------
  3136. void D3D9RenderSystem::registerThread()
  3137. {
  3138. // nothing to do - D3D9 shares rendering context already
  3139. }
  3140. //---------------------------------------------------------------------
  3141. void D3D9RenderSystem::unregisterThread()
  3142. {
  3143. // nothing to do - D3D9 shares rendering context already
  3144. }
  3145. //---------------------------------------------------------------------
  3146. void D3D9RenderSystem::preExtraThreadsStarted()
  3147. {
  3148. // nothing to do - D3D9 shares rendering context already
  3149. }
  3150. //---------------------------------------------------------------------
  3151. void D3D9RenderSystem::postExtraThreadsStarted()
  3152. {
  3153. // nothing to do - D3D9 shares rendering context already
  3154. }
  3155. //---------------------------------------------------------------------
  3156. D3D9ResourceManager* D3D9RenderSystem::getResourceManager()
  3157. {
  3158. return msD3D9RenderSystem->mResourceManager;
  3159. }
  3160. //---------------------------------------------------------------------
  3161. D3D9DeviceManager* D3D9RenderSystem::getDeviceManager()
  3162. {
  3163. return msD3D9RenderSystem->mDeviceManager;
  3164. }
  3165. //---------------------------------------------------------------------
  3166. RenderSystemCapabilities* D3D9RenderSystem::createRenderSystemCapabilities() const
  3167. {
  3168. return mRealCapabilities;
  3169. }
  3170. //---------------------------------------------------------------------
  3171. unsigned int D3D9RenderSystem::getDisplayMonitorCount() const
  3172. {
  3173. return mpD3D->GetAdapterCount();
  3174. }
  3175. //---------------------------------------------------------------------
  3176. void D3D9RenderSystem::notifyOnDeviceLost(D3D9Device* device)
  3177. {
  3178. // you need to stop the physics or game engines after this event
  3179. fireEvent("DeviceLost");
  3180. }
  3181. //---------------------------------------------------------------------
  3182. void D3D9RenderSystem::notifyOnDeviceReset(D3D9Device* device)
  3183. {
  3184. // Reset state attributes.
  3185. mVertexProgramBound = false;
  3186. mFragmentProgramBound = false;
  3187. mLastVertexSourceCount = 0;
  3188. // Restore previous active device.
  3189. // Invalidate active view port.
  3190. mActiveViewport = NULL;
  3191. // Reset the texture stages, they will need to be rebound
  3192. for (size_t i = 0; i < CM_MAX_TEXTURE_LAYERS; ++i)
  3193. _setTexture(i, false, TexturePtr());
  3194. fireEvent("DeviceRestored");
  3195. }
  3196. //---------------------------------------------------------------------
  3197. bool D3D9RenderSystem::ZBufferIdentifierComparator::operator()( const ZBufferIdentifier& z0, const ZBufferIdentifier& z1 ) const
  3198. {
  3199. if (z0.device < z1.device)
  3200. return true;
  3201. if (z0.device == z1.device)
  3202. {
  3203. if (z0.format < z1.format)
  3204. return true;
  3205. if (z0.format == z1.format)
  3206. {
  3207. if (z0.multisampleType < z1.multisampleType)
  3208. return true;
  3209. }
  3210. }
  3211. return false;
  3212. }
  3213. //---------------------------------------------------------------------
  3214. void D3D9RenderSystem::determineFSAASettings(IDirect3DDevice9* d3d9Device,
  3215. size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat,
  3216. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality)
  3217. {
  3218. bool ok = false;
  3219. bool qualityHint = fsaaHint.find("Quality") != String::npos;
  3220. size_t origFSAA = fsaa;
  3221. D3D9DriverList* driverList = getDirect3DDrivers();
  3222. D3D9Driver* deviceDriver = mActiveD3DDriver;
  3223. D3D9Device* device = mDeviceManager->getDeviceFromD3D9Device(d3d9Device);
  3224. for (UINT32 i = 0; i < driverList->count(); ++i)
  3225. {
  3226. D3D9Driver* currDriver = driverList->item(i);
  3227. if (currDriver->getAdapterNumber() == device->getAdapterNumber())
  3228. {
  3229. deviceDriver = currDriver;
  3230. break;
  3231. }
  3232. }
  3233. bool tryCSAA = false;
  3234. // NVIDIA, prefer CSAA if available for 8+
  3235. // it would be tempting to use getCapabilities()->getVendor() == GPU_NVIDIA but
  3236. // if this is the first window, caps will not be initialised yet
  3237. if (deviceDriver->getAdapterIdentifier().VendorId == 0x10DE &&
  3238. fsaa >= 8)
  3239. {
  3240. tryCSAA = true;
  3241. }
  3242. while (!ok)
  3243. {
  3244. // Deal with special cases
  3245. if (tryCSAA)
  3246. {
  3247. // see http://developer.nvidia.com/object/coverage-sampled-aa.html
  3248. switch(fsaa)
  3249. {
  3250. case 8:
  3251. if (qualityHint)
  3252. {
  3253. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  3254. *outMultisampleQuality = 0;
  3255. }
  3256. else
  3257. {
  3258. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  3259. *outMultisampleQuality = 2;
  3260. }
  3261. break;
  3262. case 16:
  3263. if (qualityHint)
  3264. {
  3265. *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES;
  3266. *outMultisampleQuality = 2;
  3267. }
  3268. else
  3269. {
  3270. *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES;
  3271. *outMultisampleQuality = 4;
  3272. }
  3273. break;
  3274. }
  3275. }
  3276. else // !CSAA
  3277. {
  3278. *outMultisampleType = (D3DMULTISAMPLE_TYPE)fsaa;
  3279. *outMultisampleQuality = 0;
  3280. }
  3281. HRESULT hr;
  3282. DWORD outQuality;
  3283. hr = mpD3D->CheckDeviceMultiSampleType(
  3284. deviceDriver->getAdapterNumber(),
  3285. D3DDEVTYPE_HAL,
  3286. d3dPixelFormat,
  3287. fullScreen,
  3288. *outMultisampleType,
  3289. &outQuality);
  3290. if (SUCCEEDED(hr) &&
  3291. (!tryCSAA || outQuality > *outMultisampleQuality))
  3292. {
  3293. ok = true;
  3294. }
  3295. else
  3296. {
  3297. // downgrade
  3298. if (tryCSAA && fsaa == 8)
  3299. {
  3300. // for CSAA, we'll try downgrading with quality mode at all samples.
  3301. // then try without quality, then drop CSAA
  3302. if (qualityHint)
  3303. {
  3304. // drop quality first
  3305. qualityHint = false;
  3306. }
  3307. else
  3308. {
  3309. // drop CSAA entirely
  3310. tryCSAA = false;
  3311. }
  3312. // return to original requested samples
  3313. fsaa = origFSAA;
  3314. }
  3315. else
  3316. {
  3317. // drop samples
  3318. --fsaa;
  3319. if (fsaa == 1)
  3320. {
  3321. // ran out of options, no FSAA
  3322. fsaa = 0;
  3323. ok = true;
  3324. }
  3325. }
  3326. }
  3327. } // while !ok
  3328. }
  3329. }