renderer_d3d9.cpp 118 KB

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