renderer_d3d9.cpp 124 KB

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