renderer_d3d9.cpp 120 KB

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