renderer_d3d9.cpp 125 KB

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