renderer_d3d9.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if BGFX_CONFIG_RENDERER_DIRECT3D9
  7. # include "renderer_d3d9.h"
  8. namespace bgfx { namespace d3d9
  9. {
  10. static wchar_t s_viewNameW[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  11. struct PrimInfo
  12. {
  13. D3DPRIMITIVETYPE m_type;
  14. uint32_t m_min;
  15. uint32_t m_div;
  16. uint32_t m_sub;
  17. };
  18. static const PrimInfo s_primInfo[] =
  19. {
  20. { D3DPT_TRIANGLELIST, 3, 3, 0 },
  21. { D3DPT_TRIANGLESTRIP, 3, 1, 2 },
  22. { D3DPT_LINELIST, 2, 2, 0 },
  23. { D3DPT_LINESTRIP, 2, 1, 1 },
  24. { D3DPT_POINTLIST, 1, 1, 0 },
  25. { D3DPRIMITIVETYPE(0), 0, 0, 0 },
  26. };
  27. static const char* s_primName[] =
  28. {
  29. "TriList",
  30. "TriStrip",
  31. "Line",
  32. "LineStrip",
  33. "Point",
  34. };
  35. BX_STATIC_ASSERT(BX_COUNTOF(s_primInfo) == BX_COUNTOF(s_primName)+1);
  36. static const D3DMULTISAMPLE_TYPE s_checkMsaa[] =
  37. {
  38. D3DMULTISAMPLE_NONE,
  39. D3DMULTISAMPLE_2_SAMPLES,
  40. D3DMULTISAMPLE_4_SAMPLES,
  41. D3DMULTISAMPLE_8_SAMPLES,
  42. D3DMULTISAMPLE_16_SAMPLES,
  43. };
  44. static Msaa s_msaa[] =
  45. {
  46. { D3DMULTISAMPLE_NONE, 0 },
  47. { D3DMULTISAMPLE_2_SAMPLES, 0 },
  48. { D3DMULTISAMPLE_4_SAMPLES, 0 },
  49. { D3DMULTISAMPLE_8_SAMPLES, 0 },
  50. { D3DMULTISAMPLE_16_SAMPLES, 0 },
  51. };
  52. struct Blend
  53. {
  54. D3DBLEND m_src;
  55. D3DBLEND m_dst;
  56. bool m_factor;
  57. };
  58. static const Blend s_blendFactor[] =
  59. {
  60. { (D3DBLEND)0, (D3DBLEND)0, false }, // ignored
  61. { D3DBLEND_ZERO, D3DBLEND_ZERO, false }, // ZERO
  62. { D3DBLEND_ONE, D3DBLEND_ONE, false }, // ONE
  63. { D3DBLEND_SRCCOLOR, D3DBLEND_SRCCOLOR, false }, // SRC_COLOR
  64. { D3DBLEND_INVSRCCOLOR, D3DBLEND_INVSRCCOLOR, false }, // INV_SRC_COLOR
  65. { D3DBLEND_SRCALPHA, D3DBLEND_SRCALPHA, false }, // SRC_ALPHA
  66. { D3DBLEND_INVSRCALPHA, D3DBLEND_INVSRCALPHA, false }, // INV_SRC_ALPHA
  67. { D3DBLEND_DESTALPHA, D3DBLEND_DESTALPHA, false }, // DST_ALPHA
  68. { D3DBLEND_INVDESTALPHA, D3DBLEND_INVDESTALPHA, false }, // INV_DST_ALPHA
  69. { D3DBLEND_DESTCOLOR, D3DBLEND_DESTCOLOR, false }, // DST_COLOR
  70. { D3DBLEND_INVDESTCOLOR, D3DBLEND_INVDESTCOLOR, false }, // INV_DST_COLOR
  71. { D3DBLEND_SRCALPHASAT, D3DBLEND_ONE, false }, // SRC_ALPHA_SAT
  72. { D3DBLEND_BLENDFACTOR, D3DBLEND_BLENDFACTOR, true }, // FACTOR
  73. { D3DBLEND_INVBLENDFACTOR, D3DBLEND_INVBLENDFACTOR, true }, // INV_FACTOR
  74. };
  75. static const D3DBLENDOP s_blendEquation[] =
  76. {
  77. D3DBLENDOP_ADD,
  78. D3DBLENDOP_SUBTRACT,
  79. D3DBLENDOP_REVSUBTRACT,
  80. D3DBLENDOP_MIN,
  81. D3DBLENDOP_MAX,
  82. };
  83. static const D3DCMPFUNC s_cmpFunc[] =
  84. {
  85. (D3DCMPFUNC)0, // ignored
  86. D3DCMP_LESS,
  87. D3DCMP_LESSEQUAL,
  88. D3DCMP_EQUAL,
  89. D3DCMP_GREATEREQUAL,
  90. D3DCMP_GREATER,
  91. D3DCMP_NOTEQUAL,
  92. D3DCMP_NEVER,
  93. D3DCMP_ALWAYS,
  94. };
  95. static const D3DSTENCILOP s_stencilOp[] =
  96. {
  97. D3DSTENCILOP_ZERO,
  98. D3DSTENCILOP_KEEP,
  99. D3DSTENCILOP_REPLACE,
  100. D3DSTENCILOP_INCR,
  101. D3DSTENCILOP_INCRSAT,
  102. D3DSTENCILOP_DECR,
  103. D3DSTENCILOP_DECRSAT,
  104. D3DSTENCILOP_INVERT,
  105. };
  106. static const D3DRENDERSTATETYPE s_stencilFuncRs[] =
  107. {
  108. D3DRS_STENCILFUNC,
  109. D3DRS_CCW_STENCILFUNC,
  110. };
  111. static const D3DRENDERSTATETYPE s_stencilFailRs[] =
  112. {
  113. D3DRS_STENCILFAIL,
  114. D3DRS_CCW_STENCILFAIL,
  115. };
  116. static const D3DRENDERSTATETYPE s_stencilZFailRs[] =
  117. {
  118. D3DRS_STENCILZFAIL,
  119. D3DRS_CCW_STENCILZFAIL,
  120. };
  121. static const D3DRENDERSTATETYPE s_stencilZPassRs[] =
  122. {
  123. D3DRS_STENCILPASS,
  124. D3DRS_CCW_STENCILPASS,
  125. };
  126. static const D3DCULL s_cullMode[] =
  127. {
  128. D3DCULL_NONE,
  129. D3DCULL_CW,
  130. D3DCULL_CCW,
  131. };
  132. static const D3DTEXTUREADDRESS s_textureAddress[] =
  133. {
  134. D3DTADDRESS_WRAP,
  135. D3DTADDRESS_MIRROR,
  136. D3DTADDRESS_CLAMP,
  137. D3DTADDRESS_BORDER,
  138. };
  139. static const D3DTEXTUREFILTERTYPE s_textureFilter[] =
  140. {
  141. D3DTEXF_LINEAR,
  142. D3DTEXF_POINT,
  143. D3DTEXF_ANISOTROPIC,
  144. };
  145. struct TextureFormatInfo
  146. {
  147. D3DFORMAT m_fmt;
  148. };
  149. static TextureFormatInfo s_textureFormat[] =
  150. {
  151. { D3DFMT_DXT1 }, // BC1
  152. { D3DFMT_DXT3 }, // BC2
  153. { D3DFMT_DXT5 }, // BC3
  154. { D3DFMT_UNKNOWN }, // BC4
  155. { D3DFMT_UNKNOWN }, // BC5
  156. { D3DFMT_UNKNOWN }, // BC6H
  157. { D3DFMT_UNKNOWN }, // BC7
  158. { D3DFMT_UNKNOWN }, // ETC1
  159. { D3DFMT_UNKNOWN }, // ETC2
  160. { D3DFMT_UNKNOWN }, // ETC2A
  161. { D3DFMT_UNKNOWN }, // ETC2A1
  162. { D3DFMT_UNKNOWN }, // PTC12
  163. { D3DFMT_UNKNOWN }, // PTC14
  164. { D3DFMT_UNKNOWN }, // PTC12A
  165. { D3DFMT_UNKNOWN }, // PTC14A
  166. { D3DFMT_UNKNOWN }, // PTC22
  167. { D3DFMT_UNKNOWN }, // PTC24
  168. { D3DFMT_UNKNOWN }, // Unknown
  169. { D3DFMT_A1 }, // R1
  170. { D3DFMT_A8 }, // A8
  171. { D3DFMT_L8 }, // R8
  172. { D3DFMT_UNKNOWN }, // R8I
  173. { D3DFMT_UNKNOWN }, // R8U
  174. { D3DFMT_UNKNOWN }, // R8S
  175. { D3DFMT_L16 }, // R16
  176. { D3DFMT_UNKNOWN }, // R16I
  177. { D3DFMT_UNKNOWN }, // R16U
  178. { D3DFMT_R16F }, // R16F
  179. { D3DFMT_UNKNOWN }, // R16S
  180. { D3DFMT_UNKNOWN }, // R32I
  181. { D3DFMT_UNKNOWN }, // R32U
  182. { D3DFMT_R32F }, // R32F
  183. { D3DFMT_A8L8 }, // RG8
  184. { D3DFMT_UNKNOWN }, // RG8I
  185. { D3DFMT_UNKNOWN }, // RG8U
  186. { D3DFMT_UNKNOWN }, // RG8S
  187. { D3DFMT_G16R16 }, // RG16
  188. { D3DFMT_UNKNOWN }, // RG16I
  189. { D3DFMT_UNKNOWN }, // RG16U
  190. { D3DFMT_G16R16F }, // RG16F
  191. { D3DFMT_UNKNOWN }, // RG16S
  192. { D3DFMT_UNKNOWN }, // RG32I
  193. { D3DFMT_UNKNOWN }, // RG32U
  194. { D3DFMT_G32R32F }, // RG32F
  195. { D3DFMT_UNKNOWN }, // RGB9E5F
  196. { D3DFMT_A8R8G8B8 }, // BGRA8
  197. { D3DFMT_UNKNOWN }, // RGBA8
  198. { D3DFMT_UNKNOWN }, // RGBA8I
  199. { D3DFMT_UNKNOWN }, // RGBA8U
  200. { D3DFMT_UNKNOWN }, // RGBA8S
  201. { D3DFMT_A16B16G16R16 }, // RGBA16
  202. { D3DFMT_UNKNOWN }, // RGBA16I
  203. { D3DFMT_UNKNOWN }, // RGBA16U
  204. { D3DFMT_A16B16G16R16F }, // RGBA16F
  205. { D3DFMT_UNKNOWN }, // RGBA16S
  206. { D3DFMT_UNKNOWN }, // RGBA32I
  207. { D3DFMT_UNKNOWN }, // RGBA32U
  208. { D3DFMT_A32B32G32R32F }, // RGBA32F
  209. { D3DFMT_R5G6B5 }, // R5G6B5
  210. { D3DFMT_A4R4G4B4 }, // RGBA4
  211. { D3DFMT_A1R5G5B5 }, // RGB5A1
  212. { D3DFMT_A2B10G10R10 }, // RGB10A2
  213. { D3DFMT_UNKNOWN }, // R11G11B10F
  214. { D3DFMT_UNKNOWN }, // UnknownDepth
  215. { D3DFMT_D16 }, // D16
  216. { D3DFMT_D24X8 }, // D24
  217. { D3DFMT_D24S8 }, // D24S8
  218. { D3DFMT_D32 }, // D32
  219. { D3DFMT_DF16 }, // D16F
  220. { D3DFMT_DF24 }, // D24F
  221. { D3DFMT_D32F_LOCKABLE }, // D32F
  222. { D3DFMT_S8_LOCKABLE }, // D0S8
  223. };
  224. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  225. static ExtendedFormat s_extendedFormats[ExtendedFormat::Count] =
  226. {
  227. { D3DFMT_ATI1, 0, D3DRTYPE_TEXTURE, false },
  228. { D3DFMT_ATI2, 0, D3DRTYPE_TEXTURE, false },
  229. { D3DFMT_DF16, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  230. { D3DFMT_DF24, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  231. { D3DFMT_INST, 0, D3DRTYPE_SURFACE, false },
  232. { D3DFMT_INTZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  233. { D3DFMT_NULL, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  234. { D3DFMT_RESZ, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  235. { D3DFMT_RAWZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  236. };
  237. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  238. static const GUID IID_IDirect3D9 = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } };
  239. static const GUID IID_IDirect3DDevice9Ex = { 0xb18b10ce, 0x2649, 0x405a, { 0x87, 0xf, 0x95, 0xf7, 0x77, 0xd4, 0x31, 0x3a } };
  240. typedef HRESULT (WINAPI *Direct3DCreate9ExFn)(UINT SDKVersion, IDirect3D9Ex**);
  241. static Direct3DCreate9ExFn Direct3DCreate9Ex;
  242. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  243. typedef IDirect3D9* (WINAPI *Direct3DCreate9Fn)(UINT SDKVersion);
  244. static Direct3DCreate9Fn Direct3DCreate9;
  245. static PFN_D3DPERF_SET_MARKER D3DPERF_SetMarker;
  246. static PFN_D3DPERF_BEGIN_EVENT D3DPERF_BeginEvent;
  247. static PFN_D3DPERF_END_EVENT D3DPERF_EndEvent;
  248. struct RendererContextD3D9 : public RendererContextI
  249. {
  250. RendererContextD3D9()
  251. : m_d3d9(NULL)
  252. , m_device(NULL)
  253. , m_flushQuery(NULL)
  254. , m_swapChain(NULL)
  255. , m_captureTexture(NULL)
  256. , m_captureSurface(NULL)
  257. , m_captureResolve(NULL)
  258. , m_flags(BGFX_RESET_NONE)
  259. , m_maxAnisotropy(1)
  260. , m_initialized(false)
  261. , m_amd(false)
  262. , m_nvidia(false)
  263. , m_instancingSupport(false)
  264. , m_timerQuerySupport(false)
  265. , m_rtMsaa(false)
  266. {
  267. }
  268. ~RendererContextD3D9()
  269. {
  270. }
  271. bool init()
  272. {
  273. struct ErrorState
  274. {
  275. enum Enum
  276. {
  277. Default,
  278. LoadedD3D9,
  279. CreatedD3D9,
  280. CreatedDevice,
  281. };
  282. };
  283. ErrorState::Enum errorState = ErrorState::Default;
  284. m_fbh.idx = invalidHandle;
  285. memset(m_uniforms, 0, sizeof(m_uniforms) );
  286. memset(&m_resolution, 0, sizeof(m_resolution) );
  287. D3DFORMAT adapterFormat = D3DFMT_X8R8G8B8;
  288. // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172588%28v=vs.85%29.aspx
  289. memset(&m_params, 0, sizeof(m_params) );
  290. m_params.BackBufferWidth = BGFX_DEFAULT_WIDTH;
  291. m_params.BackBufferHeight = BGFX_DEFAULT_HEIGHT;
  292. m_params.BackBufferFormat = adapterFormat;
  293. m_params.BackBufferCount = 1;
  294. m_params.MultiSampleType = D3DMULTISAMPLE_NONE;
  295. m_params.MultiSampleQuality = 0;
  296. m_params.EnableAutoDepthStencil = TRUE;
  297. m_params.AutoDepthStencilFormat = D3DFMT_D24S8;
  298. m_params.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
  299. #if BX_PLATFORM_WINDOWS
  300. m_params.FullScreen_RefreshRateInHz = 0;
  301. m_params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  302. m_params.SwapEffect = D3DSWAPEFFECT_DISCARD;
  303. m_params.hDeviceWindow = NULL;
  304. m_params.Windowed = true;
  305. RECT rect;
  306. GetWindowRect( (HWND)g_platformData.nwh, &rect);
  307. m_params.BackBufferWidth = rect.right-rect.left;
  308. m_params.BackBufferHeight = rect.bottom-rect.top;
  309. m_d3d9dll = bx::dlopen("d3d9.dll");
  310. BX_WARN(NULL != m_d3d9dll, "Failed to load d3d9.dll.");
  311. if (NULL == m_d3d9dll)
  312. {
  313. goto error;
  314. }
  315. errorState = ErrorState::LoadedD3D9;
  316. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  317. {
  318. D3DPERF_SetMarker = (PFN_D3DPERF_SET_MARKER )bx::dlsym(m_d3d9dll, "D3DPERF_SetMarker");
  319. D3DPERF_BeginEvent = (PFN_D3DPERF_BEGIN_EVENT)bx::dlsym(m_d3d9dll, "D3DPERF_BeginEvent");
  320. D3DPERF_EndEvent = (PFN_D3DPERF_END_EVENT )bx::dlsym(m_d3d9dll, "D3DPERF_EndEvent");
  321. BX_CHECK(NULL != D3DPERF_SetMarker
  322. && NULL != D3DPERF_BeginEvent
  323. && NULL != D3DPERF_EndEvent
  324. , "Failed to initialize PIX events."
  325. );
  326. }
  327. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  328. m_d3d9ex = NULL;
  329. Direct3DCreate9Ex = (Direct3DCreate9ExFn)bx::dlsym(m_d3d9dll, "Direct3DCreate9Ex");
  330. if (NULL != Direct3DCreate9Ex)
  331. {
  332. Direct3DCreate9Ex(D3D_SDK_VERSION, &m_d3d9ex);
  333. DX_CHECK(m_d3d9ex->QueryInterface(IID_IDirect3D9, (void**)&m_d3d9) );
  334. m_pool = D3DPOOL_DEFAULT;
  335. }
  336. else
  337. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  338. {
  339. Direct3DCreate9 = (Direct3DCreate9Fn)bx::dlsym(m_d3d9dll, "Direct3DCreate9");
  340. BX_WARN(NULL != Direct3DCreate9, "Function Direct3DCreate9 not found.");
  341. if (NULL == Direct3DCreate9)
  342. {
  343. goto error;
  344. }
  345. m_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  346. m_pool = D3DPOOL_MANAGED;
  347. }
  348. BX_WARN(NULL != m_d3d9, "Unable to create Direct3D.");
  349. if (NULL == m_d3d9)
  350. {
  351. goto error;
  352. }
  353. errorState = ErrorState::CreatedD3D9;
  354. {
  355. m_adapter = D3DADAPTER_DEFAULT;
  356. m_deviceType = BGFX_PCI_ID_SOFTWARE_RASTERIZER == g_caps.vendorId
  357. ? D3DDEVTYPE_REF
  358. : D3DDEVTYPE_HAL
  359. ;
  360. uint8_t numGPUs = uint8_t(bx::uint32_min(BX_COUNTOF(g_caps.gpu), m_d3d9->GetAdapterCount() ) );
  361. for (uint32_t ii = 0; ii < numGPUs; ++ii)
  362. {
  363. D3DADAPTER_IDENTIFIER9 desc;
  364. HRESULT hr = m_d3d9->GetAdapterIdentifier(ii, 0, &desc);
  365. if (SUCCEEDED(hr) )
  366. {
  367. BX_TRACE("Adapter #%d", ii);
  368. BX_TRACE("\tDriver: %s", desc.Driver);
  369. BX_TRACE("\tDescription: %s", desc.Description);
  370. BX_TRACE("\tDeviceName: %s", desc.DeviceName);
  371. BX_TRACE("\tVendorId: 0x%08x, DeviceId: 0x%08x, SubSysId: 0x%08x, Revision: 0x%08x"
  372. , desc.VendorId
  373. , desc.DeviceId
  374. , desc.SubSysId
  375. , desc.Revision
  376. );
  377. g_caps.gpu[ii].vendorId = (uint16_t)desc.VendorId;
  378. g_caps.gpu[ii].deviceId = (uint16_t)desc.DeviceId;
  379. if (D3DADAPTER_DEFAULT == m_adapter)
  380. {
  381. if ( (BGFX_PCI_ID_NONE != g_caps.vendorId || 0 != g_caps.deviceId)
  382. && (BGFX_PCI_ID_NONE == g_caps.vendorId || desc.VendorId == g_caps.vendorId)
  383. && ( 0 == g_caps.deviceId || desc.DeviceId == g_caps.deviceId) )
  384. {
  385. m_adapter = ii;
  386. }
  387. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PERFHUD)
  388. && 0 != strstr(desc.Description, "PerfHUD") )
  389. {
  390. m_adapter = ii;
  391. m_deviceType = D3DDEVTYPE_REF;
  392. }
  393. }
  394. }
  395. }
  396. DX_CHECK(m_d3d9->GetAdapterIdentifier(m_adapter, 0, &m_identifier) );
  397. m_amd = m_identifier.VendorId == BGFX_PCI_ID_AMD;
  398. m_nvidia = m_identifier.VendorId == BGFX_PCI_ID_NVIDIA;
  399. g_caps.vendorId = 0 == m_identifier.VendorId
  400. ? BGFX_PCI_ID_SOFTWARE_RASTERIZER
  401. : (uint16_t)m_identifier.VendorId
  402. ;
  403. g_caps.deviceId = (uint16_t)m_identifier.DeviceId;
  404. uint32_t behaviorFlags[] =
  405. {
  406. D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE | D3DCREATE_PUREDEVICE,
  407. D3DCREATE_MIXED_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
  408. D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
  409. };
  410. for (uint32_t ii = 0; ii < BX_COUNTOF(behaviorFlags) && NULL == m_device; ++ii)
  411. {
  412. #if 0 // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  413. DX_CHECK(m_d3d9->CreateDeviceEx(m_adapter
  414. , m_deviceType
  415. , g_platformHooks.nwh
  416. , behaviorFlags[ii]
  417. , &m_params
  418. , NULL
  419. , &m_device
  420. ) );
  421. #else
  422. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  423. , m_deviceType
  424. , (HWND)g_platformData.nwh
  425. , behaviorFlags[ii]
  426. , &m_params
  427. , &m_device
  428. ));
  429. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  430. }
  431. }
  432. BX_WARN(NULL != m_device, "Unable to create Direct3D9 device.");
  433. if (NULL == m_device)
  434. {
  435. goto error;
  436. }
  437. errorState = ErrorState::CreatedDevice;
  438. m_numWindows = 1;
  439. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  440. if (NULL != m_d3d9ex)
  441. {
  442. DX_CHECK(m_device->QueryInterface(IID_IDirect3DDevice9Ex, (void**)&m_deviceEx) );
  443. }
  444. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  445. DX_CHECK(m_device->GetDeviceCaps(&m_caps) );
  446. // For shit GPUs that can create DX9 device but can't do simple stuff. GTFO!
  447. BX_WARN( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) == 0, "D3DPTEXTURECAPS_SQUAREONLY");
  448. BX_WARN( (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) == D3DPTEXTURECAPS_MIPMAP, "D3DPTEXTURECAPS_MIPMAP");
  449. BX_WARN( (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) == D3DPTEXTURECAPS_ALPHA, "D3DPTEXTURECAPS_ALPHA");
  450. BX_WARN(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1)
  451. , "Shader Model Version (vs: %x, ps: %x)."
  452. , m_caps.VertexShaderVersion
  453. , m_caps.PixelShaderVersion
  454. );
  455. if ( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) != 0
  456. || (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) != D3DPTEXTURECAPS_MIPMAP
  457. || (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) != D3DPTEXTURECAPS_ALPHA
  458. || !(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1) ) )
  459. {
  460. goto error;
  461. }
  462. BX_TRACE("Max vertex shader 3.0 instr. slots: %d", m_caps.MaxVertexShader30InstructionSlots);
  463. BX_TRACE("Max vertex shader constants: %d", m_caps.MaxVertexShaderConst);
  464. BX_TRACE("Max fragment shader 2.0 instr. slots: %d", m_caps.PS20Caps.NumInstructionSlots);
  465. BX_TRACE("Max fragment shader 3.0 instr. slots: %d", m_caps.MaxPixelShader30InstructionSlots);
  466. BX_TRACE("Num simultaneous render targets: %d", m_caps.NumSimultaneousRTs);
  467. BX_TRACE("Max vertex index: %d", m_caps.MaxVertexIndex);
  468. g_caps.supported |= ( 0
  469. | BGFX_CAPS_TEXTURE_3D
  470. | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  471. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  472. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  473. | BGFX_CAPS_FRAGMENT_DEPTH
  474. | BGFX_CAPS_SWAP_CHAIN
  475. | ( (UINT16_MAX < m_caps.MaxVertexIndex) ? BGFX_CAPS_INDEX32 : 0)
  476. | ( (m_caps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) ? BGFX_CAPS_BLIT : 0)
  477. );
  478. g_caps.maxTextureSize = uint16_t(bx::uint32_min(m_caps.MaxTextureWidth, m_caps.MaxTextureHeight) );
  479. // g_caps.maxVertexIndex = m_caps.MaxVertexIndex;
  480. m_caps.NumSimultaneousRTs = uint8_t(bx::uint32_min(m_caps.NumSimultaneousRTs, BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS) );
  481. g_caps.maxFBAttachments = uint8_t(m_caps.NumSimultaneousRTs);
  482. m_caps.MaxAnisotropy = bx::uint32_max(m_caps.MaxAnisotropy, 1);
  483. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  484. {
  485. BX_TRACE("Extended formats:");
  486. for (uint32_t ii = 0; ii < ExtendedFormat::Count; ++ii)
  487. {
  488. ExtendedFormat& fmt = s_extendedFormats[ii];
  489. fmt.m_supported = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, fmt.m_usage, fmt.m_type, fmt.m_fmt) );
  490. const char* fourcc = (const char*)&fmt.m_fmt;
  491. BX_TRACE("\t%2d: %c%c%c%c %s", ii, fourcc[0], fourcc[1], fourcc[2], fourcc[3], fmt.m_supported ? "supported" : "");
  492. BX_UNUSED(fourcc);
  493. }
  494. m_instancingSupport = false
  495. || s_extendedFormats[ExtendedFormat::Inst].m_supported
  496. || (m_caps.VertexShaderVersion >= D3DVS_VERSION(3, 0) )
  497. ;
  498. if (m_amd
  499. && s_extendedFormats[ExtendedFormat::Inst].m_supported)
  500. { // AMD only
  501. m_device->SetRenderState(D3DRS_POINTSIZE, D3DFMT_INST);
  502. }
  503. if (s_extendedFormats[ExtendedFormat::Intz].m_supported)
  504. {
  505. s_textureFormat[TextureFormat::D24].m_fmt = D3DFMT_INTZ;
  506. s_textureFormat[TextureFormat::D32].m_fmt = D3DFMT_INTZ;
  507. }
  508. s_textureFormat[TextureFormat::BC4].m_fmt = s_extendedFormats[ExtendedFormat::Ati1].m_supported ? D3DFMT_ATI1 : D3DFMT_UNKNOWN;
  509. s_textureFormat[TextureFormat::BC5].m_fmt = s_extendedFormats[ExtendedFormat::Ati2].m_supported ? D3DFMT_ATI2 : D3DFMT_UNKNOWN;
  510. g_caps.supported |= m_instancingSupport ? BGFX_CAPS_INSTANCING : 0;
  511. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  512. {
  513. uint8_t support = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  514. , m_deviceType
  515. , adapterFormat
  516. , 0
  517. , D3DRTYPE_TEXTURE
  518. , s_textureFormat[ii].m_fmt
  519. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_COLOR : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  520. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  521. , m_deviceType
  522. , adapterFormat
  523. , D3DUSAGE_QUERY_SRGBREAD
  524. , D3DRTYPE_TEXTURE
  525. , s_textureFormat[ii].m_fmt
  526. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_COLOR_SRGB : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  527. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  528. , m_deviceType
  529. , adapterFormat
  530. , D3DUSAGE_QUERY_VERTEXTEXTURE
  531. , D3DRTYPE_TEXTURE
  532. , s_textureFormat[ii].m_fmt
  533. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_VERTEX : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  534. support |= SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter
  535. , m_deviceType
  536. , adapterFormat
  537. , isDepth(TextureFormat::Enum(ii) ) ? D3DUSAGE_DEPTHSTENCIL : D3DUSAGE_RENDERTARGET
  538. , D3DRTYPE_TEXTURE
  539. , s_textureFormat[ii].m_fmt
  540. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  541. support |= SUCCEEDED(m_d3d9->CheckDeviceMultiSampleType(m_adapter
  542. , m_deviceType
  543. , s_textureFormat[ii].m_fmt
  544. , true
  545. , D3DMULTISAMPLE_2_SAMPLES
  546. , NULL
  547. ) ) ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA : BGFX_CAPS_FORMAT_TEXTURE_NONE;
  548. g_caps.formats[ii] = support;
  549. }
  550. }
  551. m_fmtDepth = D3DFMT_D24S8;
  552. #elif BX_PLATFORM_XBOX360
  553. m_params.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  554. m_params.DisableAutoBackBuffer = FALSE;
  555. m_params.DisableAutoFrontBuffer = FALSE;
  556. m_params.FrontBufferFormat = D3DFMT_X8R8G8B8;
  557. m_params.FrontBufferColorSpace = D3DCOLORSPACE_RGB;
  558. m_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  559. BX_TRACE("Creating D3D9 %p", m_d3d9);
  560. XVIDEO_MODE videoMode;
  561. XGetVideoMode(&videoMode);
  562. if (!videoMode.fIsWideScreen)
  563. {
  564. m_params.Flags |= D3DPRESENTFLAG_NO_LETTERBOX;
  565. }
  566. BX_TRACE("Creating device");
  567. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  568. , m_deviceType
  569. , NULL
  570. , D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES
  571. , &m_params
  572. , &m_device
  573. ) );
  574. BX_TRACE("Device %p", m_device);
  575. m_fmtDepth = D3DFMT_D24FS8;
  576. #endif // BX_PLATFORM_WINDOWS
  577. {
  578. IDirect3DQuery9* timerQueryTest[3] = {};
  579. m_timerQuerySupport = true
  580. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_TIMESTAMPDISJOINT, &timerQueryTest[0]) )
  581. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_TIMESTAMP, &timerQueryTest[1]) )
  582. && SUCCEEDED(m_device->CreateQuery(D3DQUERYTYPE_TIMESTAMPFREQ, &timerQueryTest[2]) )
  583. ;
  584. DX_RELEASE(timerQueryTest[0], 0);
  585. DX_RELEASE(timerQueryTest[1], 0);
  586. DX_RELEASE(timerQueryTest[2], 0);
  587. }
  588. {
  589. IDirect3DSwapChain9* swapChain;
  590. DX_CHECK(m_device->GetSwapChain(0, &swapChain) );
  591. // GPA increases swapchain ref count.
  592. //
  593. // This causes assert in debug. When debugger is present refcount
  594. // checks are off.
  595. setGraphicsDebuggerPresent(1 != getRefCount(swapChain) );
  596. DX_RELEASE(swapChain, 0);
  597. }
  598. // Init reserved part of view name.
  599. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  600. {
  601. char name[BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1];
  602. bx::snprintf(name, sizeof(name), "%3d ", ii);
  603. mbstowcs(s_viewNameW[ii], name, BGFX_CONFIG_MAX_VIEW_NAME_RESERVED);
  604. }
  605. postReset();
  606. m_initialized = true;
  607. return true;
  608. error:
  609. switch (errorState)
  610. {
  611. case ErrorState::CreatedDevice:
  612. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  613. if (NULL != m_d3d9ex)
  614. {
  615. DX_RELEASE(m_deviceEx, 1);
  616. DX_RELEASE(m_device, 0);
  617. }
  618. else
  619. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  620. {
  621. DX_RELEASE(m_device, 0);
  622. }
  623. case ErrorState::CreatedD3D9:
  624. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  625. if (NULL != m_d3d9ex)
  626. {
  627. DX_RELEASE(m_d3d9, 1);
  628. DX_RELEASE(m_d3d9ex, 0);
  629. }
  630. else
  631. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  632. {
  633. DX_RELEASE(m_d3d9, 0);
  634. }
  635. #if BX_PLATFORM_WINDOWS
  636. case ErrorState::LoadedD3D9:
  637. bx::dlclose(m_d3d9dll);
  638. #endif // BX_PLATFORM_WINDOWS
  639. case ErrorState::Default:
  640. break;
  641. }
  642. return false;
  643. }
  644. void shutdown()
  645. {
  646. preReset();
  647. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  648. {
  649. m_indexBuffers[ii].destroy();
  650. }
  651. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  652. {
  653. m_vertexBuffers[ii].destroy();
  654. }
  655. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shaders); ++ii)
  656. {
  657. m_shaders[ii].destroy();
  658. }
  659. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  660. {
  661. m_textures[ii].destroy();
  662. }
  663. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexDecls); ++ii)
  664. {
  665. m_vertexDecls[ii].destroy();
  666. }
  667. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  668. if (NULL != m_d3d9ex)
  669. {
  670. DX_RELEASE(m_deviceEx, 1);
  671. DX_RELEASE(m_device, 0);
  672. DX_RELEASE(m_d3d9, 1);
  673. DX_RELEASE(m_d3d9ex, 0);
  674. }
  675. else
  676. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  677. {
  678. DX_RELEASE(m_device, 0);
  679. DX_RELEASE(m_d3d9, 0);
  680. }
  681. #if BX_PLATFORM_WINDOWS
  682. bx::dlclose(m_d3d9dll);
  683. #endif // BX_PLATFORM_WINDOWS
  684. m_initialized = false;
  685. }
  686. RendererType::Enum getRendererType() const BX_OVERRIDE
  687. {
  688. return RendererType::Direct3D9;
  689. }
  690. const char* getRendererName() const BX_OVERRIDE
  691. {
  692. return BGFX_RENDERER_DIRECT3D9_NAME;
  693. }
  694. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) BX_OVERRIDE
  695. {
  696. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  697. }
  698. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  699. {
  700. m_indexBuffers[_handle.idx].destroy();
  701. }
  702. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  703. {
  704. m_vertexDecls[_handle.idx].create(_decl);
  705. }
  706. void destroyVertexDecl(VertexDeclHandle _handle) BX_OVERRIDE
  707. {
  708. m_vertexDecls[_handle.idx].destroy();
  709. }
  710. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t /*_flags*/) BX_OVERRIDE
  711. {
  712. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  713. }
  714. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  715. {
  716. m_vertexBuffers[_handle.idx].destroy();
  717. }
  718. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  719. {
  720. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  721. }
  722. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  723. {
  724. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  725. }
  726. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  727. {
  728. m_indexBuffers[_handle.idx].destroy();
  729. }
  730. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t /*_flags*/) BX_OVERRIDE
  731. {
  732. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  733. m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  734. }
  735. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  736. {
  737. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  738. }
  739. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  740. {
  741. m_vertexBuffers[_handle.idx].destroy();
  742. }
  743. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  744. {
  745. m_shaders[_handle.idx].create(_mem);
  746. }
  747. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  748. {
  749. m_shaders[_handle.idx].destroy();
  750. }
  751. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  752. {
  753. m_program[_handle.idx].create(m_shaders[_vsh.idx], m_shaders[_fsh.idx]);
  754. }
  755. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  756. {
  757. m_program[_handle.idx].destroy();
  758. }
  759. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  760. {
  761. m_textures[_handle.idx].create(_mem, _flags, _skip);
  762. }
  763. void updateTextureBegin(TextureHandle _handle, uint8_t _side, uint8_t _mip) BX_OVERRIDE
  764. {
  765. m_updateTexture = &m_textures[_handle.idx];
  766. m_updateTexture->updateBegin(_side, _mip);
  767. }
  768. void updateTexture(TextureHandle /*_handle*/, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) BX_OVERRIDE
  769. {
  770. m_updateTexture->update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  771. }
  772. void updateTextureEnd() BX_OVERRIDE
  773. {
  774. m_updateTexture->updateEnd();
  775. m_updateTexture = NULL;
  776. }
  777. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height) BX_OVERRIDE
  778. {
  779. TextureD3D9& texture = m_textures[_handle.idx];
  780. texture.m_width = _width;
  781. texture.m_height = _height;
  782. }
  783. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  784. {
  785. m_textures[_handle.idx].destroy();
  786. }
  787. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const TextureHandle* _textureHandles) BX_OVERRIDE
  788. {
  789. m_frameBuffers[_handle.idx].create(_num, _textureHandles);
  790. }
  791. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  792. {
  793. uint16_t denseIdx = m_numWindows++;
  794. m_windows[denseIdx] = _handle;
  795. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  796. }
  797. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  798. {
  799. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  800. if (UINT16_MAX != denseIdx)
  801. {
  802. --m_numWindows;
  803. if (m_numWindows > 1)
  804. {
  805. FrameBufferHandle handle = m_windows[m_numWindows];
  806. m_windows[denseIdx] = handle;
  807. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  808. }
  809. }
  810. }
  811. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  812. {
  813. if (NULL != m_uniforms[_handle.idx])
  814. {
  815. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  816. }
  817. uint32_t size = BX_ALIGN_16(g_uniformTypeSize[_type]*_num);
  818. void* data = BX_ALLOC(g_allocator, size);
  819. memset(data, 0, size);
  820. m_uniforms[_handle.idx] = data;
  821. m_uniformReg.add(_handle, _name, data);
  822. }
  823. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  824. {
  825. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  826. m_uniforms[_handle.idx] = NULL;
  827. }
  828. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  829. {
  830. #if BX_PLATFORM_WINDOWS
  831. IDirect3DSurface9* surface;
  832. D3DDEVICE_CREATION_PARAMETERS dcp;
  833. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  834. D3DDISPLAYMODE dm;
  835. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  836. DX_CHECK(m_device->CreateOffscreenPlainSurface(dm.Width
  837. , dm.Height
  838. , D3DFMT_A8R8G8B8
  839. , D3DPOOL_SCRATCH
  840. , &surface
  841. , NULL
  842. ) );
  843. DX_CHECK(m_device->GetFrontBufferData(0, surface) );
  844. D3DLOCKED_RECT rect;
  845. DX_CHECK(surface->LockRect(&rect
  846. , NULL
  847. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  848. ) );
  849. RECT rc;
  850. GetClientRect( (HWND)g_platformData.nwh, &rc);
  851. POINT point;
  852. point.x = rc.left;
  853. point.y = rc.top;
  854. ClientToScreen( (HWND)g_platformData.nwh, &point);
  855. uint8_t* data = (uint8_t*)rect.pBits;
  856. uint32_t bytesPerPixel = rect.Pitch/dm.Width;
  857. g_callback->screenShot(_filePath
  858. , m_params.BackBufferWidth
  859. , m_params.BackBufferHeight
  860. , rect.Pitch
  861. , &data[point.y*rect.Pitch+point.x*bytesPerPixel]
  862. , m_params.BackBufferHeight*rect.Pitch
  863. , false
  864. );
  865. DX_CHECK(surface->UnlockRect() );
  866. DX_RELEASE(surface, 0);
  867. #endif // BX_PLATFORM_WINDOWS
  868. }
  869. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  870. {
  871. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  872. {
  873. mbstowcs(&s_viewNameW[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  874. , _name
  875. , BX_COUNTOF(s_viewNameW[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  876. );
  877. }
  878. }
  879. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  880. {
  881. memcpy(m_uniforms[_loc], _data, _size);
  882. }
  883. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  884. {
  885. #if BGFX_CONFIG_DEBUG_PIX
  886. uint32_t size = _size*sizeof(wchar_t);
  887. wchar_t* name = (wchar_t*)alloca(size);
  888. mbstowcs(name, _marker, size-2);
  889. PIX_SETMARKER(D3DCOLOR_RGBA(0xff, 0xff, 0xff, 0xff), name);
  890. #endif // BGFX_CONFIG_DEBUG_PIX
  891. BX_UNUSED(_marker, _size);
  892. }
  893. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  894. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  895. {
  896. uint32_t width = m_params.BackBufferWidth;
  897. uint32_t height = m_params.BackBufferHeight;
  898. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  899. setFrameBuffer(fbh, false);
  900. D3DVIEWPORT9 vp;
  901. vp.X = 0;
  902. vp.Y = 0;
  903. vp.Width = width;
  904. vp.Height = height;
  905. vp.MinZ = 0.0f;
  906. vp.MaxZ = 1.0f;
  907. IDirect3DDevice9* device = m_device;
  908. DX_CHECK(device->SetViewport(&vp) );
  909. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  910. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  911. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  912. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  913. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  914. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  915. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE) );
  916. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
  917. ProgramD3D9& program = m_program[_blitter.m_program.idx];
  918. DX_CHECK(device->SetVertexShader(program.m_vsh->m_vertexShader) );
  919. DX_CHECK(device->SetPixelShader(program.m_fsh->m_pixelShader) );
  920. VertexBufferD3D9& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  921. VertexDeclD3D9& vertexDecl = m_vertexDecls[_blitter.m_vb->decl.idx];
  922. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  923. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  924. IndexBufferD3D9& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  925. DX_CHECK(device->SetIndices(ib.m_ptr) );
  926. float proj[16];
  927. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  928. PredefinedUniform& predefined = program.m_predefined[0];
  929. uint8_t flags = predefined.m_type;
  930. setShaderUniform(flags, predefined.m_loc, proj, 4);
  931. m_textures[_blitter.m_texture.idx].commit(0, BGFX_SAMPLER_DEFAULT_FLAGS, NULL);
  932. }
  933. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  934. {
  935. const uint32_t numVertices = _numIndices*4/6;
  936. if (0 < numVertices)
  937. {
  938. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices * 2, _blitter.m_ib->data, true);
  939. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data, true);
  940. DX_CHECK(m_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST
  941. , 0
  942. , 0
  943. , numVertices
  944. , 0
  945. , _numIndices / 3
  946. ) );
  947. }
  948. }
  949. void updateMsaa()
  950. {
  951. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_checkMsaa); ++ii)
  952. {
  953. D3DMULTISAMPLE_TYPE msaa = s_checkMsaa[ii];
  954. DWORD quality;
  955. HRESULT hr = m_d3d9->CheckDeviceMultiSampleType(m_adapter
  956. , m_deviceType
  957. , m_params.BackBufferFormat
  958. , m_params.Windowed
  959. , msaa
  960. , &quality
  961. );
  962. if (SUCCEEDED(hr) )
  963. {
  964. s_msaa[ii].m_type = msaa;
  965. s_msaa[ii].m_quality = bx::uint32_imax(0, quality-1);
  966. last = ii;
  967. }
  968. else
  969. {
  970. s_msaa[ii] = s_msaa[last];
  971. }
  972. }
  973. }
  974. void updateResolution(const Resolution& _resolution)
  975. {
  976. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  977. ? m_caps.MaxAnisotropy
  978. : 1
  979. ;
  980. uint32_t flags = _resolution.m_flags & ~(BGFX_RESET_HMD_RECENTER | BGFX_RESET_MAXANISOTROPY);
  981. if (m_params.BackBufferWidth != _resolution.m_width
  982. || m_params.BackBufferHeight != _resolution.m_height
  983. || m_flags != flags)
  984. {
  985. m_flags = flags;
  986. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  987. m_textVideoMem.clear();
  988. #if BX_PLATFORM_WINDOWS
  989. D3DDEVICE_CREATION_PARAMETERS dcp;
  990. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  991. D3DDISPLAYMODE dm;
  992. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  993. m_params.BackBufferFormat = dm.Format;
  994. #endif // BX_PLATFORM_WINDOWS
  995. m_params.BackBufferWidth = _resolution.m_width;
  996. m_params.BackBufferHeight = _resolution.m_height;
  997. m_params.FullScreen_RefreshRateInHz = BGFX_RESET_FULLSCREEN == (m_flags&BGFX_RESET_FULLSCREEN_MASK) ? 60 : 0;
  998. m_params.PresentationInterval = !!(m_flags&BGFX_RESET_VSYNC) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
  999. updateMsaa();
  1000. Msaa& msaa = s_msaa[(m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  1001. m_params.MultiSampleType = msaa.m_type;
  1002. m_params.MultiSampleQuality = msaa.m_quality;
  1003. m_resolution = _resolution;
  1004. preReset();
  1005. DX_CHECK(m_device->Reset(&m_params) );
  1006. postReset();
  1007. }
  1008. }
  1009. void setFrameBuffer(FrameBufferHandle _fbh, bool _msaa = true)
  1010. {
  1011. if (isValid(m_fbh)
  1012. && m_fbh.idx != _fbh.idx
  1013. && m_rtMsaa)
  1014. {
  1015. FrameBufferD3D9& frameBuffer = m_frameBuffers[m_fbh.idx];
  1016. frameBuffer.resolve();
  1017. }
  1018. if (!isValid(_fbh) )
  1019. {
  1020. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  1021. for (uint32_t ii = 1, num = g_caps.maxFBAttachments; ii < num; ++ii)
  1022. {
  1023. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  1024. }
  1025. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  1026. DX_CHECK(m_device->SetRenderState(D3DRS_SRGBWRITEENABLE, 0 != (m_flags & BGFX_RESET_SRGB_BACKBUFFER) ) );
  1027. }
  1028. else
  1029. {
  1030. const FrameBufferD3D9& frameBuffer = m_frameBuffers[_fbh.idx];
  1031. // If frame buffer has only depth attachment D3DFMT_NULL
  1032. // render target is created.
  1033. uint32_t fbnum = bx::uint32_max(1, frameBuffer.m_num);
  1034. for (uint32_t ii = 0; ii < fbnum; ++ii)
  1035. {
  1036. DX_CHECK(m_device->SetRenderTarget(ii, frameBuffer.m_color[ii]) );
  1037. }
  1038. for (uint32_t ii = fbnum, num = g_caps.maxFBAttachments; ii < num; ++ii)
  1039. {
  1040. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  1041. }
  1042. IDirect3DSurface9* depthStencil = frameBuffer.m_depthStencil;
  1043. DX_CHECK(m_device->SetDepthStencilSurface(NULL != depthStencil ? depthStencil : m_backBufferDepthStencil) );
  1044. DX_CHECK(m_device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE) );
  1045. }
  1046. m_fbh = _fbh;
  1047. m_rtMsaa = _msaa;
  1048. }
  1049. void setShaderUniform(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1050. {
  1051. if (_flags&BGFX_UNIFORM_FRAGMENTBIT)
  1052. {
  1053. DX_CHECK(m_device->SetPixelShaderConstantF(_regIndex, (const float*)_val, _numRegs) );
  1054. }
  1055. else
  1056. {
  1057. DX_CHECK(m_device->SetVertexShaderConstantF(_regIndex, (const float*)_val, _numRegs) );
  1058. }
  1059. }
  1060. void setShaderUniform4f(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1061. {
  1062. setShaderUniform(_flags, _regIndex, _val, _numRegs);
  1063. }
  1064. void setShaderUniform4x4f(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1065. {
  1066. setShaderUniform(_flags, _regIndex, _val, _numRegs);
  1067. }
  1068. void reset()
  1069. {
  1070. preReset();
  1071. HRESULT hr;
  1072. do
  1073. {
  1074. hr = m_device->Reset(&m_params);
  1075. } while (FAILED(hr) );
  1076. postReset();
  1077. }
  1078. static bool isLost(HRESULT _hr)
  1079. {
  1080. return D3DERR_DEVICELOST == _hr
  1081. || D3DERR_DRIVERINTERNALERROR == _hr
  1082. #if !defined(D3D_DISABLE_9EX)
  1083. || D3DERR_DEVICEHUNG == _hr
  1084. || D3DERR_DEVICEREMOVED == _hr
  1085. #endif // !defined(D3D_DISABLE_9EX)
  1086. ;
  1087. }
  1088. void flip(HMD& /*_hmd*/) BX_OVERRIDE
  1089. {
  1090. if (NULL != m_swapChain)
  1091. {
  1092. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  1093. if (NULL != m_deviceEx)
  1094. {
  1095. DX_CHECK(m_deviceEx->WaitForVBlank(0) );
  1096. }
  1097. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  1098. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  1099. {
  1100. HRESULT hr;
  1101. if (0 == ii)
  1102. {
  1103. hr = m_swapChain->Present(NULL, NULL, (HWND)g_platformData.nwh, NULL, 0);
  1104. }
  1105. else
  1106. {
  1107. hr = m_frameBuffers[m_windows[ii].idx].present();
  1108. }
  1109. #if BX_PLATFORM_WINDOWS
  1110. if (isLost(hr) )
  1111. {
  1112. do
  1113. {
  1114. do
  1115. {
  1116. hr = m_device->TestCooperativeLevel();
  1117. }
  1118. while (D3DERR_DEVICENOTRESET != hr);
  1119. reset();
  1120. hr = m_device->TestCooperativeLevel();
  1121. }
  1122. while (FAILED(hr) );
  1123. break;
  1124. }
  1125. else if (FAILED(hr) )
  1126. {
  1127. BX_TRACE("Present failed with err 0x%08x.", hr);
  1128. }
  1129. #endif // BX_PLATFORM_
  1130. }
  1131. }
  1132. }
  1133. void preReset()
  1134. {
  1135. invalidateSamplerState();
  1136. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  1137. {
  1138. DX_CHECK(m_device->SetTexture(stage, NULL) );
  1139. }
  1140. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  1141. for (uint32_t ii = 1, num = g_caps.maxFBAttachments; ii < num; ++ii)
  1142. {
  1143. DX_CHECK(m_device->SetRenderTarget(ii, NULL) );
  1144. }
  1145. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  1146. DX_CHECK(m_device->SetVertexShader(NULL) );
  1147. DX_CHECK(m_device->SetPixelShader(NULL) );
  1148. DX_CHECK(m_device->SetStreamSource(0, NULL, 0, 0) );
  1149. DX_CHECK(m_device->SetIndices(NULL) );
  1150. DX_RELEASE(m_backBufferColor, 0);
  1151. DX_RELEASE(m_backBufferDepthStencil, 0);
  1152. DX_RELEASE(m_swapChain, 0);
  1153. capturePreReset();
  1154. DX_RELEASE(m_flushQuery, 0);
  1155. if (m_timerQuerySupport)
  1156. {
  1157. m_gpuTimer.preReset();
  1158. }
  1159. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  1160. {
  1161. m_indexBuffers[ii].preReset();
  1162. }
  1163. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  1164. {
  1165. m_vertexBuffers[ii].preReset();
  1166. }
  1167. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1168. {
  1169. m_frameBuffers[ii].preReset();
  1170. }
  1171. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  1172. {
  1173. m_textures[ii].preReset();
  1174. }
  1175. }
  1176. void postReset()
  1177. {
  1178. DX_CHECK(m_device->GetSwapChain(0, &m_swapChain) );
  1179. DX_CHECK(m_swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &m_backBufferColor) );
  1180. DX_CHECK(m_device->GetDepthStencilSurface(&m_backBufferDepthStencil) );
  1181. DX_CHECK(m_device->CreateQuery(D3DQUERYTYPE_EVENT, &m_flushQuery) );
  1182. if (m_timerQuerySupport)
  1183. {
  1184. m_gpuTimer.postReset();
  1185. }
  1186. capturePostReset();
  1187. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  1188. {
  1189. m_indexBuffers[ii].postReset();
  1190. }
  1191. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  1192. {
  1193. m_vertexBuffers[ii].postReset();
  1194. }
  1195. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  1196. {
  1197. m_textures[ii].postReset();
  1198. }
  1199. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1200. {
  1201. m_frameBuffers[ii].postReset();
  1202. }
  1203. }
  1204. void invalidateSamplerState()
  1205. {
  1206. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  1207. {
  1208. m_samplerFlags[stage] = UINT32_MAX;
  1209. }
  1210. }
  1211. static void setSamplerState(IDirect3DDevice9* _device, DWORD _stage, D3DSAMPLERSTATETYPE _type, DWORD _value)
  1212. {
  1213. DX_CHECK(_device->SetSamplerState(_stage, _type, _value) );
  1214. if (4 > _stage)
  1215. {
  1216. DX_CHECK(_device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0 + _stage, _type, _value) );
  1217. }
  1218. }
  1219. void setSamplerState(uint8_t _stage, uint32_t _flags, const float _rgba[4])
  1220. {
  1221. const uint32_t flags = _flags&( (~BGFX_TEXTURE_RESERVED_MASK) | BGFX_TEXTURE_SAMPLER_BITS_MASK | BGFX_TEXTURE_SRGB);
  1222. BX_CHECK(_stage < BX_COUNTOF(m_samplerFlags), "");
  1223. if (m_samplerFlags[_stage] != flags)
  1224. {
  1225. m_samplerFlags[_stage] = flags;
  1226. IDirect3DDevice9* device = m_device;
  1227. D3DTEXTUREADDRESS tau = s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT];
  1228. D3DTEXTUREADDRESS tav = s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT];
  1229. D3DTEXTUREADDRESS taw = s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT];
  1230. D3DTEXTUREFILTERTYPE minFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT];
  1231. D3DTEXTUREFILTERTYPE magFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  1232. D3DTEXTUREFILTERTYPE mipFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT];
  1233. setSamplerState(device, _stage, D3DSAMP_ADDRESSU, tau);
  1234. setSamplerState(device, _stage, D3DSAMP_ADDRESSV, tav);
  1235. setSamplerState(device, _stage, D3DSAMP_ADDRESSW, taw);
  1236. setSamplerState(device, _stage, D3DSAMP_MINFILTER, minFilter);
  1237. setSamplerState(device, _stage, D3DSAMP_MAGFILTER, magFilter);
  1238. setSamplerState(device, _stage, D3DSAMP_MIPFILTER, mipFilter);
  1239. setSamplerState(device, _stage, D3DSAMP_MAXANISOTROPY, m_maxAnisotropy);
  1240. setSamplerState(device, _stage, D3DSAMP_SRGBTEXTURE, 0 != (flags & BGFX_TEXTURE_SRGB) );
  1241. if (NULL != _rgba)
  1242. {
  1243. if (needBorderColor(_flags) )
  1244. {
  1245. DWORD bc = D3DCOLOR_COLORVALUE(_rgba[0], _rgba[1], _rgba[2], _rgba[3]);
  1246. setSamplerState(device
  1247. , _stage
  1248. , D3DSAMP_BORDERCOLOR
  1249. , bc
  1250. );
  1251. }
  1252. }
  1253. }
  1254. }
  1255. void capturePreReset()
  1256. {
  1257. if (NULL != m_captureSurface)
  1258. {
  1259. g_callback->captureEnd();
  1260. }
  1261. DX_RELEASE(m_captureSurface, 1);
  1262. DX_RELEASE(m_captureTexture, 0);
  1263. DX_RELEASE(m_captureResolve, 0);
  1264. }
  1265. void capturePostReset()
  1266. {
  1267. if (m_flags&BGFX_RESET_CAPTURE)
  1268. {
  1269. uint32_t width = m_params.BackBufferWidth;
  1270. uint32_t height = m_params.BackBufferHeight;
  1271. D3DFORMAT fmt = m_params.BackBufferFormat;
  1272. DX_CHECK(m_device->CreateTexture(width
  1273. , height
  1274. , 1
  1275. , 0
  1276. , fmt
  1277. , D3DPOOL_SYSTEMMEM
  1278. , &m_captureTexture
  1279. , NULL
  1280. ) );
  1281. DX_CHECK(m_captureTexture->GetSurfaceLevel(0
  1282. , &m_captureSurface
  1283. ) );
  1284. if (m_params.MultiSampleType != D3DMULTISAMPLE_NONE)
  1285. {
  1286. DX_CHECK(m_device->CreateRenderTarget(width
  1287. , height
  1288. , fmt
  1289. , D3DMULTISAMPLE_NONE
  1290. , 0
  1291. , false
  1292. , &m_captureResolve
  1293. , NULL
  1294. ) );
  1295. }
  1296. g_callback->captureBegin(width, height, width*4, TextureFormat::BGRA8, false);
  1297. }
  1298. }
  1299. void capture()
  1300. {
  1301. if (NULL != m_captureSurface)
  1302. {
  1303. IDirect3DSurface9* resolve = m_backBufferColor;
  1304. if (NULL != m_captureResolve)
  1305. {
  1306. resolve = m_captureResolve;
  1307. DX_CHECK(m_device->StretchRect(m_backBufferColor
  1308. , 0
  1309. , m_captureResolve
  1310. , NULL
  1311. , D3DTEXF_NONE
  1312. ) );
  1313. }
  1314. HRESULT hr = m_device->GetRenderTargetData(resolve, m_captureSurface);
  1315. if (SUCCEEDED(hr) )
  1316. {
  1317. D3DLOCKED_RECT rect;
  1318. DX_CHECK(m_captureSurface->LockRect(&rect
  1319. , NULL
  1320. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  1321. ) );
  1322. g_callback->captureFrame(rect.pBits, m_params.BackBufferHeight*rect.Pitch);
  1323. DX_CHECK(m_captureSurface->UnlockRect() );
  1324. }
  1325. }
  1326. }
  1327. void commit(UniformBuffer& _uniformBuffer)
  1328. {
  1329. _uniformBuffer.reset();
  1330. IDirect3DDevice9* device = m_device;
  1331. for (;;)
  1332. {
  1333. uint32_t opcode = _uniformBuffer.read();
  1334. if (UniformType::End == opcode)
  1335. {
  1336. break;
  1337. }
  1338. UniformType::Enum type;
  1339. uint16_t loc;
  1340. uint16_t num;
  1341. uint16_t copy;
  1342. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  1343. const char* data;
  1344. if (copy)
  1345. {
  1346. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  1347. }
  1348. else
  1349. {
  1350. UniformHandle handle;
  1351. memcpy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  1352. data = (const char*)m_uniforms[handle.idx];
  1353. }
  1354. #define CASE_IMPLEMENT_UNIFORM(_uniform, _dxsuffix, _type) \
  1355. case UniformType::_uniform: \
  1356. { \
  1357. _type* value = (_type*)data; \
  1358. DX_CHECK(device->SetVertexShaderConstant##_dxsuffix(loc, value, num) ); \
  1359. } \
  1360. break; \
  1361. \
  1362. case UniformType::_uniform|BGFX_UNIFORM_FRAGMENTBIT: \
  1363. { \
  1364. _type* value = (_type*)data; \
  1365. DX_CHECK(device->SetPixelShaderConstant##_dxsuffix(loc, value, num) ); \
  1366. } \
  1367. break
  1368. switch ( (int32_t)type)
  1369. {
  1370. case UniformType::Mat3:
  1371. {
  1372. float* value = (float*)data;
  1373. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3, value += 9)
  1374. {
  1375. Matrix4 mtx;
  1376. mtx.un.val[ 0] = value[0];
  1377. mtx.un.val[ 1] = value[1];
  1378. mtx.un.val[ 2] = value[2];
  1379. mtx.un.val[ 3] = 0.0f;
  1380. mtx.un.val[ 4] = value[3];
  1381. mtx.un.val[ 5] = value[4];
  1382. mtx.un.val[ 6] = value[5];
  1383. mtx.un.val[ 7] = 0.0f;
  1384. mtx.un.val[ 8] = value[6];
  1385. mtx.un.val[ 9] = value[7];
  1386. mtx.un.val[10] = value[8];
  1387. mtx.un.val[11] = 0.0f;
  1388. DX_CHECK(device->SetVertexShaderConstantF(loc, &mtx.un.val[0], 3) );
  1389. }
  1390. }
  1391. break;
  1392. case UniformType::Mat3|BGFX_UNIFORM_FRAGMENTBIT:
  1393. {
  1394. float* value = (float*)data;
  1395. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3, value += 9)
  1396. {
  1397. Matrix4 mtx;
  1398. mtx.un.val[ 0] = value[0];
  1399. mtx.un.val[ 1] = value[1];
  1400. mtx.un.val[ 2] = value[2];
  1401. mtx.un.val[ 3] = 0.0f;
  1402. mtx.un.val[ 4] = value[3];
  1403. mtx.un.val[ 5] = value[4];
  1404. mtx.un.val[ 6] = value[5];
  1405. mtx.un.val[ 7] = 0.0f;
  1406. mtx.un.val[ 8] = value[6];
  1407. mtx.un.val[ 9] = value[7];
  1408. mtx.un.val[10] = value[8];
  1409. mtx.un.val[11] = 0.0f;
  1410. DX_CHECK(device->SetPixelShaderConstantF(loc, &mtx.un.val[0], 3) );
  1411. }
  1412. }
  1413. break;
  1414. CASE_IMPLEMENT_UNIFORM(Int1, I, int);
  1415. CASE_IMPLEMENT_UNIFORM(Vec4, F, float);
  1416. CASE_IMPLEMENT_UNIFORM(Mat4, F, float);
  1417. case UniformType::End:
  1418. break;
  1419. default:
  1420. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  1421. break;
  1422. }
  1423. #undef CASE_IMPLEMENT_UNIFORM
  1424. }
  1425. }
  1426. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, const float _palette[][4])
  1427. {
  1428. IDirect3DDevice9* device = m_device;
  1429. uint32_t numMrt = 1;
  1430. FrameBufferHandle fbh = m_fbh;
  1431. if (isValid(fbh) )
  1432. {
  1433. const FrameBufferD3D9& fb = m_frameBuffers[fbh.idx];
  1434. numMrt = bx::uint32_max(1, fb.m_num);
  1435. }
  1436. if (1 == numMrt)
  1437. {
  1438. D3DCOLOR color = 0;
  1439. DWORD flags = 0;
  1440. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  1441. {
  1442. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1443. {
  1444. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]);
  1445. const float* rgba = _palette[index];
  1446. const float rr = rgba[0];
  1447. const float gg = rgba[1];
  1448. const float bb = rgba[2];
  1449. const float aa = rgba[3];
  1450. color = D3DCOLOR_COLORVALUE(rr, gg, bb, aa);
  1451. }
  1452. else
  1453. {
  1454. color = D3DCOLOR_RGBA(_clear.m_index[0], _clear.m_index[1], _clear.m_index[2], _clear.m_index[3]);
  1455. }
  1456. flags |= D3DCLEAR_TARGET;
  1457. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE
  1458. , D3DCOLORWRITEENABLE_RED
  1459. | D3DCOLORWRITEENABLE_GREEN
  1460. | D3DCOLORWRITEENABLE_BLUE
  1461. | D3DCOLORWRITEENABLE_ALPHA
  1462. ) );
  1463. }
  1464. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  1465. {
  1466. flags |= D3DCLEAR_ZBUFFER;
  1467. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  1468. }
  1469. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  1470. {
  1471. flags |= D3DCLEAR_STENCIL;
  1472. }
  1473. if (0 != flags)
  1474. {
  1475. RECT rc;
  1476. rc.left = _rect.m_x;
  1477. rc.top = _rect.m_y;
  1478. rc.right = _rect.m_x + _rect.m_width;
  1479. rc.bottom = _rect.m_y + _rect.m_height;
  1480. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE) );
  1481. DX_CHECK(device->SetScissorRect(&rc) );
  1482. DX_CHECK(device->Clear(0, NULL, flags, color, _clear.m_depth, _clear.m_stencil) );
  1483. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  1484. }
  1485. }
  1486. else
  1487. {
  1488. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  1489. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  1490. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  1491. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  1492. {
  1493. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE
  1494. , D3DCOLORWRITEENABLE_RED
  1495. | D3DCOLORWRITEENABLE_GREEN
  1496. | D3DCOLORWRITEENABLE_BLUE
  1497. | D3DCOLORWRITEENABLE_ALPHA
  1498. ) );
  1499. }
  1500. else
  1501. {
  1502. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, 0) );
  1503. }
  1504. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  1505. {
  1506. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  1507. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  1508. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  1509. }
  1510. else
  1511. {
  1512. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE) );
  1513. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  1514. }
  1515. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  1516. {
  1517. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, TRUE) );
  1518. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE) );
  1519. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, _clear.m_stencil) );
  1520. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, 0xff) );
  1521. DX_CHECK(device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS) );
  1522. DX_CHECK(device->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE) );
  1523. DX_CHECK(device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE) );
  1524. DX_CHECK(device->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE) );
  1525. }
  1526. else
  1527. {
  1528. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  1529. }
  1530. VertexBufferD3D9& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  1531. VertexDeclD3D9& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  1532. uint32_t stride = _clearQuad.m_decl.m_stride;
  1533. {
  1534. struct Vertex
  1535. {
  1536. float m_x;
  1537. float m_y;
  1538. float m_z;
  1539. };
  1540. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  1541. BX_CHECK(stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", stride, sizeof(Vertex) );
  1542. const float depth = _clear.m_depth;
  1543. vertex->m_x = -1.0f;
  1544. vertex->m_y = -1.0f;
  1545. vertex->m_z = depth;
  1546. vertex++;
  1547. vertex->m_x = 1.0f;
  1548. vertex->m_y = -1.0f;
  1549. vertex->m_z = depth;
  1550. vertex++;
  1551. vertex->m_x = -1.0f;
  1552. vertex->m_y = 1.0f;
  1553. vertex->m_z = depth;
  1554. vertex++;
  1555. vertex->m_x = 1.0f;
  1556. vertex->m_y = 1.0f;
  1557. vertex->m_z = depth;
  1558. }
  1559. vb.update(0, 4*stride, _clearQuad.m_vb->data);
  1560. ProgramD3D9& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  1561. device->SetVertexShader(program.m_vsh->m_vertexShader);
  1562. device->SetPixelShader(program.m_fsh->m_pixelShader);
  1563. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1564. {
  1565. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  1566. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1567. {
  1568. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  1569. memcpy(mrtClear[ii], _palette[index], 16);
  1570. }
  1571. DX_CHECK(m_device->SetPixelShaderConstantF(0, mrtClear[0], numMrt) );
  1572. }
  1573. else
  1574. {
  1575. float rgba[4] =
  1576. {
  1577. _clear.m_index[0]*1.0f/255.0f,
  1578. _clear.m_index[1]*1.0f/255.0f,
  1579. _clear.m_index[2]*1.0f/255.0f,
  1580. _clear.m_index[3]*1.0f/255.0f,
  1581. };
  1582. DX_CHECK(m_device->SetPixelShaderConstantF(0, rgba, 1) );
  1583. }
  1584. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, stride) );
  1585. DX_CHECK(device->SetStreamSourceFreq(0, 1) );
  1586. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  1587. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  1588. DX_CHECK(device->SetIndices(NULL) );
  1589. DX_CHECK(device->DrawPrimitive(D3DPT_TRIANGLESTRIP
  1590. , 0
  1591. , 2
  1592. ) );
  1593. }
  1594. }
  1595. #if BX_PLATFORM_WINDOWS
  1596. D3DCAPS9 m_caps;
  1597. #endif // BX_PLATFORM_WINDOWS
  1598. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  1599. IDirect3D9Ex* m_d3d9ex;
  1600. IDirect3DDevice9Ex* m_deviceEx;
  1601. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  1602. IDirect3D9* m_d3d9;
  1603. IDirect3DDevice9* m_device;
  1604. IDirect3DQuery9* m_flushQuery;
  1605. TimerQueryD3D9 m_gpuTimer;
  1606. D3DPOOL m_pool;
  1607. IDirect3DSwapChain9* m_swapChain;
  1608. uint16_t m_numWindows;
  1609. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1610. IDirect3DSurface9* m_backBufferColor;
  1611. IDirect3DSurface9* m_backBufferDepthStencil;
  1612. IDirect3DTexture9* m_captureTexture;
  1613. IDirect3DSurface9* m_captureSurface;
  1614. IDirect3DSurface9* m_captureResolve;
  1615. IDirect3DVertexDeclaration9* m_instanceDataDecls[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1616. void* m_d3d9dll;
  1617. uint32_t m_adapter;
  1618. D3DDEVTYPE m_deviceType;
  1619. D3DPRESENT_PARAMETERS m_params;
  1620. uint32_t m_flags;
  1621. uint32_t m_maxAnisotropy;
  1622. D3DADAPTER_IDENTIFIER9 m_identifier;
  1623. Resolution m_resolution;
  1624. bool m_initialized;
  1625. bool m_amd;
  1626. bool m_nvidia;
  1627. bool m_instancingSupport;
  1628. bool m_timerQuerySupport;
  1629. D3DFORMAT m_fmtDepth;
  1630. IndexBufferD3D9 m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  1631. VertexBufferD3D9 m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  1632. ShaderD3D9 m_shaders[BGFX_CONFIG_MAX_SHADERS];
  1633. ProgramD3D9 m_program[BGFX_CONFIG_MAX_PROGRAMS];
  1634. TextureD3D9 m_textures[BGFX_CONFIG_MAX_TEXTURES];
  1635. VertexDeclD3D9 m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  1636. FrameBufferD3D9 m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1637. UniformRegistry m_uniformReg;
  1638. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  1639. uint32_t m_samplerFlags[BGFX_CONFIG_MAX_TEXTURE_SAMPLERS];
  1640. TextureD3D9* m_updateTexture;
  1641. uint8_t* m_updateTextureBits;
  1642. uint32_t m_updateTexturePitch;
  1643. uint8_t m_updateTextureSide;
  1644. uint8_t m_updateTextureMip;
  1645. TextVideoMem m_textVideoMem;
  1646. FrameBufferHandle m_fbh;
  1647. bool m_rtMsaa;
  1648. };
  1649. static RendererContextD3D9* s_renderD3D9;
  1650. RendererContextI* rendererCreate()
  1651. {
  1652. s_renderD3D9 = BX_NEW(g_allocator, RendererContextD3D9);
  1653. if (!s_renderD3D9->init() )
  1654. {
  1655. BX_DELETE(g_allocator, s_renderD3D9);
  1656. s_renderD3D9 = NULL;
  1657. }
  1658. return s_renderD3D9;
  1659. }
  1660. void rendererDestroy()
  1661. {
  1662. s_renderD3D9->shutdown();
  1663. BX_DELETE(g_allocator, s_renderD3D9);
  1664. s_renderD3D9 = NULL;
  1665. }
  1666. void IndexBufferD3D9::create(uint32_t _size, void* _data, uint16_t _flags)
  1667. {
  1668. m_size = _size;
  1669. m_flags = _flags;
  1670. m_dynamic = NULL == _data;
  1671. uint32_t usage = D3DUSAGE_WRITEONLY;
  1672. D3DPOOL pool = s_renderD3D9->m_pool;
  1673. if (m_dynamic)
  1674. {
  1675. usage |= D3DUSAGE_DYNAMIC;
  1676. pool = D3DPOOL_DEFAULT;
  1677. }
  1678. const D3DFORMAT format = 0 == (_flags & BGFX_BUFFER_INDEX32)
  1679. ? D3DFMT_INDEX16
  1680. : D3DFMT_INDEX32
  1681. ;
  1682. DX_CHECK(s_renderD3D9->m_device->CreateIndexBuffer(m_size
  1683. , usage
  1684. , format
  1685. , pool
  1686. , &m_ptr
  1687. , NULL
  1688. ) );
  1689. if (NULL != _data)
  1690. {
  1691. update(0, _size, _data);
  1692. }
  1693. }
  1694. void IndexBufferD3D9::preReset()
  1695. {
  1696. if (m_dynamic)
  1697. {
  1698. DX_RELEASE(m_ptr, 0);
  1699. }
  1700. }
  1701. void IndexBufferD3D9::postReset()
  1702. {
  1703. if (m_dynamic)
  1704. {
  1705. const D3DFORMAT format = 0 == (m_flags & BGFX_BUFFER_INDEX32)
  1706. ? D3DFMT_INDEX16
  1707. : D3DFMT_INDEX32
  1708. ;
  1709. DX_CHECK(s_renderD3D9->m_device->CreateIndexBuffer(m_size
  1710. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  1711. , format
  1712. , D3DPOOL_DEFAULT
  1713. , &m_ptr
  1714. , NULL
  1715. ) );
  1716. }
  1717. }
  1718. void VertexBufferD3D9::create(uint32_t _size, void* _data, VertexDeclHandle _declHandle)
  1719. {
  1720. m_size = _size;
  1721. m_decl = _declHandle;
  1722. m_dynamic = NULL == _data;
  1723. uint32_t usage = D3DUSAGE_WRITEONLY;
  1724. D3DPOOL pool = s_renderD3D9->m_pool;
  1725. if (m_dynamic)
  1726. {
  1727. usage |= D3DUSAGE_DYNAMIC;
  1728. pool = D3DPOOL_DEFAULT;
  1729. }
  1730. DX_CHECK(s_renderD3D9->m_device->CreateVertexBuffer(m_size
  1731. , usage
  1732. , 0
  1733. , pool
  1734. , &m_ptr
  1735. , NULL
  1736. ) );
  1737. if (NULL != _data)
  1738. {
  1739. update(0, _size, _data);
  1740. }
  1741. }
  1742. void VertexBufferD3D9::preReset()
  1743. {
  1744. if (m_dynamic)
  1745. {
  1746. DX_RELEASE(m_ptr, 0);
  1747. }
  1748. }
  1749. void VertexBufferD3D9::postReset()
  1750. {
  1751. if (m_dynamic)
  1752. {
  1753. DX_CHECK(s_renderD3D9->m_device->CreateVertexBuffer(m_size
  1754. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  1755. , 0
  1756. , D3DPOOL_DEFAULT
  1757. , &m_ptr
  1758. , NULL
  1759. ) );
  1760. }
  1761. }
  1762. static const D3DVERTEXELEMENT9 s_attrib[] =
  1763. {
  1764. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
  1765. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
  1766. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
  1767. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 },
  1768. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
  1769. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 },
  1770. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
  1771. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
  1772. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
  1773. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
  1774. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
  1775. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
  1776. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 },
  1777. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 },
  1778. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 6 },
  1779. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 7 },
  1780. D3DDECL_END()
  1781. };
  1782. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attrib)-1);
  1783. static const uint8_t s_attribType[][4][2] =
  1784. {
  1785. { // Uint8
  1786. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1787. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1788. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1789. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1790. },
  1791. { // Uint10
  1792. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  1793. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  1794. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  1795. { D3DDECLTYPE_UDEC3, D3DDECLTYPE_DEC3N },
  1796. },
  1797. { // Int16
  1798. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1799. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1800. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1801. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1802. },
  1803. { // Half
  1804. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1805. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1806. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1807. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1808. },
  1809. { // Float
  1810. { D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT1 },
  1811. { D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT2 },
  1812. { D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT3 },
  1813. { D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT4 },
  1814. },
  1815. };
  1816. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  1817. static D3DVERTEXELEMENT9* fillVertexDecl(D3DVERTEXELEMENT9* _out, const VertexDecl& _decl)
  1818. {
  1819. D3DVERTEXELEMENT9* elem = _out;
  1820. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  1821. {
  1822. if (UINT16_MAX != _decl.m_attributes[attr])
  1823. {
  1824. uint8_t num;
  1825. AttribType::Enum type;
  1826. bool normalized;
  1827. bool asInt;
  1828. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  1829. memcpy(elem, &s_attrib[attr], sizeof(D3DVERTEXELEMENT9) );
  1830. elem->Type = s_attribType[type][num-1][normalized];
  1831. elem->Offset = _decl.m_offset[attr];
  1832. ++elem;
  1833. }
  1834. }
  1835. return elem;
  1836. }
  1837. static IDirect3DVertexDeclaration9* createVertexDeclaration(const VertexDecl& _decl, uint16_t _numInstanceData)
  1838. {
  1839. D3DVERTEXELEMENT9 vertexElements[Attrib::Count+1+BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1840. D3DVERTEXELEMENT9* elem = fillVertexDecl(vertexElements, _decl);
  1841. const D3DVERTEXELEMENT9 inst = { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 };
  1842. for (uint8_t ii = 0; ii < _numInstanceData; ++ii)
  1843. {
  1844. memcpy(elem, &inst, sizeof(D3DVERTEXELEMENT9) );
  1845. elem->UsageIndex = uint8_t(7-ii); // TEXCOORD7 = i_data0, TEXCOORD6 = i_data1, etc.
  1846. elem->Offset = ii*16;
  1847. ++elem;
  1848. }
  1849. memcpy(elem, &s_attrib[Attrib::Count], sizeof(D3DVERTEXELEMENT9) );
  1850. IDirect3DVertexDeclaration9* ptr;
  1851. DX_CHECK(s_renderD3D9->m_device->CreateVertexDeclaration(vertexElements, &ptr) );
  1852. return ptr;
  1853. }
  1854. void VertexDeclD3D9::create(const VertexDecl& _decl)
  1855. {
  1856. memcpy(&m_decl, &_decl, sizeof(VertexDecl) );
  1857. dump(m_decl);
  1858. m_ptr = createVertexDeclaration(_decl, 0);
  1859. }
  1860. void ShaderD3D9::create(const Memory* _mem)
  1861. {
  1862. bx::MemoryReader reader(_mem->data, _mem->size);
  1863. uint32_t magic;
  1864. bx::read(&reader, magic);
  1865. switch (magic)
  1866. {
  1867. case BGFX_CHUNK_MAGIC_FSH:
  1868. case BGFX_CHUNK_MAGIC_VSH:
  1869. break;
  1870. default:
  1871. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  1872. break;
  1873. }
  1874. bool fragment = BGFX_CHUNK_MAGIC_FSH == magic;
  1875. uint32_t iohash;
  1876. bx::read(&reader, iohash);
  1877. uint16_t count;
  1878. bx::read(&reader, count);
  1879. m_numPredefined = 0;
  1880. BX_TRACE("Shader consts %d", count);
  1881. uint8_t fragmentBit = fragment ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  1882. if (0 < count)
  1883. {
  1884. for (uint32_t ii = 0; ii < count; ++ii)
  1885. {
  1886. uint8_t nameSize;
  1887. bx::read(&reader, nameSize);
  1888. char name[256];
  1889. bx::read(&reader, &name, nameSize);
  1890. name[nameSize] = '\0';
  1891. uint8_t type;
  1892. bx::read(&reader, type);
  1893. uint8_t num;
  1894. bx::read(&reader, num);
  1895. uint16_t regIndex;
  1896. bx::read(&reader, regIndex);
  1897. uint16_t regCount;
  1898. bx::read(&reader, regCount);
  1899. const char* kind = "invalid";
  1900. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  1901. if (PredefinedUniform::Count != predefined)
  1902. {
  1903. kind = "predefined";
  1904. m_predefined[m_numPredefined].m_loc = regIndex;
  1905. m_predefined[m_numPredefined].m_count = regCount;
  1906. m_predefined[m_numPredefined].m_type = uint8_t(predefined|fragmentBit);
  1907. m_numPredefined++;
  1908. }
  1909. else if (0 == (BGFX_UNIFORM_SAMPLERBIT & type) )
  1910. {
  1911. const UniformInfo* info = s_renderD3D9->m_uniformReg.find(name);
  1912. BX_CHECK(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  1913. if (NULL != info)
  1914. {
  1915. if (NULL == m_constantBuffer)
  1916. {
  1917. m_constantBuffer = UniformBuffer::create(1024);
  1918. }
  1919. kind = "user";
  1920. m_constantBuffer->writeUniformHandle( (UniformType::Enum)(type|fragmentBit), regIndex, info->m_handle, regCount);
  1921. }
  1922. }
  1923. else
  1924. {
  1925. kind = "sampler";
  1926. }
  1927. BX_TRACE("\t%s: %s (%s), num %2d, r.index %3d, r.count %2d"
  1928. , kind
  1929. , name
  1930. , getUniformTypeName(UniformType::Enum(type&~BGFX_UNIFORM_MASK) )
  1931. , num
  1932. , regIndex
  1933. , regCount
  1934. );
  1935. BX_UNUSED(kind);
  1936. }
  1937. if (NULL != m_constantBuffer)
  1938. {
  1939. m_constantBuffer->finish();
  1940. }
  1941. }
  1942. uint16_t shaderSize;
  1943. bx::read(&reader, shaderSize);
  1944. const DWORD* code = (const DWORD*)reader.getDataPtr();
  1945. if (fragment)
  1946. {
  1947. m_type = 1;
  1948. DX_CHECK(s_renderD3D9->m_device->CreatePixelShader(code, &m_pixelShader) );
  1949. BGFX_FATAL(NULL != m_pixelShader, bgfx::Fatal::InvalidShader, "Failed to create fragment shader.");
  1950. }
  1951. else
  1952. {
  1953. m_type = 0;
  1954. DX_CHECK(s_renderD3D9->m_device->CreateVertexShader(code, &m_vertexShader) );
  1955. BGFX_FATAL(NULL != m_vertexShader, bgfx::Fatal::InvalidShader, "Failed to create vertex shader.");
  1956. }
  1957. }
  1958. void TextureD3D9::createTexture(uint32_t _width, uint32_t _height, uint8_t _numMips)
  1959. {
  1960. m_type = Texture2D;
  1961. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  1962. DWORD usage = 0;
  1963. D3DPOOL pool = s_renderD3D9->m_pool;
  1964. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  1965. const bool blit = 0 != (m_flags&BGFX_TEXTURE_BLIT_DST);
  1966. if (isDepth(fmt) )
  1967. {
  1968. usage = D3DUSAGE_DEPTHSTENCIL;
  1969. pool = D3DPOOL_DEFAULT;
  1970. }
  1971. else if (renderTarget || blit)
  1972. {
  1973. usage = D3DUSAGE_RENDERTARGET;
  1974. pool = D3DPOOL_DEFAULT;
  1975. }
  1976. if (renderTarget)
  1977. {
  1978. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  1979. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  1980. bool bufferOnly = 0 != (m_flags&BGFX_TEXTURE_RT_BUFFER_ONLY);
  1981. if (0 != msaaQuality
  1982. || bufferOnly)
  1983. {
  1984. const Msaa& msaa = s_msaa[msaaQuality];
  1985. if (isDepth(fmt) )
  1986. {
  1987. DX_CHECK(s_renderD3D9->m_device->CreateDepthStencilSurface(
  1988. m_width
  1989. , m_height
  1990. , s_textureFormat[m_textureFormat].m_fmt
  1991. , msaa.m_type
  1992. , msaa.m_quality
  1993. , FALSE
  1994. , &m_surface
  1995. , NULL
  1996. ) );
  1997. }
  1998. else
  1999. {
  2000. DX_CHECK(s_renderD3D9->m_device->CreateRenderTarget(
  2001. m_width
  2002. , m_height
  2003. , s_textureFormat[m_textureFormat].m_fmt
  2004. , msaa.m_type
  2005. , msaa.m_quality
  2006. , FALSE
  2007. , &m_surface
  2008. , NULL
  2009. ) );
  2010. }
  2011. if (bufferOnly)
  2012. {
  2013. // This is render buffer, there is no sampling, no need
  2014. // to create texture.
  2015. return;
  2016. }
  2017. }
  2018. }
  2019. DX_CHECK(s_renderD3D9->m_device->CreateTexture(_width
  2020. , _height
  2021. , _numMips
  2022. , usage
  2023. , s_textureFormat[fmt].m_fmt
  2024. , pool
  2025. , &m_texture2d
  2026. , NULL
  2027. ) );
  2028. BGFX_FATAL(NULL != m_texture2d, Fatal::UnableToCreateTexture, "Failed to create texture (size: %dx%d, mips: %d, fmt: %d)."
  2029. , _width
  2030. , _height
  2031. , _numMips
  2032. , getName(fmt)
  2033. );
  2034. }
  2035. void TextureD3D9::createVolumeTexture(uint32_t _width, uint32_t _height, uint32_t _depth, uint32_t _numMips)
  2036. {
  2037. m_type = Texture3D;
  2038. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2039. DX_CHECK(s_renderD3D9->m_device->CreateVolumeTexture(_width
  2040. , _height
  2041. , _depth
  2042. , _numMips
  2043. , 0
  2044. , s_textureFormat[fmt].m_fmt
  2045. , s_renderD3D9->m_pool
  2046. , &m_texture3d
  2047. , NULL
  2048. ) );
  2049. BGFX_FATAL(NULL != m_texture3d, Fatal::UnableToCreateTexture, "Failed to create volume texture (size: %dx%dx%d, mips: %d, fmt: %s)."
  2050. , _width
  2051. , _height
  2052. , _depth
  2053. , _numMips
  2054. , getName(fmt)
  2055. );
  2056. }
  2057. void TextureD3D9::createCubeTexture(uint32_t _edge, uint32_t _numMips)
  2058. {
  2059. m_type = TextureCube;
  2060. const TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2061. DWORD usage = 0;
  2062. D3DPOOL pool = s_renderD3D9->m_pool;
  2063. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  2064. const bool blit = 0 != (m_flags&BGFX_TEXTURE_BLIT_DST);
  2065. if (isDepth(fmt) )
  2066. {
  2067. usage = D3DUSAGE_DEPTHSTENCIL;
  2068. pool = D3DPOOL_DEFAULT;
  2069. }
  2070. else if (renderTarget || blit)
  2071. {
  2072. usage = D3DUSAGE_RENDERTARGET;
  2073. pool = D3DPOOL_DEFAULT;
  2074. }
  2075. DX_CHECK(s_renderD3D9->m_device->CreateCubeTexture(_edge
  2076. , _numMips
  2077. , usage
  2078. , s_textureFormat[fmt].m_fmt
  2079. , pool
  2080. , &m_textureCube
  2081. , NULL
  2082. ) );
  2083. BGFX_FATAL(NULL != m_textureCube, Fatal::UnableToCreateTexture, "Failed to create cube texture (edge: %d, mips: %d, fmt: %s)."
  2084. , _edge
  2085. , _numMips
  2086. , getName(fmt)
  2087. );
  2088. }
  2089. uint8_t* TextureD3D9::lock(uint8_t _side, uint8_t _lod, uint32_t& _pitch, uint32_t& _slicePitch, const Rect* _rect)
  2090. {
  2091. switch (m_type)
  2092. {
  2093. case Texture2D:
  2094. {
  2095. D3DLOCKED_RECT lockedRect;
  2096. if (NULL != _rect)
  2097. {
  2098. RECT rect;
  2099. rect.left = _rect->m_x;
  2100. rect.top = _rect->m_y;
  2101. rect.right = rect.left + _rect->m_width;
  2102. rect.bottom = rect.top + _rect->m_height;
  2103. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, &rect, 0) );
  2104. }
  2105. else
  2106. {
  2107. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, NULL, 0) );
  2108. }
  2109. _pitch = lockedRect.Pitch;
  2110. _slicePitch = 0;
  2111. return (uint8_t*)lockedRect.pBits;
  2112. }
  2113. case Texture3D:
  2114. {
  2115. D3DLOCKED_BOX box;
  2116. DX_CHECK(m_texture3d->LockBox(_lod, &box, NULL, 0) );
  2117. _pitch = box.RowPitch;
  2118. _slicePitch = box.SlicePitch;
  2119. return (uint8_t*)box.pBits;
  2120. }
  2121. case TextureCube:
  2122. {
  2123. D3DLOCKED_RECT lockedRect;
  2124. if (NULL != _rect)
  2125. {
  2126. RECT rect;
  2127. rect.left = _rect->m_x;
  2128. rect.top = _rect->m_y;
  2129. rect.right = rect.left + _rect->m_width;
  2130. rect.bottom = rect.top + _rect->m_height;
  2131. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, &rect, 0) );
  2132. }
  2133. else
  2134. {
  2135. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, NULL, 0) );
  2136. }
  2137. _pitch = lockedRect.Pitch;
  2138. _slicePitch = 0;
  2139. return (uint8_t*)lockedRect.pBits;
  2140. }
  2141. }
  2142. BX_CHECK(false, "You should not be here.");
  2143. _pitch = 0;
  2144. _slicePitch = 0;
  2145. return NULL;
  2146. }
  2147. void TextureD3D9::unlock(uint8_t _side, uint8_t _lod)
  2148. {
  2149. switch (m_type)
  2150. {
  2151. case Texture2D:
  2152. {
  2153. DX_CHECK(m_texture2d->UnlockRect(_lod) );
  2154. }
  2155. return;
  2156. case Texture3D:
  2157. {
  2158. DX_CHECK(m_texture3d->UnlockBox(_lod) );
  2159. }
  2160. return;
  2161. case TextureCube:
  2162. {
  2163. DX_CHECK(m_textureCube->UnlockRect(D3DCUBEMAP_FACES(_side), _lod) );
  2164. }
  2165. return;
  2166. }
  2167. BX_CHECK(false, "You should not be here.");
  2168. }
  2169. void TextureD3D9::dirty(uint8_t _side, const Rect& _rect, uint16_t _z, uint16_t _depth)
  2170. {
  2171. switch (m_type)
  2172. {
  2173. case Texture2D:
  2174. {
  2175. RECT rect;
  2176. rect.left = _rect.m_x;
  2177. rect.top = _rect.m_y;
  2178. rect.right = rect.left + _rect.m_width;
  2179. rect.bottom = rect.top + _rect.m_height;
  2180. DX_CHECK(m_texture2d->AddDirtyRect(&rect) );
  2181. }
  2182. return;
  2183. case Texture3D:
  2184. {
  2185. D3DBOX box;
  2186. box.Left = _rect.m_x;
  2187. box.Top = _rect.m_y;
  2188. box.Right = box.Left + _rect.m_width;
  2189. box.Bottom = box.Top + _rect.m_height;
  2190. box.Front = _z;
  2191. box.Back = box.Front + _depth;
  2192. DX_CHECK(m_texture3d->AddDirtyBox(&box) );
  2193. }
  2194. return;
  2195. case TextureCube:
  2196. {
  2197. RECT rect;
  2198. rect.left = _rect.m_x;
  2199. rect.top = _rect.m_y;
  2200. rect.right = rect.left + _rect.m_width;
  2201. rect.bottom = rect.top + _rect.m_height;
  2202. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), &rect) );
  2203. }
  2204. return;
  2205. }
  2206. BX_CHECK(false, "You should not be here.");
  2207. }
  2208. void TextureD3D9::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  2209. {
  2210. ImageContainer imageContainer;
  2211. if (imageParse(imageContainer, _mem->data, _mem->size) )
  2212. {
  2213. uint8_t numMips = imageContainer.m_numMips;
  2214. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  2215. numMips -= startLod;
  2216. const ImageBlockInfo& blockInfo = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  2217. const uint32_t textureWidth = bx::uint32_max(blockInfo.blockWidth, imageContainer.m_width >>startLod);
  2218. const uint32_t textureHeight = bx::uint32_max(blockInfo.blockHeight, imageContainer.m_height>>startLod);
  2219. m_flags = _flags;
  2220. m_width = textureWidth;
  2221. m_height = textureHeight;
  2222. m_depth = imageContainer.m_depth;
  2223. m_numMips = numMips;
  2224. m_requestedFormat = imageContainer.m_format;
  2225. m_textureFormat = imageContainer.m_format;
  2226. const TextureFormatInfo& tfi = s_textureFormat[m_requestedFormat];
  2227. uint8_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  2228. if (D3DFMT_UNKNOWN == tfi.m_fmt)
  2229. {
  2230. m_textureFormat = (uint8_t)TextureFormat::BGRA8;
  2231. bpp = 32;
  2232. }
  2233. if (imageContainer.m_cubeMap)
  2234. {
  2235. createCubeTexture(textureWidth, numMips);
  2236. }
  2237. else if (imageContainer.m_depth > 1)
  2238. {
  2239. createVolumeTexture(textureWidth, textureHeight, imageContainer.m_depth, numMips);
  2240. }
  2241. else
  2242. {
  2243. createTexture(textureWidth, textureHeight, numMips);
  2244. }
  2245. if (imageContainer.m_srgb)
  2246. {
  2247. m_flags |= BGFX_TEXTURE_SRGB;
  2248. }
  2249. BX_TRACE("Texture %3d: %s (requested: %s), %dx%d%s%s."
  2250. , this - s_renderD3D9->m_textures
  2251. , getName( (TextureFormat::Enum)m_textureFormat)
  2252. , getName( (TextureFormat::Enum)m_requestedFormat)
  2253. , textureWidth
  2254. , textureHeight
  2255. , imageContainer.m_cubeMap ? "x6" : ""
  2256. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  2257. );
  2258. if (0 != (_flags&BGFX_TEXTURE_RT_BUFFER_ONLY) )
  2259. {
  2260. return;
  2261. }
  2262. // For BC4 and B5 in DX9 LockRect returns wrong number of
  2263. // bytes. If actual mip size is used it causes memory corruption.
  2264. // http://www.aras-p.info/texts/D3D9GPUHacks.html#3dc
  2265. const bool useMipSize = true
  2266. && imageContainer.m_format != TextureFormat::BC4
  2267. && imageContainer.m_format != TextureFormat::BC5
  2268. ;
  2269. const bool convert = m_textureFormat != m_requestedFormat;
  2270. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  2271. {
  2272. uint32_t width = textureWidth;
  2273. uint32_t height = textureHeight;
  2274. uint32_t depth = imageContainer.m_depth;
  2275. uint32_t mipWidth = imageContainer.m_width;
  2276. uint32_t mipHeight = imageContainer.m_height;
  2277. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  2278. {
  2279. width = bx::uint32_max(1, width);
  2280. height = bx::uint32_max(1, height);
  2281. depth = bx::uint32_max(1, depth);
  2282. mipWidth = bx::uint32_max(blockInfo.blockWidth, mipWidth);
  2283. mipHeight = bx::uint32_max(blockInfo.blockHeight, mipHeight);
  2284. uint32_t mipSize = width*height*depth*bpp/8;
  2285. ImageMip mip;
  2286. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  2287. {
  2288. uint32_t pitch;
  2289. uint32_t slicePitch;
  2290. uint8_t* bits = lock(side, lod, pitch, slicePitch);
  2291. if (convert)
  2292. {
  2293. if (width != mipWidth
  2294. || height != mipHeight)
  2295. {
  2296. uint32_t srcpitch = mipWidth*bpp/8;
  2297. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, srcpitch*mipHeight);
  2298. imageDecodeToBgra8(temp
  2299. , mip.m_data
  2300. , mip.m_width
  2301. , mip.m_height
  2302. , srcpitch
  2303. , mip.m_format
  2304. );
  2305. uint32_t dstpitch = pitch;
  2306. for (uint32_t yy = 0; yy < height; ++yy)
  2307. {
  2308. uint8_t* src = &temp[yy*srcpitch];
  2309. uint8_t* dst = &bits[yy*dstpitch];
  2310. memcpy(dst, src, dstpitch);
  2311. }
  2312. BX_FREE(g_allocator, temp);
  2313. }
  2314. else
  2315. {
  2316. imageDecodeToBgra8(bits, mip.m_data, mip.m_width, mip.m_height, pitch, mip.m_format);
  2317. }
  2318. }
  2319. else
  2320. {
  2321. uint32_t size = useMipSize ? mip.m_size : mipSize;
  2322. memcpy(bits, mip.m_data, size);
  2323. }
  2324. unlock(side, lod);
  2325. }
  2326. width >>= 1;
  2327. height >>= 1;
  2328. depth >>= 1;
  2329. mipWidth >>= 1;
  2330. mipHeight >>= 1;
  2331. }
  2332. }
  2333. }
  2334. }
  2335. void TextureD3D9::updateBegin(uint8_t _side, uint8_t _mip)
  2336. {
  2337. uint32_t slicePitch;
  2338. s_renderD3D9->m_updateTextureSide = _side;
  2339. s_renderD3D9->m_updateTextureMip = _mip;
  2340. s_renderD3D9->m_updateTextureBits = lock(_side, _mip, s_renderD3D9->m_updateTexturePitch, slicePitch);
  2341. }
  2342. void TextureD3D9::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  2343. {
  2344. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  2345. const uint32_t rectpitch = _rect.m_width*bpp/8;
  2346. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  2347. const uint32_t dstpitch = s_renderD3D9->m_updateTexturePitch;
  2348. uint8_t* bits = s_renderD3D9->m_updateTextureBits + _rect.m_y*dstpitch + _rect.m_x*bpp/8;
  2349. const bool convert = m_textureFormat != m_requestedFormat;
  2350. uint8_t* data = _mem->data;
  2351. uint8_t* temp = NULL;
  2352. if (convert)
  2353. {
  2354. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  2355. imageDecodeToBgra8(temp, data, _rect.m_width, _rect.m_height, srcpitch, m_requestedFormat);
  2356. data = temp;
  2357. }
  2358. {
  2359. uint8_t* src = data;
  2360. uint8_t* dst = bits;
  2361. for (uint32_t yy = 0, height = _rect.m_height; yy < height; ++yy)
  2362. {
  2363. memcpy(dst, src, rectpitch);
  2364. src += srcpitch;
  2365. dst += dstpitch;
  2366. }
  2367. }
  2368. if (NULL != temp)
  2369. {
  2370. BX_FREE(g_allocator, temp);
  2371. }
  2372. if (0 == _mip)
  2373. {
  2374. dirty(_side, _rect, _z, _depth);
  2375. }
  2376. }
  2377. void TextureD3D9::updateEnd()
  2378. {
  2379. unlock(s_renderD3D9->m_updateTextureSide, s_renderD3D9->m_updateTextureMip);
  2380. }
  2381. void TextureD3D9::commit(uint8_t _stage, uint32_t _flags, const float _palette[][4])
  2382. {
  2383. uint32_t flags = 0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags)
  2384. ? _flags
  2385. : m_flags
  2386. ;
  2387. uint32_t index = (flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  2388. s_renderD3D9->setSamplerState(_stage, flags, _palette[index]);
  2389. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2390. DX_CHECK(device->SetTexture(_stage, m_ptr) );
  2391. if (4 > _stage)
  2392. {
  2393. DX_CHECK(device->SetTexture(D3DVERTEXTEXTURESAMPLER0 + _stage, m_ptr) );
  2394. }
  2395. }
  2396. void TextureD3D9::resolve() const
  2397. {
  2398. if (NULL != m_surface
  2399. && NULL != m_texture2d)
  2400. {
  2401. IDirect3DSurface9* surface;
  2402. DX_CHECK(m_texture2d->GetSurfaceLevel(0, &surface) );
  2403. DX_CHECK(s_renderD3D9->m_device->StretchRect(m_surface
  2404. , NULL
  2405. , surface
  2406. , NULL
  2407. , D3DTEXF_LINEAR
  2408. ) );
  2409. DX_RELEASE(surface, 1);
  2410. }
  2411. }
  2412. void TextureD3D9::preReset()
  2413. {
  2414. TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2415. if (TextureFormat::Unknown != fmt
  2416. && (isDepth(fmt) || !!(m_flags&(BGFX_TEXTURE_RT_MASK|BGFX_TEXTURE_BLIT_DST) ) ) )
  2417. {
  2418. DX_RELEASE(m_ptr, 0);
  2419. DX_RELEASE(m_surface, 0);
  2420. }
  2421. }
  2422. void TextureD3D9::postReset()
  2423. {
  2424. TextureFormat::Enum fmt = (TextureFormat::Enum)m_textureFormat;
  2425. if (TextureFormat::Unknown != fmt
  2426. && (isDepth(fmt) || !!(m_flags&(BGFX_TEXTURE_RT_MASK|BGFX_TEXTURE_BLIT_DST)) ) )
  2427. {
  2428. createTexture(m_width, m_height, m_numMips);
  2429. }
  2430. }
  2431. void FrameBufferD3D9::create(uint8_t _num, const TextureHandle* _handles)
  2432. {
  2433. for (uint32_t ii = 0; ii < BX_COUNTOF(m_color); ++ii)
  2434. {
  2435. m_color[ii] = NULL;
  2436. }
  2437. m_depthStencil = NULL;
  2438. m_num = 0;
  2439. m_needResolve = false;
  2440. for (uint32_t ii = 0; ii < _num; ++ii)
  2441. {
  2442. TextureHandle handle = _handles[ii];
  2443. if (isValid(handle) )
  2444. {
  2445. const TextureD3D9& texture = s_renderD3D9->m_textures[handle.idx];
  2446. if (isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  2447. {
  2448. m_depthHandle = handle;
  2449. if (NULL != texture.m_surface)
  2450. {
  2451. m_depthStencil = texture.m_surface;
  2452. m_depthStencil->AddRef();
  2453. }
  2454. else
  2455. {
  2456. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_depthStencil) );
  2457. }
  2458. }
  2459. else
  2460. {
  2461. m_colorHandle[m_num] = handle;
  2462. if (NULL != texture.m_surface)
  2463. {
  2464. m_color[m_num] = texture.m_surface;
  2465. m_color[m_num]->AddRef();
  2466. }
  2467. else
  2468. {
  2469. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_color[m_num]) );
  2470. }
  2471. m_num++;
  2472. }
  2473. m_needResolve |= (NULL != texture.m_surface) && (NULL != texture.m_texture2d);
  2474. }
  2475. }
  2476. if (0 == m_num)
  2477. {
  2478. createNullColorRT();
  2479. }
  2480. }
  2481. void FrameBufferD3D9::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  2482. {
  2483. BX_UNUSED(_depthFormat);
  2484. m_hwnd = (HWND)_nwh;
  2485. m_width = bx::uint32_max(_width, 16);
  2486. m_height = bx::uint32_max(_height, 16);
  2487. D3DPRESENT_PARAMETERS params;
  2488. memcpy(&params, &s_renderD3D9->m_params, sizeof(D3DPRESENT_PARAMETERS) );
  2489. params.BackBufferWidth = m_width;
  2490. params.BackBufferHeight = m_height;
  2491. DX_CHECK(s_renderD3D9->m_device->CreateAdditionalSwapChain(&params, &m_swapChain) );
  2492. DX_CHECK(m_swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &m_color[0]) );
  2493. DX_CHECK(s_renderD3D9->m_device->CreateDepthStencilSurface(
  2494. params.BackBufferWidth
  2495. , params.BackBufferHeight
  2496. , params.AutoDepthStencilFormat
  2497. , params.MultiSampleType
  2498. , params.MultiSampleQuality
  2499. , FALSE
  2500. , &m_depthStencil
  2501. , NULL
  2502. ) );
  2503. m_colorHandle[0].idx = invalidHandle;
  2504. m_denseIdx = _denseIdx;
  2505. m_num = 1;
  2506. m_needResolve = false;
  2507. }
  2508. uint16_t FrameBufferD3D9::destroy()
  2509. {
  2510. if (NULL != m_hwnd)
  2511. {
  2512. DX_RELEASE(m_depthStencil, 0);
  2513. DX_RELEASE(m_color[0], 0);
  2514. DX_RELEASE(m_swapChain, 0);
  2515. }
  2516. else
  2517. {
  2518. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2519. {
  2520. m_colorHandle[ii].idx = invalidHandle;
  2521. IDirect3DSurface9* ptr = m_color[ii];
  2522. if (NULL != ptr)
  2523. {
  2524. ptr->Release();
  2525. m_color[ii] = NULL;
  2526. }
  2527. }
  2528. if (NULL != m_depthStencil)
  2529. {
  2530. if (0 == m_num)
  2531. {
  2532. IDirect3DSurface9* ptr = m_color[0];
  2533. if (NULL != ptr)
  2534. {
  2535. ptr->Release();
  2536. m_color[0] = NULL;
  2537. }
  2538. }
  2539. m_depthStencil->Release();
  2540. m_depthStencil = NULL;
  2541. }
  2542. }
  2543. m_hwnd = NULL;
  2544. m_num = 0;
  2545. m_depthHandle.idx = invalidHandle;
  2546. uint16_t denseIdx = m_denseIdx;
  2547. m_denseIdx = UINT16_MAX;
  2548. return denseIdx;
  2549. }
  2550. HRESULT FrameBufferD3D9::present()
  2551. {
  2552. return m_swapChain->Present(NULL, NULL, m_hwnd, NULL, 0);
  2553. }
  2554. void FrameBufferD3D9::resolve() const
  2555. {
  2556. if (m_needResolve)
  2557. {
  2558. if (isValid(m_depthHandle) )
  2559. {
  2560. const TextureD3D9& texture = s_renderD3D9->m_textures[m_depthHandle.idx];
  2561. texture.resolve();
  2562. }
  2563. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2564. {
  2565. const TextureD3D9& texture = s_renderD3D9->m_textures[m_colorHandle[ii].idx];
  2566. texture.resolve();
  2567. }
  2568. }
  2569. }
  2570. void FrameBufferD3D9::preReset()
  2571. {
  2572. if (NULL != m_hwnd)
  2573. {
  2574. DX_RELEASE(m_color[0], 0);
  2575. DX_RELEASE(m_depthStencil, 0);
  2576. DX_RELEASE(m_swapChain, 0);
  2577. }
  2578. else
  2579. {
  2580. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2581. {
  2582. m_color[ii]->Release();
  2583. m_color[ii] = NULL;
  2584. }
  2585. if (isValid(m_depthHandle) )
  2586. {
  2587. if (0 == m_num)
  2588. {
  2589. m_color[0]->Release();
  2590. m_color[0] = NULL;
  2591. }
  2592. m_depthStencil->Release();
  2593. m_depthStencil = NULL;
  2594. }
  2595. }
  2596. }
  2597. void FrameBufferD3D9::postReset()
  2598. {
  2599. if (NULL != m_hwnd)
  2600. {
  2601. D3DPRESENT_PARAMETERS params;
  2602. memcpy(&params, &s_renderD3D9->m_params, sizeof(D3DPRESENT_PARAMETERS) );
  2603. params.BackBufferWidth = m_width;
  2604. params.BackBufferHeight = m_height;
  2605. DX_CHECK(s_renderD3D9->m_device->CreateAdditionalSwapChain(&params, &m_swapChain) );
  2606. DX_CHECK(m_swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &m_color[0]) );
  2607. DX_CHECK(s_renderD3D9->m_device->CreateDepthStencilSurface(params.BackBufferWidth
  2608. , params.BackBufferHeight
  2609. , params.AutoDepthStencilFormat
  2610. , params.MultiSampleType
  2611. , params.MultiSampleQuality
  2612. , FALSE
  2613. , &m_depthStencil
  2614. , NULL
  2615. ) );
  2616. }
  2617. else
  2618. {
  2619. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  2620. {
  2621. TextureHandle th = m_colorHandle[ii];
  2622. if (isValid(th) )
  2623. {
  2624. TextureD3D9& texture = s_renderD3D9->m_textures[th.idx];
  2625. if (NULL != texture.m_surface)
  2626. {
  2627. m_color[ii] = texture.m_surface;
  2628. m_color[ii]->AddRef();
  2629. }
  2630. else
  2631. {
  2632. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_color[ii]) );
  2633. }
  2634. }
  2635. }
  2636. if (isValid(m_depthHandle) )
  2637. {
  2638. TextureD3D9& texture = s_renderD3D9->m_textures[m_depthHandle.idx];
  2639. if (NULL != texture.m_surface)
  2640. {
  2641. m_depthStencil = texture.m_surface;
  2642. m_depthStencil->AddRef();
  2643. }
  2644. else
  2645. {
  2646. DX_CHECK(texture.m_texture2d->GetSurfaceLevel(0, &m_depthStencil) );
  2647. }
  2648. if (0 == m_num)
  2649. {
  2650. createNullColorRT();
  2651. }
  2652. }
  2653. }
  2654. }
  2655. void FrameBufferD3D9::createNullColorRT()
  2656. {
  2657. const TextureD3D9& texture = s_renderD3D9->m_textures[m_depthHandle.idx];
  2658. DX_CHECK(s_renderD3D9->m_device->CreateRenderTarget(texture.m_width
  2659. , texture.m_height
  2660. , D3DFMT_NULL
  2661. , D3DMULTISAMPLE_NONE
  2662. , 0
  2663. , false
  2664. , &m_color[0]
  2665. , NULL
  2666. ) );
  2667. }
  2668. void TimerQueryD3D9::postReset()
  2669. {
  2670. IDirect3DDevice9* device = s_renderD3D9->m_device;
  2671. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frame); ++ii)
  2672. {
  2673. Frame& frame = m_frame[ii];
  2674. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMPDISJOINT, &frame.m_disjoint) );
  2675. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMP, &frame.m_start) );
  2676. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMP, &frame.m_end) );
  2677. DX_CHECK(device->CreateQuery(D3DQUERYTYPE_TIMESTAMPFREQ, &frame.m_freq) );
  2678. }
  2679. m_elapsed = 0;
  2680. m_frequency = 1;
  2681. m_control.reset();
  2682. }
  2683. void TimerQueryD3D9::preReset()
  2684. {
  2685. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frame); ++ii)
  2686. {
  2687. Frame& frame = m_frame[ii];
  2688. DX_RELEASE(frame.m_disjoint, 0);
  2689. DX_RELEASE(frame.m_start, 0);
  2690. DX_RELEASE(frame.m_end, 0);
  2691. DX_RELEASE(frame.m_freq, 0);
  2692. }
  2693. }
  2694. void TimerQueryD3D9::begin()
  2695. {
  2696. while (0 == m_control.reserve(1) )
  2697. {
  2698. get();
  2699. }
  2700. Frame& frame = m_frame[m_control.m_current];
  2701. frame.m_disjoint->Issue(D3DISSUE_BEGIN);
  2702. frame.m_start->Issue(D3DISSUE_END);
  2703. }
  2704. void TimerQueryD3D9::end()
  2705. {
  2706. Frame& frame = m_frame[m_control.m_current];
  2707. frame.m_disjoint->Issue(D3DISSUE_END);
  2708. frame.m_end->Issue(D3DISSUE_END);
  2709. frame.m_freq->Issue(D3DISSUE_END);
  2710. m_control.commit(1);
  2711. }
  2712. bool TimerQueryD3D9::get()
  2713. {
  2714. if (0 != m_control.available() )
  2715. {
  2716. Frame& frame = m_frame[m_control.m_read];
  2717. uint64_t freq;
  2718. HRESULT hr = frame.m_freq->GetData(&freq, sizeof(freq), 0);
  2719. if (S_OK == hr)
  2720. {
  2721. m_control.consume(1);
  2722. uint64_t timeStart;
  2723. DX_CHECK(frame.m_start->GetData(&timeStart, sizeof(timeStart), 0) );
  2724. uint64_t timeEnd;
  2725. DX_CHECK(frame.m_end->GetData(&timeEnd, sizeof(timeEnd), 0) );
  2726. m_frequency = freq;
  2727. m_elapsed = timeEnd - timeStart;
  2728. return true;
  2729. }
  2730. }
  2731. return false;
  2732. }
  2733. void RendererContextD3D9::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  2734. {
  2735. IDirect3DDevice9* device = m_device;
  2736. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), L"rendererSubmit");
  2737. updateResolution(_render->m_resolution);
  2738. int64_t elapsed = -bx::getHPCounter();
  2739. int64_t captureElapsed = 0;
  2740. device->BeginScene();
  2741. if (m_timerQuerySupport)
  2742. {
  2743. m_gpuTimer.begin();
  2744. }
  2745. if (0 < _render->m_iboffset)
  2746. {
  2747. TransientIndexBuffer* ib = _render->m_transientIb;
  2748. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  2749. }
  2750. if (0 < _render->m_vboffset)
  2751. {
  2752. TransientVertexBuffer* vb = _render->m_transientVb;
  2753. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  2754. }
  2755. _render->sort();
  2756. RenderDraw currentState;
  2757. currentState.clear();
  2758. currentState.m_flags = BGFX_STATE_NONE;
  2759. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  2760. ViewState viewState(_render, false);
  2761. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, _render->m_debug&BGFX_DEBUG_WIREFRAME ? D3DFILL_WIREFRAME : D3DFILL_SOLID) );
  2762. uint16_t programIdx = invalidHandle;
  2763. SortKey key;
  2764. uint16_t view = UINT16_MAX;
  2765. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  2766. uint32_t blendFactor = 0;
  2767. BlitKey blitKey;
  2768. blitKey.decode(_render->m_blitKeys[0]);
  2769. uint16_t numBlitItems = _render->m_numBlitItems;
  2770. uint16_t blitItem = 0;
  2771. uint8_t primIndex;
  2772. {
  2773. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  2774. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  2775. }
  2776. PrimInfo prim = s_primInfo[primIndex];
  2777. bool viewHasScissor = false;
  2778. Rect viewScissorRect;
  2779. viewScissorRect.clear();
  2780. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  2781. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  2782. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  2783. uint32_t statsNumIndices = 0;
  2784. uint32_t statsKeyType[2] = {};
  2785. invalidateSamplerState();
  2786. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  2787. {
  2788. for (uint32_t item = 0, numItems = _render->m_num; item < numItems; ++item)
  2789. {
  2790. const bool isCompute = key.decode(_render->m_sortKeys[item], _render->m_viewRemap);
  2791. statsKeyType[isCompute]++;
  2792. if (isCompute)
  2793. {
  2794. BX_CHECK(false, "Compute is not supported on DirectX 9.");
  2795. continue;
  2796. }
  2797. const RenderDraw& draw = _render->m_renderItem[_render->m_sortValues[item] ].draw;
  2798. const uint64_t newFlags = draw.m_flags;
  2799. uint64_t changedFlags = currentState.m_flags ^ draw.m_flags;
  2800. currentState.m_flags = newFlags;
  2801. const uint64_t newStencil = draw.m_stencil;
  2802. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  2803. currentState.m_stencil = newStencil;
  2804. if (key.m_view != view)
  2805. {
  2806. currentState.clear();
  2807. currentState.m_scissor = !draw.m_scissor;
  2808. changedFlags = BGFX_STATE_MASK;
  2809. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  2810. currentState.m_flags = newFlags;
  2811. currentState.m_stencil = newStencil;
  2812. PIX_ENDEVENT();
  2813. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), s_viewNameW[key.m_view]);
  2814. view = key.m_view;
  2815. programIdx = invalidHandle;
  2816. if (_render->m_fb[view].idx != fbh.idx)
  2817. {
  2818. fbh = _render->m_fb[view];
  2819. setFrameBuffer(fbh);
  2820. }
  2821. viewState.m_rect = _render->m_rect[view];
  2822. const Rect& scissorRect = _render->m_scissor[view];
  2823. viewHasScissor = !scissorRect.isZero();
  2824. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  2825. D3DVIEWPORT9 vp;
  2826. vp.X = viewState.m_rect.m_x;
  2827. vp.Y = viewState.m_rect.m_y;
  2828. vp.Width = viewState.m_rect.m_width;
  2829. vp.Height = viewState.m_rect.m_height;
  2830. vp.MinZ = 0.0f;
  2831. vp.MaxZ = 1.0f;
  2832. DX_CHECK(device->SetViewport(&vp) );
  2833. Clear& clear = _render->m_clear[view];
  2834. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  2835. {
  2836. clearQuad(_clearQuad, viewState.m_rect, clear, _render->m_colorPalette);
  2837. prim = s_primInfo[BX_COUNTOF(s_primName)]; // Force primitive type update after clear quad.
  2838. }
  2839. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  2840. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  2841. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS) );
  2842. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  2843. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  2844. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  2845. for (; blitItem < numBlitItems && blitKey.m_view <= view; blitItem++)
  2846. {
  2847. const BlitItem& blit = _render->m_blitItem[blitItem];
  2848. blitKey.decode(_render->m_blitKeys[blitItem+1]);
  2849. const TextureD3D9& src = m_textures[blit.m_src.idx];
  2850. const TextureD3D9& dst = m_textures[blit.m_dst.idx];
  2851. uint32_t srcWidth = bx::uint32_min(src.m_width, blit.m_srcX + blit.m_width) - blit.m_srcX;
  2852. uint32_t srcHeight = bx::uint32_min(src.m_height, blit.m_srcY + blit.m_height) - blit.m_srcY;
  2853. uint32_t dstWidth = bx::uint32_min(dst.m_width, blit.m_dstX + blit.m_width) - blit.m_dstX;
  2854. uint32_t dstHeight = bx::uint32_min(dst.m_height, blit.m_dstY + blit.m_height) - blit.m_dstY;
  2855. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  2856. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  2857. RECT srcRect = { LONG(blit.m_srcX), LONG(blit.m_srcY), LONG(blit.m_srcX + width), LONG(blit.m_srcY + height) };
  2858. RECT dstRect = { LONG(blit.m_dstX), LONG(blit.m_dstY), LONG(blit.m_dstX + width), LONG(blit.m_dstY + height) };
  2859. IDirect3DSurface9* srcSurface;
  2860. switch (src.m_type)
  2861. {
  2862. case TextureD3D9::Texture2D:
  2863. DX_CHECK(src.m_texture2d->GetSurfaceLevel(blit.m_srcMip, &srcSurface) );
  2864. break;
  2865. case TextureD3D9::Texture3D:
  2866. BX_CHECK(false, "");
  2867. break;
  2868. case TextureD3D9::TextureCube:
  2869. DX_CHECK(src.m_textureCube->GetCubeMapSurface(D3DCUBEMAP_FACES(blit.m_srcZ), blit.m_srcMip, &srcSurface) );
  2870. break;
  2871. }
  2872. IDirect3DSurface9* dstSurface;
  2873. switch (dst.m_type)
  2874. {
  2875. case TextureD3D9::Texture2D:
  2876. DX_CHECK(dst.m_texture2d->GetSurfaceLevel(blit.m_dstMip, &dstSurface) );
  2877. break;
  2878. case TextureD3D9::Texture3D:
  2879. BX_CHECK(false, "");
  2880. break;
  2881. case TextureD3D9::TextureCube:
  2882. DX_CHECK(dst.m_textureCube->GetCubeMapSurface(D3DCUBEMAP_FACES(blit.m_dstZ), blit.m_dstMip, &dstSurface) );
  2883. break;
  2884. }
  2885. HRESULT hr = m_device->StretchRect(srcSurface
  2886. , &srcRect
  2887. , dstSurface
  2888. , &dstRect
  2889. , D3DTEXF_NONE
  2890. );
  2891. BX_WARN(SUCCEEDED(hr), "StretchRect failed %x.", hr);
  2892. BX_UNUSED(hr);
  2893. srcSurface->Release();
  2894. dstSurface->Release();
  2895. }
  2896. }
  2897. uint16_t scissor = draw.m_scissor;
  2898. if (currentState.m_scissor != scissor)
  2899. {
  2900. currentState.m_scissor = scissor;
  2901. if (UINT16_MAX == scissor)
  2902. {
  2903. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, viewHasScissor) );
  2904. if (viewHasScissor)
  2905. {
  2906. RECT rc;
  2907. rc.left = viewScissorRect.m_x;
  2908. rc.top = viewScissorRect.m_y;
  2909. rc.right = viewScissorRect.m_x + viewScissorRect.m_width;
  2910. rc.bottom = viewScissorRect.m_y + viewScissorRect.m_height;
  2911. DX_CHECK(device->SetScissorRect(&rc) );
  2912. }
  2913. }
  2914. else
  2915. {
  2916. Rect scissorRect;
  2917. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  2918. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, true) );
  2919. RECT rc;
  2920. rc.left = scissorRect.m_x;
  2921. rc.top = scissorRect.m_y;
  2922. rc.right = scissorRect.m_x + scissorRect.m_width;
  2923. rc.bottom = scissorRect.m_y + scissorRect.m_height;
  2924. DX_CHECK(device->SetScissorRect(&rc) );
  2925. }
  2926. }
  2927. if (0 != changedStencil)
  2928. {
  2929. bool enable = 0 != newStencil;
  2930. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, enable) );
  2931. if (0 != newStencil)
  2932. {
  2933. uint32_t fstencil = unpackStencil(0, newStencil);
  2934. uint32_t bstencil = unpackStencil(1, newStencil);
  2935. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  2936. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, 0 != frontAndBack) );
  2937. uint32_t fchanged = unpackStencil(0, changedStencil);
  2938. if ( (BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & fchanged)
  2939. {
  2940. uint32_t ref = (fstencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  2941. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, ref) );
  2942. uint32_t rmask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2943. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, rmask) );
  2944. }
  2945. // uint32_t bchanged = unpackStencil(1, changedStencil);
  2946. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  2947. // {
  2948. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2949. // DX_CHECK(device->SetRenderState(D3DRS_STENCILWRITEMASK, wmask) );
  2950. // }
  2951. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  2952. {
  2953. uint32_t stencil = unpackStencil(ii, newStencil);
  2954. uint32_t changed = unpackStencil(ii, changedStencil);
  2955. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  2956. {
  2957. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  2958. DX_CHECK(device->SetRenderState(s_stencilFuncRs[ii], s_cmpFunc[func]) );
  2959. }
  2960. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  2961. {
  2962. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  2963. DX_CHECK(device->SetRenderState(s_stencilFailRs[ii], s_stencilOp[sfail]) );
  2964. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  2965. DX_CHECK(device->SetRenderState(s_stencilZFailRs[ii], s_stencilOp[zfail]) );
  2966. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  2967. DX_CHECK(device->SetRenderState(s_stencilZPassRs[ii], s_stencilOp[zpass]) );
  2968. }
  2969. }
  2970. }
  2971. }
  2972. if ( (0
  2973. | BGFX_STATE_CULL_MASK
  2974. | BGFX_STATE_DEPTH_WRITE
  2975. | BGFX_STATE_DEPTH_TEST_MASK
  2976. | BGFX_STATE_RGB_WRITE
  2977. | BGFX_STATE_ALPHA_WRITE
  2978. | BGFX_STATE_BLEND_MASK
  2979. | BGFX_STATE_BLEND_EQUATION_MASK
  2980. | BGFX_STATE_ALPHA_REF_MASK
  2981. | BGFX_STATE_PT_MASK
  2982. | BGFX_STATE_POINT_SIZE_MASK
  2983. | BGFX_STATE_MSAA
  2984. ) & changedFlags)
  2985. {
  2986. if (BGFX_STATE_CULL_MASK & changedFlags)
  2987. {
  2988. uint32_t cull = (newFlags&BGFX_STATE_CULL_MASK)>>BGFX_STATE_CULL_SHIFT;
  2989. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, s_cullMode[cull]) );
  2990. }
  2991. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  2992. {
  2993. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, !!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  2994. }
  2995. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  2996. {
  2997. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  2998. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, 0 != func) );
  2999. if (0 != func)
  3000. {
  3001. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, s_cmpFunc[func]) );
  3002. }
  3003. }
  3004. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  3005. {
  3006. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  3007. viewState.m_alphaRef = ref/255.0f;
  3008. }
  3009. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  3010. {
  3011. DX_CHECK(device->SetRenderState(D3DRS_POINTSIZE, castfu( (float)( (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) ) ) );
  3012. }
  3013. if (BGFX_STATE_MSAA & changedFlags)
  3014. {
  3015. DX_CHECK(device->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, (newFlags&BGFX_STATE_MSAA) == BGFX_STATE_MSAA) );
  3016. }
  3017. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  3018. {
  3019. uint32_t writeEnable = (newFlags&BGFX_STATE_ALPHA_WRITE) ? D3DCOLORWRITEENABLE_ALPHA : 0;
  3020. writeEnable |= (newFlags&BGFX_STATE_RGB_WRITE) ? D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE : 0;
  3021. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, writeEnable) );
  3022. }
  3023. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK) & changedFlags
  3024. || blendFactor != draw.m_rgba)
  3025. {
  3026. bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  3027. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, enabled) );
  3028. if (enabled)
  3029. {
  3030. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  3031. const uint32_t equation = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  3032. const uint32_t srcRGB = (blend )&0xf;
  3033. const uint32_t dstRGB = (blend>> 4)&0xf;
  3034. const uint32_t srcA = (blend>> 8)&0xf;
  3035. const uint32_t dstA = (blend>>12)&0xf;
  3036. const uint32_t equRGB = (equation )&0x7;
  3037. const uint32_t equA = (equation>>3)&0x7;
  3038. DX_CHECK(device->SetRenderState(D3DRS_SRCBLEND, s_blendFactor[srcRGB].m_src) );
  3039. DX_CHECK(device->SetRenderState(D3DRS_DESTBLEND, s_blendFactor[dstRGB].m_dst) );
  3040. DX_CHECK(device->SetRenderState(D3DRS_BLENDOP, s_blendEquation[equRGB]) );
  3041. const bool separate = srcRGB != srcA || dstRGB != dstA || equRGB != equA;
  3042. DX_CHECK(device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, separate) );
  3043. if (separate)
  3044. {
  3045. DX_CHECK(device->SetRenderState(D3DRS_SRCBLENDALPHA, s_blendFactor[srcA].m_src) );
  3046. DX_CHECK(device->SetRenderState(D3DRS_DESTBLENDALPHA, s_blendFactor[dstA].m_dst) );
  3047. DX_CHECK(device->SetRenderState(D3DRS_BLENDOPALPHA, s_blendEquation[equA]) );
  3048. }
  3049. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  3050. && blendFactor != draw.m_rgba)
  3051. {
  3052. const uint32_t rgba = draw.m_rgba;
  3053. D3DCOLOR color = D3DCOLOR_RGBA(rgba>>24
  3054. , (rgba>>16)&0xff
  3055. , (rgba>> 8)&0xff
  3056. , (rgba )&0xff
  3057. );
  3058. DX_CHECK(device->SetRenderState(D3DRS_BLENDFACTOR, color) );
  3059. }
  3060. }
  3061. blendFactor = draw.m_rgba;
  3062. }
  3063. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  3064. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  3065. prim = s_primInfo[primIndex];
  3066. }
  3067. bool programChanged = false;
  3068. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  3069. rendererUpdateUniforms(this, _render->m_uniformBuffer, draw.m_constBegin, draw.m_constEnd);
  3070. if (key.m_program != programIdx)
  3071. {
  3072. programIdx = key.m_program;
  3073. if (invalidHandle == programIdx)
  3074. {
  3075. device->SetVertexShader(NULL);
  3076. device->SetPixelShader(NULL);
  3077. }
  3078. else
  3079. {
  3080. ProgramD3D9& program = m_program[programIdx];
  3081. device->SetVertexShader(program.m_vsh->m_vertexShader);
  3082. device->SetPixelShader(program.m_fsh->m_pixelShader);
  3083. }
  3084. programChanged =
  3085. constantsChanged = true;
  3086. }
  3087. if (invalidHandle != programIdx)
  3088. {
  3089. ProgramD3D9& program = m_program[programIdx];
  3090. if (constantsChanged)
  3091. {
  3092. UniformBuffer* vcb = program.m_vsh->m_constantBuffer;
  3093. if (NULL != vcb)
  3094. {
  3095. commit(*vcb);
  3096. }
  3097. UniformBuffer* fcb = program.m_fsh->m_constantBuffer;
  3098. if (NULL != fcb)
  3099. {
  3100. commit(*fcb);
  3101. }
  3102. }
  3103. viewState.setPredefined<4>(this, view, 0, program, _render, draw);
  3104. }
  3105. {
  3106. for (uint8_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  3107. {
  3108. const Binding& bind = draw.m_bind[stage];
  3109. Binding& current = currentState.m_bind[stage];
  3110. if (current.m_idx != bind.m_idx
  3111. || current.m_un.m_draw.m_flags != bind.m_un.m_draw.m_flags
  3112. || programChanged)
  3113. {
  3114. if (invalidHandle != bind.m_idx)
  3115. {
  3116. m_textures[bind.m_idx].commit(stage, bind.m_un.m_draw.m_flags, _render->m_colorPalette);
  3117. }
  3118. else
  3119. {
  3120. DX_CHECK(device->SetTexture(stage, NULL) );
  3121. }
  3122. }
  3123. current = bind;
  3124. }
  3125. }
  3126. if (programChanged
  3127. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  3128. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  3129. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  3130. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  3131. {
  3132. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  3133. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  3134. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  3135. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  3136. uint16_t handle = draw.m_vertexBuffer.idx;
  3137. if (invalidHandle != handle)
  3138. {
  3139. const VertexBufferD3D9& vb = m_vertexBuffers[handle];
  3140. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  3141. const VertexDeclD3D9& vertexDecl = m_vertexDecls[decl];
  3142. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  3143. if (isValid(draw.m_instanceDataBuffer)
  3144. && m_instancingSupport)
  3145. {
  3146. const VertexBufferD3D9& inst = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  3147. DX_CHECK(device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA|draw.m_numInstances) );
  3148. DX_CHECK(device->SetStreamSourceFreq(1, UINT(D3DSTREAMSOURCE_INSTANCEDATA|1) ) );
  3149. DX_CHECK(device->SetStreamSource(1, inst.m_ptr, draw.m_instanceDataOffset, draw.m_instanceDataStride) );
  3150. IDirect3DVertexDeclaration9* ptr = createVertexDeclaration(vertexDecl.m_decl, draw.m_instanceDataStride/16);
  3151. DX_CHECK(device->SetVertexDeclaration(ptr) );
  3152. DX_RELEASE(ptr, 0);
  3153. }
  3154. else
  3155. {
  3156. DX_CHECK(device->SetStreamSourceFreq(0, 1) );
  3157. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  3158. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  3159. }
  3160. }
  3161. else
  3162. {
  3163. DX_CHECK(device->SetStreamSource(0, NULL, 0, 0) );
  3164. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  3165. }
  3166. }
  3167. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  3168. {
  3169. currentState.m_indexBuffer = draw.m_indexBuffer;
  3170. uint16_t handle = draw.m_indexBuffer.idx;
  3171. if (invalidHandle != handle)
  3172. {
  3173. const IndexBufferD3D9& ib = m_indexBuffers[handle];
  3174. DX_CHECK(device->SetIndices(ib.m_ptr) );
  3175. }
  3176. else
  3177. {
  3178. DX_CHECK(device->SetIndices(NULL) );
  3179. }
  3180. }
  3181. if (isValid(currentState.m_vertexBuffer) )
  3182. {
  3183. uint32_t numVertices = draw.m_numVertices;
  3184. if (UINT32_MAX == numVertices)
  3185. {
  3186. const VertexBufferD3D9& vb = m_vertexBuffers[currentState.m_vertexBuffer.idx];
  3187. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  3188. const VertexDeclD3D9& vertexDecl = m_vertexDecls[decl];
  3189. numVertices = vb.m_size/vertexDecl.m_decl.m_stride;
  3190. }
  3191. uint32_t numIndices = 0;
  3192. uint32_t numPrimsSubmitted = 0;
  3193. uint32_t numInstances = 0;
  3194. uint32_t numPrimsRendered = 0;
  3195. if (isValid(draw.m_indexBuffer) )
  3196. {
  3197. if (UINT32_MAX == draw.m_numIndices)
  3198. {
  3199. const IndexBufferD3D9& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3200. const uint32_t indexSize = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32) ? 2 : 4;
  3201. numIndices = ib.m_size/indexSize;
  3202. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3203. numInstances = draw.m_numInstances;
  3204. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3205. DX_CHECK(device->DrawIndexedPrimitive(prim.m_type
  3206. , draw.m_startVertex
  3207. , 0
  3208. , numVertices
  3209. , 0
  3210. , numPrimsSubmitted
  3211. ) );
  3212. }
  3213. else if (prim.m_min <= draw.m_numIndices)
  3214. {
  3215. numIndices = draw.m_numIndices;
  3216. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3217. numInstances = draw.m_numInstances;
  3218. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3219. DX_CHECK(device->DrawIndexedPrimitive(prim.m_type
  3220. , draw.m_startVertex
  3221. , 0
  3222. , numVertices
  3223. , draw.m_startIndex
  3224. , numPrimsSubmitted
  3225. ) );
  3226. }
  3227. }
  3228. else
  3229. {
  3230. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  3231. numInstances = draw.m_numInstances;
  3232. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3233. DX_CHECK(device->DrawPrimitive(prim.m_type
  3234. , draw.m_startVertex
  3235. , numPrimsSubmitted
  3236. ) );
  3237. }
  3238. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  3239. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  3240. statsNumInstances[primIndex] += numInstances;
  3241. statsNumIndices += numIndices;
  3242. }
  3243. }
  3244. if (0 < _render->m_num)
  3245. {
  3246. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  3247. {
  3248. m_flushQuery->Issue(D3DISSUE_END);
  3249. m_flushQuery->GetData(NULL, 0, D3DGETDATA_FLUSH);
  3250. }
  3251. captureElapsed = -bx::getHPCounter();
  3252. capture();
  3253. captureElapsed += bx::getHPCounter();
  3254. }
  3255. }
  3256. PIX_ENDEVENT();
  3257. int64_t now = bx::getHPCounter();
  3258. elapsed += now;
  3259. static int64_t last = now;
  3260. int64_t frameTime = now - last;
  3261. last = now;
  3262. static int64_t min = frameTime;
  3263. static int64_t max = frameTime;
  3264. min = min > frameTime ? frameTime : min;
  3265. max = max < frameTime ? frameTime : max;
  3266. static uint32_t maxGpuLatency = 0;
  3267. static double maxGpuElapsed = 0.0f;
  3268. double elapsedGpuMs = 0.0;
  3269. if (m_timerQuerySupport)
  3270. {
  3271. m_gpuTimer.end();
  3272. while (m_gpuTimer.get() )
  3273. {
  3274. double toGpuMs = 1000.0 / double(m_gpuTimer.m_frequency);
  3275. elapsedGpuMs = m_gpuTimer.m_elapsed * toGpuMs;
  3276. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  3277. }
  3278. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  3279. }
  3280. const int64_t timerFreq = bx::getHPFrequency();
  3281. Stats& perfStats = _render->m_perfStats;
  3282. perfStats.cpuTime = frameTime;
  3283. perfStats.cpuTimerFreq = timerFreq;
  3284. perfStats.gpuTime = m_gpuTimer.m_elapsed;
  3285. perfStats.gpuTimerFreq = m_gpuTimer.m_frequency;
  3286. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  3287. {
  3288. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugstats");
  3289. TextVideoMem& tvm = m_textVideoMem;
  3290. static int64_t next = now;
  3291. if (now >= next)
  3292. {
  3293. next = now + timerFreq;
  3294. double freq = double(timerFreq);
  3295. double toMs = 1000.0/freq;
  3296. tvm.clear();
  3297. uint16_t pos = 0;
  3298. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  3299. , getRendererName()
  3300. );
  3301. const D3DADAPTER_IDENTIFIER9& identifier = m_identifier;
  3302. tvm.printf(0, pos++, 0x8f, " Device: %s (%s)", identifier.Description, identifier.Driver);
  3303. char processMemoryUsed[16];
  3304. bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() );
  3305. tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed);
  3306. pos = 10;
  3307. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  3308. , double(frameTime)*toMs
  3309. , double(min)*toMs
  3310. , double(max)*toMs
  3311. , freq/frameTime
  3312. );
  3313. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  3314. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy "
  3315. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  3316. , 0 != msaa ? '\xfe' : ' '
  3317. , 1<<msaa
  3318. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  3319. );
  3320. double elapsedCpuMs = double(elapsed)*toMs;
  3321. tvm.printf(10, pos++, 0x8e, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d)"
  3322. , _render->m_num
  3323. , statsKeyType[0]
  3324. , statsKeyType[1]
  3325. , elapsedCpuMs
  3326. , elapsedCpuMs > maxGpuElapsed ? '>' : '<'
  3327. , maxGpuElapsed
  3328. , maxGpuLatency
  3329. );
  3330. maxGpuLatency = 0;
  3331. maxGpuElapsed = 0.0;
  3332. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primName); ++ii)
  3333. {
  3334. tvm.printf(10, pos++, 0x8e, " %9s: %7d (#inst: %5d), submitted: %7d"
  3335. , s_primName[ii]
  3336. , statsNumPrimsRendered[ii]
  3337. , statsNumInstances[ii]
  3338. , statsNumPrimsSubmitted[ii]
  3339. );
  3340. }
  3341. tvm.printf(10, pos++, 0x8e, " Indices: %7d ", statsNumIndices);
  3342. tvm.printf(10, pos++, 0x8e, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  3343. tvm.printf(10, pos++, 0x8e, " DVB size: %7d ", _render->m_vboffset);
  3344. tvm.printf(10, pos++, 0x8e, " DIB size: %7d ", _render->m_iboffset);
  3345. double captureMs = double(captureElapsed)*toMs;
  3346. tvm.printf(10, pos++, 0x8e, " Capture: %7.4f [ms]", captureMs);
  3347. uint8_t attr[2] = { 0x89, 0x8a };
  3348. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  3349. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms]", _render->m_waitSubmit*toMs);
  3350. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms]", _render->m_waitRender*toMs);
  3351. min = frameTime;
  3352. max = frameTime;
  3353. }
  3354. blit(this, _textVideoMemBlitter, tvm);
  3355. PIX_ENDEVENT();
  3356. }
  3357. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  3358. {
  3359. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugtext");
  3360. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  3361. PIX_ENDEVENT();
  3362. }
  3363. device->EndScene();
  3364. }
  3365. } /* namespace d3d9 */ } // namespace bgfx
  3366. #else
  3367. namespace bgfx { namespace d3d9
  3368. {
  3369. RendererContextI* rendererCreate()
  3370. {
  3371. return NULL;
  3372. }
  3373. void rendererDestroy()
  3374. {
  3375. }
  3376. } /* namespace d3d9 */ } // namespace bgfx
  3377. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9