renderer_d3d9.cpp 126 KB

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