renderer_d3d9.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967
  1. /*
  2. * Copyright 2011-2013 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "bgfx_p.h"
  6. #if BGFX_CONFIG_RENDERER_DIRECT3D9
  7. # include "renderer_d3d9.h"
  8. namespace bgfx
  9. {
  10. static wchar_t s_viewNameW[BGFX_CONFIG_MAX_VIEWS][256];
  11. static const D3DPRIMITIVETYPE s_primType[] =
  12. {
  13. D3DPT_TRIANGLELIST,
  14. D3DPT_LINELIST,
  15. D3DPT_POINTLIST,
  16. };
  17. static const D3DMULTISAMPLE_TYPE s_checkMsaa[] =
  18. {
  19. D3DMULTISAMPLE_NONE,
  20. D3DMULTISAMPLE_2_SAMPLES,
  21. D3DMULTISAMPLE_4_SAMPLES,
  22. D3DMULTISAMPLE_8_SAMPLES,
  23. D3DMULTISAMPLE_16_SAMPLES,
  24. };
  25. static Msaa s_msaa[] =
  26. {
  27. { D3DMULTISAMPLE_NONE, 0 },
  28. { D3DMULTISAMPLE_2_SAMPLES, 0 },
  29. { D3DMULTISAMPLE_4_SAMPLES, 0 },
  30. { D3DMULTISAMPLE_8_SAMPLES, 0 },
  31. { D3DMULTISAMPLE_16_SAMPLES, 0 },
  32. };
  33. struct Blend
  34. {
  35. D3DBLEND m_src;
  36. D3DBLEND m_dst;
  37. bool m_factor;
  38. };
  39. static const Blend s_blendFactor[] =
  40. {
  41. { (D3DBLEND)0, (D3DBLEND)0, false }, // ignored
  42. { D3DBLEND_ZERO, D3DBLEND_ZERO, false },
  43. { D3DBLEND_ONE, D3DBLEND_ONE, false },
  44. { D3DBLEND_SRCCOLOR, D3DBLEND_SRCCOLOR, false },
  45. { D3DBLEND_INVSRCCOLOR, D3DBLEND_INVSRCCOLOR, false },
  46. { D3DBLEND_SRCALPHA, D3DBLEND_SRCALPHA, false },
  47. { D3DBLEND_INVSRCALPHA, D3DBLEND_INVSRCALPHA, false },
  48. { D3DBLEND_DESTALPHA, D3DBLEND_DESTALPHA, false },
  49. { D3DBLEND_INVDESTALPHA, D3DBLEND_INVDESTALPHA, false },
  50. { D3DBLEND_DESTCOLOR, D3DBLEND_DESTCOLOR, false },
  51. { D3DBLEND_INVDESTCOLOR, D3DBLEND_INVDESTCOLOR, false },
  52. { D3DBLEND_SRCALPHASAT, D3DBLEND_ONE, false },
  53. { D3DBLEND_BLENDFACTOR, D3DBLEND_BLENDFACTOR, true },
  54. { D3DBLEND_INVBLENDFACTOR, D3DBLEND_INVBLENDFACTOR, true },
  55. };
  56. static const D3DBLENDOP s_blendEquation[] =
  57. {
  58. D3DBLENDOP_ADD,
  59. D3DBLENDOP_SUBTRACT,
  60. D3DBLENDOP_REVSUBTRACT,
  61. D3DBLENDOP_MIN,
  62. D3DBLENDOP_MAX,
  63. };
  64. static const D3DCMPFUNC s_depthFunc[] =
  65. {
  66. (D3DCMPFUNC)0, // ignored
  67. D3DCMP_LESS,
  68. D3DCMP_LESSEQUAL,
  69. D3DCMP_EQUAL,
  70. D3DCMP_GREATEREQUAL,
  71. D3DCMP_GREATER,
  72. D3DCMP_NOTEQUAL,
  73. D3DCMP_NEVER,
  74. D3DCMP_ALWAYS,
  75. };
  76. static const D3DCMPFUNC s_stencilFunc[] =
  77. {
  78. (D3DCMPFUNC)0, // ignored
  79. D3DCMP_LESS,
  80. D3DCMP_LESSEQUAL,
  81. D3DCMP_EQUAL,
  82. D3DCMP_GREATEREQUAL,
  83. D3DCMP_GREATER,
  84. D3DCMP_NOTEQUAL,
  85. D3DCMP_NEVER,
  86. D3DCMP_ALWAYS,
  87. };
  88. static const D3DSTENCILOP s_stencilOp[] =
  89. {
  90. D3DSTENCILOP_ZERO,
  91. D3DSTENCILOP_KEEP,
  92. D3DSTENCILOP_REPLACE,
  93. D3DSTENCILOP_INCR,
  94. D3DSTENCILOP_INCRSAT,
  95. D3DSTENCILOP_DECR,
  96. D3DSTENCILOP_DECRSAT,
  97. D3DSTENCILOP_INVERT,
  98. };
  99. static const D3DRENDERSTATETYPE s_stencilFuncRs[] =
  100. {
  101. D3DRS_STENCILFUNC,
  102. D3DRS_CCW_STENCILFUNC,
  103. };
  104. static const D3DRENDERSTATETYPE s_stencilFailRs[] =
  105. {
  106. D3DRS_STENCILFAIL,
  107. D3DRS_CCW_STENCILFAIL,
  108. };
  109. static const D3DRENDERSTATETYPE s_stencilZFailRs[] =
  110. {
  111. D3DRS_STENCILZFAIL,
  112. D3DRS_CCW_STENCILZFAIL,
  113. };
  114. static const D3DRENDERSTATETYPE s_stencilZPassRs[] =
  115. {
  116. D3DRS_STENCILPASS,
  117. D3DRS_CCW_STENCILPASS,
  118. };
  119. static const D3DCULL s_cullMode[] =
  120. {
  121. D3DCULL_NONE,
  122. D3DCULL_CW,
  123. D3DCULL_CCW,
  124. };
  125. static const D3DFORMAT s_checkColorFormats[] =
  126. {
  127. D3DFMT_UNKNOWN,
  128. D3DFMT_A8R8G8B8, D3DFMT_UNKNOWN,
  129. D3DFMT_R32F, D3DFMT_R16F, D3DFMT_G16R16, D3DFMT_A8R8G8B8, D3DFMT_UNKNOWN,
  130. D3DFMT_UNKNOWN, // terminator
  131. };
  132. static D3DFORMAT s_colorFormat[] =
  133. {
  134. D3DFMT_UNKNOWN, // ignored
  135. D3DFMT_A8R8G8B8,
  136. D3DFMT_A2B10G10R10,
  137. D3DFMT_A16B16G16R16,
  138. D3DFMT_A16B16G16R16F,
  139. D3DFMT_R16F,
  140. D3DFMT_R32F,
  141. };
  142. static const D3DFORMAT s_depthFormat[] =
  143. {
  144. D3DFMT_UNKNOWN, // ignored
  145. D3DFMT_D16, // D16
  146. D3DFMT_D24X8, // D24
  147. D3DFMT_D24S8, // D24S8
  148. D3DFMT_D32, // D32
  149. D3DFMT_DF16, // D16F
  150. D3DFMT_DF24, // D24F
  151. D3DFMT_D32F_LOCKABLE, // D32F
  152. #if defined(D3D_DISABLE_9EX)
  153. D3DFMT_UNKNOWN, // D0S8
  154. #else
  155. D3DFMT_S8_LOCKABLE, // D0S8
  156. #endif // defined(D3D_DISABLE_9EX)
  157. };
  158. static const D3DTEXTUREADDRESS s_textureAddress[] =
  159. {
  160. D3DTADDRESS_WRAP,
  161. D3DTADDRESS_MIRROR,
  162. D3DTADDRESS_CLAMP,
  163. };
  164. static const D3DTEXTUREFILTERTYPE s_textureFilter[] =
  165. {
  166. D3DTEXF_LINEAR,
  167. D3DTEXF_POINT,
  168. D3DTEXF_ANISOTROPIC,
  169. };
  170. struct TextureFormatInfo
  171. {
  172. D3DFORMAT m_fmt;
  173. };
  174. static TextureFormatInfo s_textureFormat[TextureFormat::Count] =
  175. {
  176. { D3DFMT_DXT1 }, // BC1
  177. { D3DFMT_DXT3 }, // BC2
  178. { D3DFMT_DXT5 }, // BC3
  179. { D3DFMT_UNKNOWN }, // BC4
  180. { D3DFMT_UNKNOWN }, // BC5
  181. { D3DFMT_UNKNOWN }, // ETC1
  182. { D3DFMT_UNKNOWN }, // ETC2
  183. { D3DFMT_UNKNOWN }, // ETC2A
  184. { D3DFMT_UNKNOWN }, // ETC2A1
  185. { D3DFMT_UNKNOWN }, // PTC12
  186. { D3DFMT_UNKNOWN }, // PTC14
  187. { D3DFMT_UNKNOWN }, // PTC12A
  188. { D3DFMT_UNKNOWN }, // PTC14A
  189. { D3DFMT_UNKNOWN }, // PTC22
  190. { D3DFMT_UNKNOWN }, // PTC24
  191. { D3DFMT_UNKNOWN }, // Unknown
  192. { D3DFMT_L8 }, // L8
  193. { D3DFMT_A8R8G8B8 }, // BGRA8
  194. { D3DFMT_A16B16G16R16 }, // RGBA16
  195. { D3DFMT_A16B16G16R16F }, // RGBA16F
  196. { D3DFMT_R5G6B5 }, // R5G6B5
  197. { D3DFMT_A4R4G4B4 }, // RGBA4
  198. { D3DFMT_A1R5G5B5 }, // RGB5A1
  199. { D3DFMT_A2B10G10R10 }, // RGB10A2
  200. { D3DFMT_UNKNOWN }, // UnknownDepth
  201. { D3DFMT_D16 }, // D16
  202. { D3DFMT_D24X8 }, // D24
  203. { D3DFMT_D24S8 }, // D24S8
  204. { D3DFMT_D32 }, // D32
  205. { D3DFMT_DF16 }, // D16F
  206. { D3DFMT_DF24 }, // D24F
  207. { D3DFMT_D32F_LOCKABLE }, // D32F
  208. #if defined(D3D_DISABLE_9EX)
  209. { D3DFMT_UNKNOWN }, // D0S8
  210. #else
  211. { D3DFMT_S8_LOCKABLE }, // D0S8
  212. #endif // defined(D3D_DISABLE_9EX)
  213. };
  214. static ExtendedFormat s_extendedFormats[ExtendedFormat::Count] =
  215. {
  216. { D3DFMT_ATI1, 0, D3DRTYPE_TEXTURE, false },
  217. { D3DFMT_ATI2, 0, D3DRTYPE_TEXTURE, false },
  218. { D3DFMT_DF16, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  219. { D3DFMT_DF24, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  220. { D3DFMT_INST, 0, D3DRTYPE_SURFACE, false },
  221. { D3DFMT_INTZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  222. { D3DFMT_NULL, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  223. { D3DFMT_RESZ, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, false },
  224. { D3DFMT_RAWZ, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, false },
  225. };
  226. static const GUID IID_IDirect3D9 = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } };
  227. static const GUID IID_IDirect3DDevice9Ex = { 0xb18b10ce, 0x2649, 0x405a, { 0x87, 0xf, 0x95, 0xf7, 0x77, 0xd4, 0x31, 0x3a } };
  228. struct RendererContext
  229. {
  230. RendererContext()
  231. : m_d3d9(NULL)
  232. , m_device(NULL)
  233. , m_backBufferColor(NULL)
  234. , m_backBufferDepthStencil(NULL)
  235. , m_captureTexture(NULL)
  236. , m_captureSurface(NULL)
  237. , m_captureResolve(NULL)
  238. , m_flags(BGFX_RESET_NONE)
  239. , m_initialized(false)
  240. , m_amd(false)
  241. , m_nvidia(false)
  242. , m_instancing(false)
  243. , m_rtMsaa(false)
  244. {
  245. m_rt.idx = invalidHandle;
  246. }
  247. void init()
  248. {
  249. D3DFORMAT adapterFormat = D3DFMT_X8R8G8B8;
  250. // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172588%28v=vs.85%29.aspx
  251. memset(&m_params, 0, sizeof(m_params) );
  252. m_params.BackBufferWidth = BGFX_DEFAULT_WIDTH;
  253. m_params.BackBufferHeight = BGFX_DEFAULT_HEIGHT;
  254. m_params.BackBufferFormat = adapterFormat;
  255. m_params.BackBufferCount = 1;
  256. m_params.MultiSampleType = D3DMULTISAMPLE_NONE;
  257. m_params.MultiSampleQuality = 0;
  258. m_params.EnableAutoDepthStencil = TRUE;
  259. m_params.AutoDepthStencilFormat = D3DFMT_D24S8;
  260. m_params.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
  261. #if BX_PLATFORM_WINDOWS
  262. m_params.FullScreen_RefreshRateInHz = 0;
  263. m_params.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  264. m_params.SwapEffect = D3DSWAPEFFECT_DISCARD;
  265. m_params.hDeviceWindow = g_bgfxHwnd;
  266. m_params.Windowed = true;
  267. RECT rect;
  268. GetWindowRect(g_bgfxHwnd, &rect);
  269. m_params.BackBufferWidth = rect.right-rect.left;
  270. m_params.BackBufferHeight = rect.bottom-rect.top;
  271. m_d3d9dll = bx::dlopen("d3d9.dll");
  272. BGFX_FATAL(NULL != m_d3d9dll, Fatal::UnableToInitialize, "Failed to load d3d9.dll.");
  273. #if BGFX_CONFIG_DEBUG_PIX
  274. m_D3DPERF_SetMarker = (D3DPERF_SetMarkerFunc)bx::dlsym(m_d3d9dll, "D3DPERF_SetMarker");
  275. m_D3DPERF_BeginEvent = (D3DPERF_BeginEventFunc)bx::dlsym(m_d3d9dll, "D3DPERF_BeginEvent");
  276. m_D3DPERF_EndEvent = (D3DPERF_EndEventFunc)bx::dlsym(m_d3d9dll, "D3DPERF_EndEvent");
  277. BX_CHECK(NULL != m_D3DPERF_SetMarker
  278. && NULL != m_D3DPERF_BeginEvent
  279. && NULL != m_D3DPERF_EndEvent
  280. , "Failed to initialize PIX events."
  281. );
  282. #endif // BGFX_CONFIG_DEBUG_PIX
  283. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  284. m_d3d9ex = NULL;
  285. Direct3DCreate9ExFn direct3DCreate9Ex = (Direct3DCreate9ExFn)bx::dlsym(m_d3d9dll, "Direct3DCreate9Ex");
  286. if (NULL != direct3DCreate9Ex)
  287. {
  288. direct3DCreate9Ex(D3D_SDK_VERSION, &m_d3d9ex);
  289. DX_CHECK(m_d3d9ex->QueryInterface(IID_IDirect3D9, (void**)&m_d3d9) );
  290. m_pool = D3DPOOL_DEFAULT;
  291. }
  292. else
  293. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  294. {
  295. Direct3DCreate9Fn direct3DCreate9 = (Direct3DCreate9Fn)bx::dlsym(m_d3d9dll, "Direct3DCreate9");
  296. BGFX_FATAL(NULL != direct3DCreate9, Fatal::UnableToInitialize, "Function Direct3DCreate9 not found.");
  297. m_d3d9 = direct3DCreate9(D3D_SDK_VERSION);
  298. m_pool = D3DPOOL_MANAGED;
  299. }
  300. BGFX_FATAL(m_d3d9, Fatal::UnableToInitialize, "Unable to create Direct3D.");
  301. m_adapter = D3DADAPTER_DEFAULT;
  302. m_deviceType = D3DDEVTYPE_HAL;
  303. uint32_t adapterCount = m_d3d9->GetAdapterCount();
  304. for (uint32_t ii = 0; ii < adapterCount; ++ii)
  305. {
  306. D3DADAPTER_IDENTIFIER9 identifier;
  307. HRESULT hr = m_d3d9->GetAdapterIdentifier(ii, 0, &identifier);
  308. if (SUCCEEDED(hr) )
  309. {
  310. BX_TRACE("Adapter #%d", ii);
  311. BX_TRACE("\tDriver: %s", identifier.Driver);
  312. BX_TRACE("\tDescription: %s", identifier.Description);
  313. BX_TRACE("\tDeviceName: %s", identifier.DeviceName);
  314. BX_TRACE("\tVendorId: 0x%08x, DeviceId: 0x%08x, SubSysId: 0x%08x, Revision: 0x%08x"
  315. , identifier.VendorId
  316. , identifier.DeviceId
  317. , identifier.SubSysId
  318. , identifier.Revision
  319. );
  320. #if BGFX_CONFIG_DEBUG_PERFHUD
  321. if (0 != strstr(identifier.Description, "PerfHUD") )
  322. {
  323. m_adapter = ii;
  324. m_deviceType = D3DDEVTYPE_REF;
  325. }
  326. #endif // BGFX_CONFIG_DEBUG_PERFHUD
  327. }
  328. }
  329. DX_CHECK(m_d3d9->GetAdapterIdentifier(m_adapter, 0, &m_identifier) );
  330. m_amd = m_identifier.VendorId == 0x1002;
  331. m_nvidia = m_identifier.VendorId == 0x10de;
  332. uint32_t behaviorFlags[] =
  333. {
  334. D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_PUREDEVICE|D3DCREATE_FPU_PRESERVE,
  335. D3DCREATE_MIXED_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,
  336. D3DCREATE_SOFTWARE_VERTEXPROCESSING|D3DCREATE_FPU_PRESERVE,
  337. };
  338. for (uint32_t ii = 0; ii < BX_COUNTOF(behaviorFlags) && NULL == m_device; ++ii)
  339. {
  340. #if 0 // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  341. DX_CHECK(m_d3d9->CreateDeviceEx(m_adapter
  342. , m_deviceType
  343. , g_bgfxHwnd
  344. , behaviorFlags[ii]
  345. , &m_params
  346. , NULL
  347. , &m_device
  348. ) );
  349. #else
  350. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  351. , m_deviceType
  352. , g_bgfxHwnd
  353. , behaviorFlags[ii]
  354. , &m_params
  355. , &m_device
  356. ) );
  357. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  358. }
  359. BGFX_FATAL(m_device, Fatal::UnableToInitialize, "Unable to create Direct3D9 device.");
  360. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  361. if (NULL != m_d3d9ex)
  362. {
  363. DX_CHECK(m_device->QueryInterface(IID_IDirect3DDevice9Ex, (void**)&m_deviceEx) );
  364. }
  365. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  366. DX_CHECK(m_device->GetDeviceCaps(&m_caps) );
  367. // For shit GPUs that can create DX9 device but can't do simple stuff. GTFO!
  368. BGFX_FATAL( (D3DPTEXTURECAPS_SQUAREONLY & m_caps.TextureCaps) == 0, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_SQUAREONLY");
  369. BGFX_FATAL( (D3DPTEXTURECAPS_MIPMAP & m_caps.TextureCaps) == D3DPTEXTURECAPS_MIPMAP, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_MIPMAP");
  370. BGFX_FATAL( (D3DPTEXTURECAPS_ALPHA & m_caps.TextureCaps) == D3DPTEXTURECAPS_ALPHA, Fatal::MinimumRequiredSpecs, "D3DPTEXTURECAPS_ALPHA");
  371. BGFX_FATAL(m_caps.VertexShaderVersion >= D3DVS_VERSION(2, 0) && m_caps.PixelShaderVersion >= D3DPS_VERSION(2, 1)
  372. , Fatal::MinimumRequiredSpecs
  373. , "Shader Model Version (vs: %x, ps: %x)."
  374. , m_caps.VertexShaderVersion
  375. , m_caps.PixelShaderVersion
  376. );
  377. BX_TRACE("Max vertex shader 3.0 instr. slots: %d", m_caps.MaxVertexShader30InstructionSlots);
  378. BX_TRACE("Max vertex shader constants: %d", m_caps.MaxVertexShaderConst);
  379. BX_TRACE("Max fragment shader 2.0 instr. slots: %d", m_caps.PS20Caps.NumInstructionSlots);
  380. BX_TRACE("Max fragment shader 3.0 instr. slots: %d", m_caps.MaxPixelShader30InstructionSlots);
  381. g_caps.supported |= ( 0
  382. | BGFX_CAPS_TEXTURE_FORMAT_BC1
  383. | BGFX_CAPS_TEXTURE_FORMAT_BC2
  384. | BGFX_CAPS_TEXTURE_FORMAT_BC3
  385. | BGFX_CAPS_TEXTURE_3D
  386. | BGFX_CAPS_TEXTURE_DEPTH_MASK
  387. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  388. | BGFX_CAPS_FRAGMENT_DEPTH
  389. );
  390. g_caps.maxTextureSize = bx::uint32_min(m_caps.MaxTextureWidth, m_caps.MaxTextureHeight);
  391. #if BGFX_CONFIG_RENDERER_USE_EXTENSIONS
  392. BX_TRACE("Extended formats:");
  393. for (uint32_t ii = 0; ii < ExtendedFormat::Count; ++ii)
  394. {
  395. ExtendedFormat& fmt = s_extendedFormats[ii];
  396. fmt.m_supported = SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, fmt.m_usage, fmt.m_type, fmt.m_fmt) );
  397. const char* fourcc = (const char*)&fmt.m_fmt;
  398. BX_TRACE("\t%2d: %c%c%c%c %s", ii, fourcc[0], fourcc[1], fourcc[2], fourcc[3], fmt.m_supported ? "supported" : "");
  399. BX_UNUSED(fourcc);
  400. }
  401. m_instancing = false
  402. || s_extendedFormats[ExtendedFormat::Inst].m_supported
  403. || (m_caps.VertexShaderVersion >= D3DVS_VERSION(3, 0) )
  404. ;
  405. if (m_amd
  406. && s_extendedFormats[ExtendedFormat::Inst].m_supported)
  407. {
  408. // AMD only
  409. m_device->SetRenderState(D3DRS_POINTSIZE, D3DFMT_INST);
  410. }
  411. s_textureFormat[TextureFormat::BC4].m_fmt = s_extendedFormats[ExtendedFormat::Ati1].m_supported ? D3DFMT_ATI1 : D3DFMT_UNKNOWN;
  412. s_textureFormat[TextureFormat::BC5].m_fmt = s_extendedFormats[ExtendedFormat::Ati2].m_supported ? D3DFMT_ATI2 : D3DFMT_UNKNOWN;
  413. g_caps.supported |= 0
  414. | (D3DFMT_UNKNOWN != s_textureFormat[TextureFormat::BC4].m_fmt ? BGFX_CAPS_TEXTURE_FORMAT_BC4 : 0)
  415. | (D3DFMT_UNKNOWN != s_textureFormat[TextureFormat::BC5].m_fmt ? BGFX_CAPS_TEXTURE_FORMAT_BC5 : 0)
  416. ;
  417. g_caps.supported |= m_instancing ? BGFX_CAPS_INSTANCING : 0;
  418. #endif // BGFX_CONFIG_RENDERER_USE_EXTENSIONS
  419. uint32_t index = 1;
  420. for (const D3DFORMAT* fmt = &s_checkColorFormats[index]; *fmt != D3DFMT_UNKNOWN; ++fmt, ++index)
  421. {
  422. for (; *fmt != D3DFMT_UNKNOWN; ++fmt)
  423. {
  424. if (SUCCEEDED(m_d3d9->CheckDeviceFormat(m_adapter, m_deviceType, adapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, *fmt) ) )
  425. {
  426. s_colorFormat[index] = *fmt;
  427. break;
  428. }
  429. }
  430. for (; *fmt != D3DFMT_UNKNOWN; ++fmt);
  431. }
  432. m_fmtDepth = D3DFMT_D24S8;
  433. #elif BX_PLATFORM_XBOX360
  434. m_params.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  435. m_params.DisableAutoBackBuffer = FALSE;
  436. m_params.DisableAutoFrontBuffer = FALSE;
  437. m_params.FrontBufferFormat = D3DFMT_X8R8G8B8;
  438. m_params.FrontBufferColorSpace = D3DCOLORSPACE_RGB;
  439. m_d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  440. BX_TRACE("Creating D3D9 %p", m_d3d9);
  441. XVIDEO_MODE videoMode;
  442. XGetVideoMode(&videoMode);
  443. if (!videoMode.fIsWideScreen)
  444. {
  445. m_params.Flags |= D3DPRESENTFLAG_NO_LETTERBOX;
  446. }
  447. BX_TRACE("Creating device");
  448. DX_CHECK(m_d3d9->CreateDevice(m_adapter
  449. , m_deviceType
  450. , NULL
  451. , D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES
  452. , &m_params
  453. , &m_device
  454. ) );
  455. BX_TRACE("Device %p", m_device);
  456. m_fmtDepth = D3DFMT_D24FS8;
  457. #endif // BX_PLATFORM_WINDOWS
  458. postReset();
  459. m_initialized = true;
  460. }
  461. void shutdown()
  462. {
  463. preReset();
  464. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  465. {
  466. m_indexBuffers[ii].destroy();
  467. }
  468. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  469. {
  470. m_vertexBuffers[ii].destroy();
  471. }
  472. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexShaders); ++ii)
  473. {
  474. m_vertexShaders[ii].destroy();
  475. }
  476. for (uint32_t ii = 0; ii < BX_COUNTOF(m_fragmentShaders); ++ii)
  477. {
  478. m_fragmentShaders[ii].destroy();
  479. }
  480. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  481. {
  482. m_textures[ii].destroy();
  483. }
  484. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexDecls); ++ii)
  485. {
  486. m_vertexDecls[ii].destroy();
  487. }
  488. for (uint32_t ii = 0; ii < BX_COUNTOF(m_renderTargets); ++ii)
  489. {
  490. m_renderTargets[ii].destroy();
  491. }
  492. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  493. if (NULL != m_d3d9ex)
  494. {
  495. DX_RELEASE(m_deviceEx, 1);
  496. DX_RELEASE(m_device, 0);
  497. DX_RELEASE(m_d3d9, 1);
  498. DX_RELEASE(m_d3d9ex, 0);
  499. }
  500. else
  501. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  502. {
  503. DX_RELEASE(m_device, 0);
  504. DX_RELEASE(m_d3d9, 0);
  505. }
  506. #if BX_PLATFORM_WINDOWS
  507. bx::dlclose(m_d3d9dll);
  508. #endif // BX_PLATFORM_WINDOWS
  509. m_initialized = false;
  510. }
  511. void updateMsaa()
  512. {
  513. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_checkMsaa); ++ii)
  514. {
  515. D3DMULTISAMPLE_TYPE msaa = s_checkMsaa[ii];
  516. DWORD quality;
  517. HRESULT hr = m_d3d9->CheckDeviceMultiSampleType(m_adapter
  518. , m_deviceType
  519. , m_params.BackBufferFormat
  520. , m_params.Windowed
  521. , msaa
  522. , &quality
  523. );
  524. if (SUCCEEDED(hr) )
  525. {
  526. s_msaa[ii].m_type = msaa;
  527. s_msaa[ii].m_quality = bx::uint32_imax(0, quality-1);
  528. last = ii;
  529. }
  530. else
  531. {
  532. s_msaa[ii] = s_msaa[last];
  533. }
  534. }
  535. }
  536. void updateResolution(const Resolution& _resolution)
  537. {
  538. if (m_params.BackBufferWidth != _resolution.m_width
  539. || m_params.BackBufferHeight != _resolution.m_height
  540. || m_flags != _resolution.m_flags)
  541. {
  542. m_flags = _resolution.m_flags;
  543. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  544. m_textVideoMem.clear();
  545. #if BX_PLATFORM_WINDOWS
  546. D3DDEVICE_CREATION_PARAMETERS dcp;
  547. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  548. D3DDISPLAYMODE dm;
  549. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  550. m_params.BackBufferFormat = dm.Format;
  551. #endif // BX_PLATFORM_WINDOWS
  552. m_params.BackBufferWidth = _resolution.m_width;
  553. m_params.BackBufferHeight = _resolution.m_height;
  554. m_params.FullScreen_RefreshRateInHz = BGFX_RESET_FULLSCREEN == (m_flags&BGFX_RESET_FULLSCREEN_MASK) ? 60 : 0;
  555. m_params.PresentationInterval = !!(m_flags&BGFX_RESET_VSYNC) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
  556. updateMsaa();
  557. Msaa& msaa = s_msaa[(m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  558. m_params.MultiSampleType = msaa.m_type;
  559. m_params.MultiSampleQuality = msaa.m_quality;
  560. preReset();
  561. DX_CHECK(m_device->Reset(&m_params) );
  562. postReset();
  563. }
  564. }
  565. void setRenderTarget(RenderTargetHandle _rt, bool _msaa = true)
  566. {
  567. if (!isValid(_rt) )
  568. {
  569. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  570. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  571. }
  572. else
  573. {
  574. RenderTarget& renderTarget = m_renderTargets[_rt.idx];
  575. if (NULL != renderTarget.m_rt)
  576. {
  577. DX_CHECK(m_device->SetRenderTarget(0, renderTarget.m_rt) );
  578. }
  579. else
  580. {
  581. DX_CHECK(m_device->SetRenderTarget(0, renderTarget.m_color) );
  582. }
  583. DX_CHECK(m_device->SetDepthStencilSurface(NULL != renderTarget.m_depth ? renderTarget.m_depth : m_backBufferDepthStencil) );
  584. }
  585. if (isValid(m_rt)
  586. && m_rt.idx != _rt.idx
  587. && m_rtMsaa)
  588. {
  589. RenderTarget& renderTarget = m_renderTargets[m_rt.idx];
  590. if (!renderTarget.m_depthOnly
  591. && renderTarget.m_rt != NULL)
  592. {
  593. renderTarget.resolve();
  594. }
  595. }
  596. m_rt = _rt;
  597. m_rtMsaa = _msaa;
  598. }
  599. void setShaderConstantF(uint8_t _flags, uint16_t _regIndex, const float* _val, uint16_t _numRegs)
  600. {
  601. if (_flags&BGFX_UNIFORM_FRAGMENTBIT)
  602. {
  603. DX_CHECK(m_device->SetPixelShaderConstantF(_regIndex, _val, _numRegs) );
  604. }
  605. else
  606. {
  607. DX_CHECK(m_device->SetVertexShaderConstantF(_regIndex, _val, _numRegs) );
  608. }
  609. }
  610. void reset()
  611. {
  612. preReset();
  613. HRESULT hr;
  614. do
  615. {
  616. hr = m_device->Reset(&m_params);
  617. } while (FAILED(hr) );
  618. postReset();
  619. }
  620. bool isLost(HRESULT _hr) const
  621. {
  622. return D3DERR_DEVICELOST == _hr
  623. || D3DERR_DRIVERINTERNALERROR == _hr
  624. #if !defined(D3D_DISABLE_9EX)
  625. || D3DERR_DEVICEHUNG == _hr
  626. || D3DERR_DEVICEREMOVED == _hr
  627. #endif // !defined(D3D_DISABLE_9EX)
  628. ;
  629. }
  630. void flip()
  631. {
  632. if (NULL != m_device)
  633. {
  634. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  635. if (NULL != m_deviceEx)
  636. {
  637. DX_CHECK(m_deviceEx->WaitForVBlank(0) );
  638. }
  639. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  640. HRESULT hr;
  641. hr = m_device->Present(NULL, NULL, NULL, NULL);
  642. #if BX_PLATFORM_WINDOWS
  643. if (isLost(hr) )
  644. {
  645. do
  646. {
  647. do
  648. {
  649. hr = m_device->TestCooperativeLevel();
  650. }
  651. while (D3DERR_DEVICENOTRESET != hr);
  652. reset();
  653. hr = m_device->TestCooperativeLevel();
  654. }
  655. while (FAILED(hr) );
  656. }
  657. else if (FAILED(hr) )
  658. {
  659. BX_TRACE("Present failed with err 0x%08x.", hr);
  660. }
  661. #endif // BX_PLATFORM_
  662. }
  663. }
  664. void preReset()
  665. {
  666. invalidateSamplerState();
  667. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  668. {
  669. DX_CHECK(m_device->SetTexture(stage, NULL) );
  670. }
  671. DX_CHECK(m_device->SetRenderTarget(0, m_backBufferColor) );
  672. DX_CHECK(m_device->SetDepthStencilSurface(m_backBufferDepthStencil) );
  673. DX_CHECK(m_device->SetVertexShader(NULL) );
  674. DX_CHECK(m_device->SetPixelShader(NULL) );
  675. DX_CHECK(m_device->SetStreamSource(0, NULL, 0, 0) );
  676. DX_CHECK(m_device->SetIndices(NULL) );
  677. DX_RELEASE(m_backBufferColor, 0);
  678. DX_RELEASE(m_backBufferDepthStencil, 0);
  679. capturePreReset();
  680. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  681. {
  682. m_indexBuffers[ii].preReset();
  683. }
  684. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  685. {
  686. m_vertexBuffers[ii].preReset();
  687. }
  688. for (uint32_t ii = 0; ii < BX_COUNTOF(m_renderTargets); ++ii)
  689. {
  690. m_renderTargets[ii].preReset();
  691. }
  692. }
  693. void postReset()
  694. {
  695. DX_CHECK(m_device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_backBufferColor) );
  696. DX_CHECK(m_device->GetDepthStencilSurface(&m_backBufferDepthStencil) );
  697. capturePostReset();
  698. for (uint32_t ii = 0; ii < BX_COUNTOF(m_indexBuffers); ++ii)
  699. {
  700. m_indexBuffers[ii].postReset();
  701. }
  702. for (uint32_t ii = 0; ii < BX_COUNTOF(m_vertexBuffers); ++ii)
  703. {
  704. m_vertexBuffers[ii].postReset();
  705. }
  706. for (uint32_t ii = 0; ii < BX_COUNTOF(m_renderTargets); ++ii)
  707. {
  708. m_renderTargets[ii].postReset();
  709. }
  710. }
  711. void invalidateSamplerState()
  712. {
  713. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  714. {
  715. m_samplerFlags[stage] = UINT32_MAX;
  716. }
  717. }
  718. void setSamplerState(uint8_t _stage, uint32_t _flags)
  719. {
  720. const uint32_t flags = _flags&(~BGFX_TEXTURE_RESERVED_MASK);
  721. if (m_samplerFlags[_stage] != flags)
  722. {
  723. m_samplerFlags[_stage] = flags;
  724. IDirect3DDevice9* device = m_device;
  725. D3DTEXTUREADDRESS tau = s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT];
  726. D3DTEXTUREADDRESS tav = s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT];
  727. D3DTEXTUREADDRESS taw = s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT];
  728. D3DTEXTUREFILTERTYPE minFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT];
  729. D3DTEXTUREFILTERTYPE magFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT];
  730. D3DTEXTUREFILTERTYPE mipFilter = s_textureFilter[(_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT];
  731. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSU, tau) );
  732. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSV, tav) );
  733. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MINFILTER, minFilter) );
  734. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MAGFILTER, magFilter) );
  735. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_MIPFILTER, mipFilter) );
  736. DX_CHECK(device->SetSamplerState(_stage, D3DSAMP_ADDRESSW, taw) );
  737. }
  738. }
  739. void capturePreReset()
  740. {
  741. if (NULL != m_captureSurface)
  742. {
  743. g_callback->captureEnd();
  744. }
  745. DX_RELEASE(m_captureSurface, 1);
  746. DX_RELEASE(m_captureTexture, 0);
  747. DX_RELEASE(m_captureResolve, 0);
  748. }
  749. void capturePostReset()
  750. {
  751. if (m_flags&BGFX_RESET_CAPTURE)
  752. {
  753. uint32_t width = m_params.BackBufferWidth;
  754. uint32_t height = m_params.BackBufferHeight;
  755. D3DFORMAT fmt = m_params.BackBufferFormat;
  756. DX_CHECK(m_device->CreateTexture(width
  757. , height
  758. , 1
  759. , 0
  760. , fmt
  761. , D3DPOOL_SYSTEMMEM
  762. , &m_captureTexture
  763. , NULL
  764. ) );
  765. DX_CHECK(m_captureTexture->GetSurfaceLevel(0
  766. , &m_captureSurface
  767. ) );
  768. if (m_params.MultiSampleType != D3DMULTISAMPLE_NONE)
  769. {
  770. DX_CHECK(m_device->CreateRenderTarget(width
  771. , height
  772. , fmt
  773. , D3DMULTISAMPLE_NONE
  774. , 0
  775. , false
  776. , &m_captureResolve
  777. , NULL
  778. ) );
  779. }
  780. g_callback->captureBegin(width, height, width*4, TextureFormat::BGRA8, false);
  781. }
  782. }
  783. void capture()
  784. {
  785. if (NULL != m_captureSurface)
  786. {
  787. IDirect3DSurface9* resolve = m_backBufferColor;
  788. if (NULL != m_captureResolve)
  789. {
  790. resolve = m_captureResolve;
  791. DX_CHECK(m_device->StretchRect(m_backBufferColor
  792. , 0
  793. , m_captureResolve
  794. , NULL
  795. , D3DTEXF_NONE
  796. ) );
  797. }
  798. HRESULT hr = m_device->GetRenderTargetData(resolve, m_captureSurface);
  799. if (SUCCEEDED(hr) )
  800. {
  801. D3DLOCKED_RECT rect;
  802. DX_CHECK(m_captureSurface->LockRect(&rect
  803. , NULL
  804. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  805. ) );
  806. g_callback->captureFrame(rect.pBits, m_params.BackBufferHeight*rect.Pitch);
  807. DX_CHECK(m_captureSurface->UnlockRect() );
  808. }
  809. }
  810. }
  811. void saveScreenShot(const char* _filePath)
  812. {
  813. #if BX_PLATFORM_WINDOWS
  814. IDirect3DSurface9* surface;
  815. D3DDEVICE_CREATION_PARAMETERS dcp;
  816. DX_CHECK(m_device->GetCreationParameters(&dcp) );
  817. D3DDISPLAYMODE dm;
  818. DX_CHECK(m_d3d9->GetAdapterDisplayMode(dcp.AdapterOrdinal, &dm) );
  819. DX_CHECK(m_device->CreateOffscreenPlainSurface(dm.Width
  820. , dm.Height
  821. , D3DFMT_A8R8G8B8
  822. , D3DPOOL_SCRATCH
  823. , &surface
  824. , NULL
  825. ) );
  826. DX_CHECK(m_device->GetFrontBufferData(0, surface) );
  827. D3DLOCKED_RECT rect;
  828. DX_CHECK(surface->LockRect(&rect
  829. , NULL
  830. , D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY
  831. ) );
  832. RECT rc;
  833. GetClientRect(g_bgfxHwnd, &rc);
  834. POINT point;
  835. point.x = rc.left;
  836. point.y = rc.top;
  837. ClientToScreen(g_bgfxHwnd, &point);
  838. uint8_t* data = (uint8_t*)rect.pBits;
  839. uint32_t bytesPerPixel = rect.Pitch/dm.Width;
  840. g_callback->screenShot(_filePath
  841. , m_params.BackBufferWidth
  842. , m_params.BackBufferHeight
  843. , rect.Pitch
  844. , &data[point.y*rect.Pitch+point.x*bytesPerPixel]
  845. , m_params.BackBufferHeight*rect.Pitch
  846. , false
  847. );
  848. DX_CHECK(surface->UnlockRect() );
  849. DX_RELEASE(surface, 0);
  850. #endif // BX_PLATFORM_WINDOWS
  851. }
  852. #if BX_PLATFORM_WINDOWS
  853. D3DCAPS9 m_caps;
  854. # if BGFX_CONFIG_DEBUG_PIX
  855. D3DPERF_SetMarkerFunc m_D3DPERF_SetMarker;
  856. D3DPERF_BeginEventFunc m_D3DPERF_BeginEvent;
  857. D3DPERF_EndEventFunc m_D3DPERF_EndEvent;
  858. # endif // BGFX_CONFIG_DEBUG_PIX
  859. #endif // BX_PLATFORM_WINDOWS
  860. #if BGFX_CONFIG_RENDERER_DIRECT3D9EX
  861. IDirect3D9Ex* m_d3d9ex;
  862. IDirect3DDevice9Ex* m_deviceEx;
  863. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9EX
  864. IDirect3D9* m_d3d9;
  865. IDirect3DDevice9* m_device;
  866. D3DPOOL m_pool;
  867. IDirect3DSurface9* m_backBufferColor;
  868. IDirect3DSurface9* m_backBufferDepthStencil;
  869. IDirect3DTexture9* m_captureTexture;
  870. IDirect3DSurface9* m_captureSurface;
  871. IDirect3DSurface9* m_captureResolve;
  872. IDirect3DVertexDeclaration9* m_instanceDataDecls[BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  873. void* m_d3d9dll;
  874. uint32_t m_adapter;
  875. D3DDEVTYPE m_deviceType;
  876. D3DPRESENT_PARAMETERS m_params;
  877. uint32_t m_flags;
  878. D3DADAPTER_IDENTIFIER9 m_identifier;
  879. bool m_initialized;
  880. bool m_amd;
  881. bool m_nvidia;
  882. bool m_instancing;
  883. D3DFORMAT m_fmtDepth;
  884. IndexBuffer m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  885. VertexBuffer m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  886. Shader m_vertexShaders[BGFX_CONFIG_MAX_VERTEX_SHADERS];
  887. Shader m_fragmentShaders[BGFX_CONFIG_MAX_FRAGMENT_SHADERS];
  888. Program m_program[BGFX_CONFIG_MAX_PROGRAMS];
  889. Texture m_textures[BGFX_CONFIG_MAX_TEXTURES];
  890. VertexDeclaration m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  891. RenderTarget m_renderTargets[BGFX_CONFIG_MAX_RENDER_TARGETS];
  892. UniformRegistry m_uniformReg;
  893. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  894. uint32_t m_samplerFlags[BGFX_STATE_TEX_COUNT];
  895. Texture* m_updateTexture;
  896. uint8_t* m_updateTextureBits;
  897. uint32_t m_updateTexturePitch;
  898. uint8_t m_updateTextureSide;
  899. uint8_t m_updateTextureMip;
  900. TextVideoMem m_textVideoMem;
  901. RenderTargetHandle m_rt;
  902. bool m_rtMsaa;
  903. };
  904. static RendererContext* s_renderCtx;
  905. void IndexBuffer::create(uint32_t _size, void* _data)
  906. {
  907. m_size = _size;
  908. m_dynamic = NULL == _data;
  909. uint32_t usage = D3DUSAGE_WRITEONLY;
  910. D3DPOOL pool = s_renderCtx->m_pool;
  911. if (m_dynamic)
  912. {
  913. usage |= D3DUSAGE_DYNAMIC;
  914. pool = D3DPOOL_DEFAULT;
  915. }
  916. DX_CHECK(s_renderCtx->m_device->CreateIndexBuffer(m_size
  917. , usage
  918. , D3DFMT_INDEX16
  919. , pool
  920. , &m_ptr
  921. , NULL
  922. ) );
  923. if (NULL != _data)
  924. {
  925. update(0, _size, _data);
  926. }
  927. }
  928. void IndexBuffer::preReset()
  929. {
  930. if (m_dynamic)
  931. {
  932. DX_RELEASE(m_ptr, 0);
  933. }
  934. }
  935. void IndexBuffer::postReset()
  936. {
  937. if (m_dynamic)
  938. {
  939. DX_CHECK(s_renderCtx->m_device->CreateIndexBuffer(m_size
  940. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  941. , D3DFMT_INDEX16
  942. , D3DPOOL_DEFAULT
  943. , &m_ptr
  944. , NULL
  945. ) );
  946. }
  947. }
  948. void VertexBuffer::create(uint32_t _size, void* _data, VertexDeclHandle _declHandle)
  949. {
  950. m_size = _size;
  951. m_decl = _declHandle;
  952. m_dynamic = NULL == _data;
  953. uint32_t usage = D3DUSAGE_WRITEONLY;
  954. D3DPOOL pool = s_renderCtx->m_pool;
  955. if (m_dynamic)
  956. {
  957. usage |= D3DUSAGE_DYNAMIC;
  958. pool = D3DPOOL_DEFAULT;
  959. }
  960. DX_CHECK(s_renderCtx->m_device->CreateVertexBuffer(m_size
  961. , usage
  962. , 0
  963. , pool
  964. , &m_ptr
  965. , NULL
  966. ) );
  967. if (NULL != _data)
  968. {
  969. update(0, _size, _data);
  970. }
  971. }
  972. void VertexBuffer::preReset()
  973. {
  974. if (m_dynamic)
  975. {
  976. DX_RELEASE(m_ptr, 0);
  977. }
  978. }
  979. void VertexBuffer::postReset()
  980. {
  981. if (m_dynamic)
  982. {
  983. DX_CHECK(s_renderCtx->m_device->CreateVertexBuffer(m_size
  984. , D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC
  985. , 0
  986. , D3DPOOL_DEFAULT
  987. , &m_ptr
  988. , NULL
  989. ) );
  990. }
  991. }
  992. static const D3DVERTEXELEMENT9 s_attrib[Attrib::Count+1] =
  993. {
  994. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
  995. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
  996. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
  997. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 },
  998. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 },
  999. { 0, 0, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
  1000. { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
  1001. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
  1002. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
  1003. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
  1004. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
  1005. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 },
  1006. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 },
  1007. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 6 },
  1008. { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 7 },
  1009. D3DDECL_END()
  1010. };
  1011. static const D3DDECLTYPE s_attribType[AttribType::Count][4][2] =
  1012. {
  1013. {
  1014. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1015. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1016. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1017. { D3DDECLTYPE_UBYTE4, D3DDECLTYPE_UBYTE4N },
  1018. },
  1019. {
  1020. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1021. { D3DDECLTYPE_SHORT2, D3DDECLTYPE_SHORT2N },
  1022. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1023. { D3DDECLTYPE_SHORT4, D3DDECLTYPE_SHORT4N },
  1024. },
  1025. {
  1026. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1027. { D3DDECLTYPE_FLOAT16_2, D3DDECLTYPE_FLOAT16_2 },
  1028. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1029. { D3DDECLTYPE_FLOAT16_4, D3DDECLTYPE_FLOAT16_4 },
  1030. },
  1031. {
  1032. { D3DDECLTYPE_FLOAT1, D3DDECLTYPE_FLOAT1 },
  1033. { D3DDECLTYPE_FLOAT2, D3DDECLTYPE_FLOAT2 },
  1034. { D3DDECLTYPE_FLOAT3, D3DDECLTYPE_FLOAT3 },
  1035. { D3DDECLTYPE_FLOAT4, D3DDECLTYPE_FLOAT4 },
  1036. },
  1037. };
  1038. static D3DVERTEXELEMENT9* fillVertexDecl(D3DVERTEXELEMENT9* _out, const VertexDecl& _decl)
  1039. {
  1040. D3DVERTEXELEMENT9* elem = _out;
  1041. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  1042. {
  1043. if (0xff != _decl.m_attributes[attr])
  1044. {
  1045. uint8_t num;
  1046. AttribType::Enum type;
  1047. bool normalized;
  1048. bool asInt;
  1049. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  1050. memcpy(elem, &s_attrib[attr], sizeof(D3DVERTEXELEMENT9) );
  1051. elem->Type = s_attribType[type][num-1][normalized];
  1052. elem->Offset = _decl.m_offset[attr];
  1053. ++elem;
  1054. }
  1055. }
  1056. return elem;
  1057. }
  1058. static IDirect3DVertexDeclaration9* createVertexDecl(const VertexDecl& _decl, uint8_t _numInstanceData)
  1059. {
  1060. D3DVERTEXELEMENT9 vertexElements[Attrib::Count+1+BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT];
  1061. D3DVERTEXELEMENT9* elem = fillVertexDecl(vertexElements, _decl);
  1062. const D3DVERTEXELEMENT9 inst = { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 };
  1063. for (uint32_t ii = 0; ii < _numInstanceData; ++ii)
  1064. {
  1065. memcpy(elem, &inst, sizeof(D3DVERTEXELEMENT9) );
  1066. elem->UsageIndex = 8-_numInstanceData+ii;
  1067. elem->Offset = ii*16;
  1068. ++elem;
  1069. }
  1070. memcpy(elem, &s_attrib[Attrib::Count], sizeof(D3DVERTEXELEMENT9) );
  1071. IDirect3DVertexDeclaration9* ptr;
  1072. DX_CHECK(s_renderCtx->m_device->CreateVertexDeclaration(vertexElements, &ptr) );
  1073. return ptr;
  1074. }
  1075. void VertexDeclaration::create(const VertexDecl& _decl)
  1076. {
  1077. memcpy(&m_decl, &_decl, sizeof(VertexDecl) );
  1078. dump(m_decl);
  1079. m_ptr = createVertexDecl(_decl, 0);
  1080. }
  1081. void Shader::create(bool _fragment, const Memory* _mem)
  1082. {
  1083. bx::MemoryReader reader(_mem->data, _mem->size);
  1084. uint32_t magic;
  1085. bx::read(&reader, magic);
  1086. uint32_t iohash;
  1087. bx::read(&reader, iohash);
  1088. uint16_t count;
  1089. bx::read(&reader, count);
  1090. m_numPredefined = 0;
  1091. BX_TRACE("Shader consts %d", count);
  1092. uint8_t fragmentBit = _fragment ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  1093. if (0 < count)
  1094. {
  1095. m_constantBuffer = ConstantBuffer::create(1024);
  1096. for (uint32_t ii = 0; ii < count; ++ii)
  1097. {
  1098. uint8_t nameSize;
  1099. bx::read(&reader, nameSize);
  1100. char name[256];
  1101. bx::read(&reader, &name, nameSize);
  1102. name[nameSize] = '\0';
  1103. uint8_t type;
  1104. bx::read(&reader, type);
  1105. uint8_t num;
  1106. bx::read(&reader, num);
  1107. uint16_t regIndex;
  1108. bx::read(&reader, regIndex);
  1109. uint16_t regCount;
  1110. bx::read(&reader, regCount);
  1111. const char* kind = "invalid";
  1112. const void* data = NULL;
  1113. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  1114. if (PredefinedUniform::Count != predefined)
  1115. {
  1116. kind = "predefined";
  1117. m_predefined[m_numPredefined].m_loc = regIndex;
  1118. m_predefined[m_numPredefined].m_count = regCount;
  1119. m_predefined[m_numPredefined].m_type = predefined|fragmentBit;
  1120. m_numPredefined++;
  1121. }
  1122. else
  1123. {
  1124. const UniformInfo* info = s_renderCtx->m_uniformReg.find(name);
  1125. BX_CHECK(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  1126. if (NULL != info)
  1127. {
  1128. kind = "user";
  1129. data = info->m_data;
  1130. m_constantBuffer->writeUniformRef( (UniformType::Enum)(type|fragmentBit), regIndex, data, regCount);
  1131. }
  1132. }
  1133. BX_TRACE("\t%s: %s, type %2d, num %2d, r.index %3d, r.count %2d"
  1134. , kind
  1135. , name
  1136. , type
  1137. , num
  1138. , regIndex
  1139. , regCount
  1140. );
  1141. BX_UNUSED(kind);
  1142. }
  1143. m_constantBuffer->finish();
  1144. }
  1145. uint16_t shaderSize;
  1146. bx::read(&reader, shaderSize);
  1147. const DWORD* code = (const DWORD*)reader.getDataPtr();
  1148. if (_fragment)
  1149. {
  1150. DX_CHECK(s_renderCtx->m_device->CreatePixelShader(code, (IDirect3DPixelShader9**)&m_ptr) );
  1151. BGFX_FATAL(NULL != m_ptr, bgfx::Fatal::InvalidShader, "Failed to create fragment shader.");
  1152. }
  1153. else
  1154. {
  1155. DX_CHECK(s_renderCtx->m_device->CreateVertexShader(code, (IDirect3DVertexShader9**)&m_ptr) );
  1156. BGFX_FATAL(NULL != m_ptr, bgfx::Fatal::InvalidShader, "Failed to create vertex shader.");
  1157. }
  1158. }
  1159. void Texture::createTexture(uint32_t _width, uint32_t _height, uint8_t _numMips, D3DFORMAT _fmt)
  1160. {
  1161. m_type = Texture2D;
  1162. DX_CHECK(s_renderCtx->m_device->CreateTexture(_width
  1163. , _height
  1164. , _numMips
  1165. , 0
  1166. , _fmt
  1167. , s_renderCtx->m_pool
  1168. , &m_texture2d
  1169. , NULL
  1170. ) );
  1171. BGFX_FATAL(NULL != m_texture2d, Fatal::UnableToCreateTexture, "Failed to create texture (size: %dx%d, mips: %d, fmt: 0x%08x)."
  1172. , _width
  1173. , _height
  1174. , _numMips
  1175. , _fmt
  1176. );
  1177. }
  1178. void Texture::createVolumeTexture(uint32_t _width, uint32_t _height, uint32_t _depth, uint32_t _numMips, D3DFORMAT _fmt)
  1179. {
  1180. m_type = Texture3D;
  1181. DX_CHECK(s_renderCtx->m_device->CreateVolumeTexture(_width
  1182. , _height
  1183. , _depth
  1184. , _numMips
  1185. , 0
  1186. , _fmt
  1187. , s_renderCtx->m_pool
  1188. , &m_texture3d
  1189. , NULL
  1190. ) );
  1191. BGFX_FATAL(NULL != m_texture3d, Fatal::UnableToCreateTexture, "Failed to create volume texture (size: %dx%dx%d, mips: %d, fmt: 0x%08x)."
  1192. , _width
  1193. , _height
  1194. , _depth
  1195. , _numMips
  1196. , _fmt
  1197. );
  1198. }
  1199. void Texture::createCubeTexture(uint32_t _edge, uint32_t _numMips, D3DFORMAT _fmt)
  1200. {
  1201. m_type = TextureCube;
  1202. DX_CHECK(s_renderCtx->m_device->CreateCubeTexture(_edge
  1203. , _numMips
  1204. , 0
  1205. , _fmt
  1206. , s_renderCtx->m_pool
  1207. , &m_textureCube
  1208. , NULL
  1209. ) );
  1210. BGFX_FATAL(NULL != m_textureCube, Fatal::UnableToCreateTexture, "Failed to create cube texture (edge: %d, mips: %d, fmt: 0x%08x)."
  1211. , _edge
  1212. , _numMips
  1213. , _fmt
  1214. );
  1215. }
  1216. uint8_t* Texture::lock(uint8_t _side, uint8_t _lod, uint32_t& _pitch, uint32_t& _slicePitch, const Rect* _rect)
  1217. {
  1218. switch (m_type)
  1219. {
  1220. case Texture2D:
  1221. {
  1222. D3DLOCKED_RECT lockedRect;
  1223. if (NULL != _rect)
  1224. {
  1225. RECT rect;
  1226. rect.left = _rect->m_x;
  1227. rect.top = _rect->m_y;
  1228. rect.right = rect.left + _rect->m_width;
  1229. rect.bottom = rect.top + _rect->m_height;
  1230. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, &rect, 0) );
  1231. }
  1232. else
  1233. {
  1234. DX_CHECK(m_texture2d->LockRect(_lod, &lockedRect, NULL, 0) );
  1235. }
  1236. _pitch = lockedRect.Pitch;
  1237. _slicePitch = 0;
  1238. return (uint8_t*)lockedRect.pBits;
  1239. }
  1240. case Texture3D:
  1241. {
  1242. D3DLOCKED_BOX box;
  1243. DX_CHECK(m_texture3d->LockBox(_lod, &box, NULL, 0) );
  1244. _pitch = box.RowPitch;
  1245. _slicePitch = box.SlicePitch;
  1246. return (uint8_t*)box.pBits;
  1247. }
  1248. case TextureCube:
  1249. {
  1250. D3DLOCKED_RECT lockedRect;
  1251. if (NULL != _rect)
  1252. {
  1253. RECT rect;
  1254. rect.left = _rect->m_x;
  1255. rect.top = _rect->m_y;
  1256. rect.right = rect.left + _rect->m_width;
  1257. rect.bottom = rect.top + _rect->m_height;
  1258. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, &rect, 0) );
  1259. }
  1260. else
  1261. {
  1262. DX_CHECK(m_textureCube->LockRect(D3DCUBEMAP_FACES(_side), _lod, &lockedRect, NULL, 0) );
  1263. }
  1264. _pitch = lockedRect.Pitch;
  1265. _slicePitch = 0;
  1266. return (uint8_t*)lockedRect.pBits;
  1267. }
  1268. }
  1269. BX_CHECK(false, "You should not be here.");
  1270. _pitch = 0;
  1271. _slicePitch = 0;
  1272. return NULL;
  1273. }
  1274. void Texture::unlock(uint8_t _side, uint8_t _lod)
  1275. {
  1276. switch (m_type)
  1277. {
  1278. case Texture2D:
  1279. {
  1280. DX_CHECK(m_texture2d->UnlockRect(_lod) );
  1281. }
  1282. return;
  1283. case Texture3D:
  1284. {
  1285. DX_CHECK(m_texture3d->UnlockBox(_lod) );
  1286. }
  1287. return;
  1288. case TextureCube:
  1289. {
  1290. DX_CHECK(m_textureCube->UnlockRect(D3DCUBEMAP_FACES(_side), _lod) );
  1291. }
  1292. return;
  1293. }
  1294. BX_CHECK(false, "You should not be here.");
  1295. }
  1296. void Texture::dirty(uint8_t _side, const Rect& _rect, uint16_t _z, uint16_t _depth)
  1297. {
  1298. switch (m_type)
  1299. {
  1300. case Texture2D:
  1301. {
  1302. RECT rect;
  1303. rect.left = _rect.m_x;
  1304. rect.top = _rect.m_y;
  1305. rect.right = rect.left + _rect.m_width;
  1306. rect.bottom = rect.top + _rect.m_height;
  1307. DX_CHECK(m_texture2d->AddDirtyRect(&rect) );
  1308. }
  1309. return;
  1310. case Texture3D:
  1311. {
  1312. D3DBOX box;
  1313. box.Left = _rect.m_x;
  1314. box.Top = _rect.m_y;
  1315. box.Right = box.Left + _rect.m_width;
  1316. box.Bottom = box.Top + _rect.m_height;
  1317. box.Front = _z;
  1318. box.Back = box.Front + _depth;
  1319. DX_CHECK(m_texture3d->AddDirtyBox(&box) );
  1320. }
  1321. return;
  1322. case TextureCube:
  1323. {
  1324. RECT rect;
  1325. rect.left = _rect.m_x;
  1326. rect.top = _rect.m_y;
  1327. rect.right = rect.left + _rect.m_width;
  1328. rect.bottom = rect.top + _rect.m_height;
  1329. DX_CHECK(m_textureCube->AddDirtyRect(D3DCUBEMAP_FACES(_side), &rect) );
  1330. }
  1331. return;
  1332. }
  1333. BX_CHECK(false, "You should not be here.");
  1334. }
  1335. void Texture::create(const Memory* _mem, uint32_t _flags)
  1336. {
  1337. m_flags = _flags;
  1338. ImageContainer imageContainer;
  1339. if (imageParse(imageContainer, _mem->data, _mem->size) )
  1340. {
  1341. m_requestedFormat = (uint8_t)imageContainer.m_format;
  1342. m_textureFormat = (uint8_t)imageContainer.m_format;
  1343. const TextureFormatInfo& tfi = s_textureFormat[m_requestedFormat];
  1344. const bool convert = D3DFMT_UNKNOWN == tfi.m_fmt;
  1345. uint8_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  1346. if (convert)
  1347. {
  1348. m_textureFormat = (uint8_t)TextureFormat::BGRA8;
  1349. bpp = 32;
  1350. }
  1351. D3DFORMAT format = s_textureFormat[m_textureFormat].m_fmt;
  1352. if (imageContainer.m_cubeMap)
  1353. {
  1354. createCubeTexture(imageContainer.m_width, imageContainer.m_numMips, format);
  1355. }
  1356. else if (imageContainer.m_depth > 1)
  1357. {
  1358. createVolumeTexture(imageContainer.m_width, imageContainer.m_height, imageContainer.m_depth, imageContainer.m_numMips, format);
  1359. }
  1360. else
  1361. {
  1362. createTexture(imageContainer.m_width, imageContainer.m_height, imageContainer.m_numMips, format);
  1363. }
  1364. // For BC4 and B5 in DX9 LockRect returns wrong number of
  1365. // bytes. If actual mip size is used it causes memory corruption.
  1366. // http://www.aras-p.info/texts/D3D9GPUHacks.html#3dc
  1367. const bool useMipSize = true
  1368. && imageContainer.m_format != TextureFormat::BC4
  1369. && imageContainer.m_format != TextureFormat::BC5
  1370. ;
  1371. const bool compressed = TextureFormat::Unknown > m_requestedFormat;
  1372. const uint32_t min = compressed ? 4 : 1;
  1373. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  1374. {
  1375. uint32_t width = imageContainer.m_width;
  1376. uint32_t height = imageContainer.m_height;
  1377. uint32_t depth = imageContainer.m_depth;
  1378. uint32_t mipWidth = imageContainer.m_width;
  1379. uint32_t mipHeight = imageContainer.m_height;
  1380. for (uint32_t lod = 0, num = imageContainer.m_numMips; lod < num; ++lod)
  1381. {
  1382. width = bx::uint32_max(1, width);
  1383. height = bx::uint32_max(1, height);
  1384. depth = bx::uint32_max(1, depth);
  1385. mipWidth = bx::uint32_max(min, mipWidth);
  1386. mipHeight = bx::uint32_max(min, mipHeight);
  1387. uint32_t mipSize = width*height*depth*bpp/8;
  1388. ImageMip mip;
  1389. if (imageGetRawData(imageContainer, side, lod, _mem->data, _mem->size, mip) )
  1390. {
  1391. uint32_t pitch;
  1392. uint32_t slicePitch;
  1393. uint8_t* bits = lock(side, lod, pitch, slicePitch);
  1394. if (convert)
  1395. {
  1396. if (width != mipWidth
  1397. || height != mipHeight)
  1398. {
  1399. uint32_t srcpitch = mipWidth*bpp/8;
  1400. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, srcpitch*mipHeight);
  1401. imageDecodeToBgra8(temp, mip.m_data, mip.m_width, mip.m_height, srcpitch, mip.m_format);
  1402. uint32_t dstpitch = pitch;
  1403. for (uint32_t yy = 0; yy < height; ++yy)
  1404. {
  1405. uint8_t* src = &temp[yy*srcpitch];
  1406. uint8_t* dst = &bits[yy*dstpitch];
  1407. memcpy(dst, src, dstpitch);
  1408. }
  1409. BX_FREE(g_allocator, temp);
  1410. }
  1411. else
  1412. {
  1413. imageDecodeToBgra8(bits, mip.m_data, mip.m_width, mip.m_height, pitch, mip.m_format);
  1414. }
  1415. }
  1416. else
  1417. {
  1418. uint32_t size = useMipSize ? mip.m_size : mipSize;
  1419. memcpy(bits, mip.m_data, size);
  1420. }
  1421. unlock(side, lod);
  1422. }
  1423. width >>= 1;
  1424. height >>= 1;
  1425. depth >>= 1;
  1426. mipWidth >>= 1;
  1427. mipHeight >>= 1;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. void Texture::updateBegin(uint8_t _side, uint8_t _mip)
  1433. {
  1434. uint32_t slicePitch;
  1435. s_renderCtx->m_updateTextureSide = _side;
  1436. s_renderCtx->m_updateTextureMip = _mip;
  1437. s_renderCtx->m_updateTextureBits = lock(_side, _mip, s_renderCtx->m_updateTexturePitch, slicePitch);
  1438. }
  1439. void Texture::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  1440. {
  1441. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  1442. const uint32_t rectpitch = _rect.m_width*bpp/8;
  1443. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  1444. const uint32_t dstpitch = s_renderCtx->m_updateTexturePitch;
  1445. uint8_t* bits = s_renderCtx->m_updateTextureBits + _rect.m_y*dstpitch + _rect.m_x*bpp/8;
  1446. const bool convert = m_textureFormat != m_requestedFormat;
  1447. uint8_t* data = _mem->data;
  1448. uint8_t* temp = NULL;
  1449. if (convert)
  1450. {
  1451. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  1452. imageDecodeToBgra8(temp, data, _rect.m_width, _rect.m_height, srcpitch, m_requestedFormat);
  1453. data = temp;
  1454. }
  1455. {
  1456. uint8_t* src = data;
  1457. uint8_t* dst = bits;
  1458. for (uint32_t yy = 0, height = _rect.m_height; yy < height; ++yy)
  1459. {
  1460. memcpy(dst, src, rectpitch);
  1461. src += srcpitch;
  1462. dst += dstpitch;
  1463. }
  1464. }
  1465. if (NULL != temp)
  1466. {
  1467. BX_FREE(g_allocator, temp);
  1468. }
  1469. if (0 == _mip)
  1470. {
  1471. dirty(_side, _rect, _z, _depth);
  1472. }
  1473. }
  1474. void Texture::updateEnd()
  1475. {
  1476. unlock(s_renderCtx->m_updateTextureSide, s_renderCtx->m_updateTextureMip);
  1477. }
  1478. void Texture::commit(uint8_t _stage, uint32_t _flags)
  1479. {
  1480. s_renderCtx->setSamplerState(_stage, 0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) ? _flags : m_flags);
  1481. DX_CHECK(s_renderCtx->m_device->SetTexture(_stage, m_ptr) );
  1482. }
  1483. void RenderTarget::create(uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1484. {
  1485. m_width = _width;
  1486. m_height = _height;
  1487. m_flags = _flags;
  1488. m_textureFlags = (_textureFlags&(BGFX_TEXTURE_MIN_MASK|BGFX_TEXTURE_MAG_MASK) )
  1489. | BGFX_TEXTURE_U_CLAMP
  1490. | BGFX_TEXTURE_V_CLAMP
  1491. ;
  1492. createTextures();
  1493. }
  1494. void RenderTarget::createTextures()
  1495. {
  1496. if (0 != m_flags)
  1497. {
  1498. m_msaa = s_msaa[(m_flags&BGFX_RENDER_TARGET_MSAA_MASK)>>BGFX_RENDER_TARGET_MSAA_SHIFT];
  1499. const uint32_t colorFormat = (m_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1500. const uint32_t depthFormat = (m_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1501. m_depthOnly = (0 == colorFormat && 0 < depthFormat);
  1502. // CheckDeviceFormat D3DUSAGE_SRGBWRITE
  1503. if (m_depthOnly)
  1504. {
  1505. DX_CHECK(s_renderCtx->m_device->CreateRenderTarget(1
  1506. , 1
  1507. , D3DFMT_R5G6B5
  1508. , D3DMULTISAMPLE_NONE
  1509. , 0
  1510. , false
  1511. , &m_rt
  1512. , NULL
  1513. ) );
  1514. BGFX_FATAL(m_rt, Fatal::UnableToCreateRenderTarget, "Unable to create 1x1 render target.");
  1515. DX_CHECK(s_renderCtx->m_device->CreateTexture(m_width
  1516. , m_height
  1517. , 1
  1518. , D3DUSAGE_DEPTHSTENCIL
  1519. , s_depthFormat[depthFormat]
  1520. , D3DPOOL_DEFAULT
  1521. , &m_depthTexture
  1522. , NULL
  1523. ) );
  1524. BGFX_FATAL(m_depthTexture, Fatal::UnableToCreateRenderTarget, "Unable to create depth texture.");
  1525. DX_CHECK(m_depthTexture->GetSurfaceLevel(0, &m_depth) );
  1526. }
  1527. else
  1528. {
  1529. if (D3DMULTISAMPLE_NONE != m_msaa.m_type)
  1530. {
  1531. DX_CHECK(s_renderCtx->m_device->CreateRenderTarget(m_width
  1532. , m_height
  1533. , s_colorFormat[colorFormat]
  1534. , m_msaa.m_type
  1535. , m_msaa.m_quality
  1536. , false
  1537. , &m_rt
  1538. , NULL
  1539. ) );
  1540. BGFX_FATAL(m_rt, Fatal::UnableToCreateRenderTarget, "Unable to create MSAA render target.");
  1541. }
  1542. if (0 < colorFormat)
  1543. {
  1544. DX_CHECK(s_renderCtx->m_device->CreateTexture(m_width
  1545. , m_height
  1546. , 1
  1547. , D3DUSAGE_RENDERTARGET
  1548. , s_colorFormat[colorFormat]
  1549. , D3DPOOL_DEFAULT
  1550. , &m_colorTexture
  1551. , NULL
  1552. ) );
  1553. BGFX_FATAL(m_colorTexture, Fatal::UnableToCreateRenderTarget, "Unable to create color render target.");
  1554. DX_CHECK(m_colorTexture->GetSurfaceLevel(0, &m_color) );
  1555. }
  1556. if (0 < depthFormat)
  1557. {
  1558. DX_CHECK(s_renderCtx->m_device->CreateDepthStencilSurface(m_width
  1559. , m_height
  1560. , s_depthFormat[depthFormat]
  1561. , m_msaa.m_type
  1562. , m_msaa.m_quality
  1563. , FALSE
  1564. , &m_depth
  1565. , NULL
  1566. ) );
  1567. BGFX_FATAL(m_depth, Fatal::UnableToCreateRenderTarget, "Unable to create depth stencil surface.");
  1568. }
  1569. }
  1570. }
  1571. }
  1572. void RenderTarget::destroyTextures()
  1573. {
  1574. if (0 != m_flags)
  1575. {
  1576. if (m_depthOnly)
  1577. {
  1578. DX_RELEASE(m_rt, 0);
  1579. DX_RELEASE(m_depth, 1);
  1580. DX_RELEASE(m_depthTexture, 0);
  1581. }
  1582. else
  1583. {
  1584. uint32_t colorFormat = (m_flags&BGFX_RENDER_TARGET_COLOR_MASK)>>BGFX_RENDER_TARGET_COLOR_SHIFT;
  1585. uint32_t depthFormat = (m_flags&BGFX_RENDER_TARGET_DEPTH_MASK)>>BGFX_RENDER_TARGET_DEPTH_SHIFT;
  1586. if (D3DMULTISAMPLE_NONE != m_msaa.m_type)
  1587. {
  1588. DX_RELEASE(m_rt, 0);
  1589. }
  1590. if (0 < colorFormat)
  1591. {
  1592. DX_RELEASE(m_color, 1);
  1593. DX_RELEASE(m_colorTexture, 0);
  1594. }
  1595. if (0 < depthFormat)
  1596. {
  1597. DX_RELEASE(m_depth, 0);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. void RenderTarget::commit(uint8_t _stage, uint32_t _textureFlags)
  1603. {
  1604. s_renderCtx->setSamplerState(_stage, 0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _textureFlags) ? _textureFlags : m_textureFlags);
  1605. DX_CHECK(s_renderCtx->m_device->SetTexture(_stage, m_depthOnly ? m_depthTexture : m_colorTexture) );
  1606. }
  1607. void RenderTarget::resolve()
  1608. {
  1609. #if BX_PLATFORM_WINDOWS
  1610. DX_CHECK(s_renderCtx->m_device->StretchRect(m_rt
  1611. , NULL
  1612. , m_color
  1613. , NULL
  1614. , D3DTEXF_NONE
  1615. ) );
  1616. #endif // BX_PLATFORM_WINDOWS
  1617. }
  1618. void ConstantBuffer::commit()
  1619. {
  1620. reset();
  1621. do
  1622. {
  1623. uint32_t opcode = read();
  1624. if (UniformType::End == opcode)
  1625. {
  1626. break;
  1627. }
  1628. UniformType::Enum type;
  1629. uint16_t loc;
  1630. uint16_t num;
  1631. uint16_t copy;
  1632. decodeOpcode(opcode, type, loc, num, copy);
  1633. const char* data;
  1634. if (copy)
  1635. {
  1636. data = read(g_uniformTypeSize[type]*num);
  1637. }
  1638. else
  1639. {
  1640. memcpy(&data, read(sizeof(void*) ), sizeof(void*) );
  1641. }
  1642. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  1643. case UniformType::_uniform: \
  1644. { \
  1645. _type* value = (_type*)data; \
  1646. s_renderCtx->m_device->SetVertexShaderConstant##_dxsuffix(loc, value, num); \
  1647. } \
  1648. break; \
  1649. \
  1650. case UniformType::_uniform|BGFX_UNIFORM_FRAGMENTBIT: \
  1651. { \
  1652. _type* value = (_type*)data; \
  1653. s_renderCtx->m_device->SetPixelShaderConstant##_dxsuffix(loc, value, num); \
  1654. } \
  1655. break
  1656. switch ((int32_t)type)
  1657. {
  1658. CASE_IMPLEMENT_UNIFORM(Uniform1i, 1iv, I, int);
  1659. CASE_IMPLEMENT_UNIFORM(Uniform1f, 1fv, F, float);
  1660. CASE_IMPLEMENT_UNIFORM(Uniform1iv, 1iv, I, int);
  1661. CASE_IMPLEMENT_UNIFORM(Uniform1fv, 1fv, F, float);
  1662. CASE_IMPLEMENT_UNIFORM(Uniform2fv, 2fv, F, float);
  1663. CASE_IMPLEMENT_UNIFORM(Uniform3fv, 3fv, F, float);
  1664. CASE_IMPLEMENT_UNIFORM(Uniform4fv, 4fv, F, float);
  1665. CASE_IMPLEMENT_UNIFORM(Uniform3x3fv, Matrix3fv, F, float);
  1666. CASE_IMPLEMENT_UNIFORM(Uniform4x4fv, Matrix4fv, F, float);
  1667. case UniformType::End:
  1668. break;
  1669. default:
  1670. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", m_pos, opcode, type, loc, num, copy);
  1671. break;
  1672. }
  1673. #undef CASE_IMPLEMENT_UNIFORM
  1674. } while (true);
  1675. }
  1676. void TextVideoMemBlitter::setup()
  1677. {
  1678. uint32_t width = s_renderCtx->m_params.BackBufferWidth;
  1679. uint32_t height = s_renderCtx->m_params.BackBufferHeight;
  1680. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  1681. s_renderCtx->setRenderTarget(rt, false);
  1682. D3DVIEWPORT9 vp;
  1683. vp.X = 0;
  1684. vp.Y = 0;
  1685. vp.Width = width;
  1686. vp.Height = height;
  1687. vp.MinZ = 0.0f;
  1688. vp.MaxZ = 1.0f;
  1689. IDirect3DDevice9* device = s_renderCtx->m_device;
  1690. DX_CHECK(device->SetViewport(&vp) );
  1691. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  1692. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, FALSE) );
  1693. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS) );
  1694. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  1695. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  1696. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  1697. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE) );
  1698. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID) );
  1699. Program& program = s_renderCtx->m_program[m_program.idx];
  1700. device->SetVertexShader( (IDirect3DVertexShader9*)program.m_vsh->m_ptr);
  1701. device->SetPixelShader( (IDirect3DPixelShader9*)program.m_fsh->m_ptr);
  1702. VertexBuffer& vb = s_renderCtx->m_vertexBuffers[m_vb->handle.idx];
  1703. VertexDeclaration& vertexDecl = s_renderCtx->m_vertexDecls[m_vb->decl.idx];
  1704. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  1705. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  1706. IndexBuffer& ib = s_renderCtx->m_indexBuffers[m_ib->handle.idx];
  1707. DX_CHECK(device->SetIndices(ib.m_ptr) );
  1708. float proj[16];
  1709. mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1710. PredefinedUniform& predefined = program.m_predefined[0];
  1711. uint8_t flags = predefined.m_type;
  1712. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, proj, 4);
  1713. s_renderCtx->m_textures[m_texture.idx].commit(0);
  1714. }
  1715. void TextVideoMemBlitter::render(uint32_t _numIndices)
  1716. {
  1717. uint32_t numVertices = _numIndices*4/6;
  1718. s_renderCtx->m_indexBuffers[m_ib->handle.idx].update(0, _numIndices*2, m_ib->data, true);
  1719. s_renderCtx->m_vertexBuffers[m_vb->handle.idx].update(0, numVertices*m_decl.m_stride, m_vb->data, true);
  1720. DX_CHECK(s_renderCtx->m_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST
  1721. , 0
  1722. , 0
  1723. , numVertices
  1724. , 0
  1725. , _numIndices/3
  1726. ) );
  1727. }
  1728. void Context::rendererFlip()
  1729. {
  1730. if (NULL != s_renderCtx)
  1731. {
  1732. s_renderCtx->flip();
  1733. }
  1734. }
  1735. void Context::rendererInit()
  1736. {
  1737. s_renderCtx = BX_NEW(g_allocator, RendererContext);
  1738. s_renderCtx->init();
  1739. }
  1740. void Context::rendererShutdown()
  1741. {
  1742. s_renderCtx->shutdown();
  1743. BX_DELETE(g_allocator, s_renderCtx);
  1744. }
  1745. void Context::rendererCreateIndexBuffer(IndexBufferHandle _handle, Memory* _mem)
  1746. {
  1747. s_renderCtx->m_indexBuffers[_handle.idx].create(_mem->size, _mem->data);
  1748. }
  1749. void Context::rendererDestroyIndexBuffer(IndexBufferHandle _handle)
  1750. {
  1751. s_renderCtx->m_indexBuffers[_handle.idx].destroy();
  1752. }
  1753. void Context::rendererCreateVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl)
  1754. {
  1755. s_renderCtx->m_vertexDecls[_handle.idx].create(_decl);
  1756. }
  1757. void Context::rendererDestroyVertexDecl(VertexDeclHandle _handle)
  1758. {
  1759. s_renderCtx->m_vertexDecls[_handle.idx].destroy();
  1760. }
  1761. void Context::rendererCreateVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle)
  1762. {
  1763. s_renderCtx->m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle);
  1764. }
  1765. void Context::rendererDestroyVertexBuffer(VertexBufferHandle _handle)
  1766. {
  1767. s_renderCtx->m_vertexBuffers[_handle.idx].destroy();
  1768. }
  1769. void Context::rendererCreateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size)
  1770. {
  1771. s_renderCtx->m_indexBuffers[_handle.idx].create(_size, NULL);
  1772. }
  1773. void Context::rendererUpdateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  1774. {
  1775. s_renderCtx->m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1776. }
  1777. void Context::rendererDestroyDynamicIndexBuffer(IndexBufferHandle _handle)
  1778. {
  1779. s_renderCtx->m_indexBuffers[_handle.idx].destroy();
  1780. }
  1781. void Context::rendererCreateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size)
  1782. {
  1783. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1784. s_renderCtx->m_vertexBuffers[_handle.idx].create(_size, NULL, decl);
  1785. }
  1786. void Context::rendererUpdateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem)
  1787. {
  1788. s_renderCtx->m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1789. }
  1790. void Context::rendererDestroyDynamicVertexBuffer(VertexBufferHandle _handle)
  1791. {
  1792. s_renderCtx->m_vertexBuffers[_handle.idx].destroy();
  1793. }
  1794. void Context::rendererCreateVertexShader(VertexShaderHandle _handle, Memory* _mem)
  1795. {
  1796. s_renderCtx->m_vertexShaders[_handle.idx].create(false, _mem);
  1797. }
  1798. void Context::rendererDestroyVertexShader(VertexShaderHandle _handle)
  1799. {
  1800. s_renderCtx->m_vertexShaders[_handle.idx].destroy();
  1801. }
  1802. void Context::rendererCreateFragmentShader(FragmentShaderHandle _handle, Memory* _mem)
  1803. {
  1804. s_renderCtx->m_fragmentShaders[_handle.idx].create(true, _mem);
  1805. }
  1806. void Context::rendererDestroyFragmentShader(FragmentShaderHandle _handle)
  1807. {
  1808. s_renderCtx->m_fragmentShaders[_handle.idx].destroy();
  1809. }
  1810. void Context::rendererCreateProgram(ProgramHandle _handle, VertexShaderHandle _vsh, FragmentShaderHandle _fsh)
  1811. {
  1812. s_renderCtx->m_program[_handle.idx].create(s_renderCtx->m_vertexShaders[_vsh.idx], s_renderCtx->m_fragmentShaders[_fsh.idx]);
  1813. }
  1814. void Context::rendererDestroyProgram(FragmentShaderHandle _handle)
  1815. {
  1816. s_renderCtx->m_program[_handle.idx].destroy();
  1817. }
  1818. void Context::rendererCreateTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags)
  1819. {
  1820. s_renderCtx->m_textures[_handle.idx].create(_mem, _flags);
  1821. }
  1822. void Context::rendererUpdateTextureBegin(TextureHandle _handle, uint8_t _side, uint8_t _mip)
  1823. {
  1824. s_renderCtx->m_updateTexture = &s_renderCtx->m_textures[_handle.idx];
  1825. s_renderCtx->m_updateTexture->updateBegin(_side, _mip);
  1826. }
  1827. void Context::rendererUpdateTexture(TextureHandle /*_handle*/, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  1828. {
  1829. s_renderCtx->m_updateTexture->update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  1830. }
  1831. void Context::rendererUpdateTextureEnd()
  1832. {
  1833. s_renderCtx->m_updateTexture->updateEnd();
  1834. s_renderCtx->m_updateTexture = NULL;
  1835. }
  1836. void Context::rendererDestroyTexture(TextureHandle _handle)
  1837. {
  1838. s_renderCtx->m_textures[_handle.idx].destroy();
  1839. }
  1840. void Context::rendererCreateRenderTarget(RenderTargetHandle _handle, uint16_t _width, uint16_t _height, uint32_t _flags, uint32_t _textureFlags)
  1841. {
  1842. s_renderCtx->m_renderTargets[_handle.idx].create(_width, _height, _flags, _textureFlags);
  1843. }
  1844. void Context::rendererDestroyRenderTarget(RenderTargetHandle _handle)
  1845. {
  1846. s_renderCtx->m_renderTargets[_handle.idx].destroy();
  1847. }
  1848. void Context::rendererCreateUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name)
  1849. {
  1850. uint32_t size = BX_ALIGN_16(g_uniformTypeSize[_type]*_num);
  1851. void* data = BX_ALLOC(g_allocator, size);
  1852. memset(data, 0, size);
  1853. s_renderCtx->m_uniforms[_handle.idx] = data;
  1854. s_renderCtx->m_uniformReg.add(_name, s_renderCtx->m_uniforms[_handle.idx]);
  1855. }
  1856. void Context::rendererDestroyUniform(UniformHandle _handle)
  1857. {
  1858. BX_FREE(g_allocator, s_renderCtx->m_uniforms[_handle.idx]);
  1859. }
  1860. void Context::rendererSaveScreenShot(const char* _filePath)
  1861. {
  1862. s_renderCtx->saveScreenShot(_filePath);
  1863. }
  1864. void Context::rendererUpdateViewName(uint8_t _id, const char* _name)
  1865. {
  1866. mbstowcs(&s_viewNameW[_id][0], _name, BX_COUNTOF(s_viewNameW[0]) );
  1867. }
  1868. void Context::rendererUpdateUniform(uint16_t _loc, const void* _data, uint32_t _size)
  1869. {
  1870. memcpy(s_renderCtx->m_uniforms[_loc], _data, _size);
  1871. }
  1872. void Context::rendererSetMarker(const char* _marker, uint32_t _size)
  1873. {
  1874. #if BGFX_CONFIG_DEBUG_PIX
  1875. uint32_t size = _size*sizeof(wchar_t);
  1876. wchar_t* name = (wchar_t*)alloca(size);
  1877. mbstowcs(name, _marker, size-2);
  1878. PIX_SETMARKER(D3DCOLOR_RGBA(0xff, 0xff, 0xff, 0xff), name);
  1879. #endif // BGFX_CONFIG_DEBUG_PIX
  1880. BX_UNUSED(_marker, _size);
  1881. }
  1882. void Context::rendererSubmit()
  1883. {
  1884. IDirect3DDevice9* device = s_renderCtx->m_device;
  1885. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), L"rendererSubmit");
  1886. s_renderCtx->updateResolution(m_render->m_resolution);
  1887. int64_t elapsed = -bx::getHPCounter();
  1888. int64_t captureElapsed = 0;
  1889. device->BeginScene();
  1890. if (0 < m_render->m_iboffset)
  1891. {
  1892. TransientIndexBuffer* ib = m_render->m_transientIb;
  1893. s_renderCtx->m_indexBuffers[ib->handle.idx].update(0, m_render->m_iboffset, ib->data, true);
  1894. }
  1895. if (0 < m_render->m_vboffset)
  1896. {
  1897. TransientVertexBuffer* vb = m_render->m_transientVb;
  1898. s_renderCtx->m_vertexBuffers[vb->handle.idx].update(0, m_render->m_vboffset, vb->data, true);
  1899. }
  1900. m_render->sort();
  1901. RenderState currentState;
  1902. currentState.reset();
  1903. currentState.m_flags = BGFX_STATE_NONE;
  1904. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  1905. Matrix4 viewProj[BGFX_CONFIG_MAX_VIEWS];
  1906. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1907. {
  1908. mtxMul(viewProj[ii].val, m_render->m_view[ii].val, m_render->m_proj[ii].val);
  1909. }
  1910. DX_CHECK(device->SetRenderState(D3DRS_FILLMODE, m_render->m_debug&BGFX_DEBUG_WIREFRAME ? D3DFILL_WIREFRAME : D3DFILL_SOLID) );
  1911. uint16_t programIdx = invalidHandle;
  1912. SortKey key;
  1913. uint8_t view = 0xff;
  1914. RenderTargetHandle rt = BGFX_INVALID_HANDLE;
  1915. float alphaRef = 0.0f;
  1916. uint32_t blendFactor = 0;
  1917. D3DPRIMITIVETYPE primType = D3DPT_TRIANGLELIST;
  1918. uint32_t primNumVerts = 3;
  1919. bool viewHasScissor = false;
  1920. Rect viewScissorRect;
  1921. viewScissorRect.clear();
  1922. uint32_t statsNumPrimsSubmitted = 0;
  1923. uint32_t statsNumIndices = 0;
  1924. uint32_t statsNumInstances = 0;
  1925. uint32_t statsNumPrimsRendered = 0;
  1926. s_renderCtx->invalidateSamplerState();
  1927. if (0 == (m_render->m_debug&BGFX_DEBUG_IFH) )
  1928. {
  1929. for (uint32_t item = 0, numItems = m_render->m_num; item < numItems; ++item)
  1930. {
  1931. key.decode(m_render->m_sortKeys[item]);
  1932. const RenderState& state = m_render->m_renderState[m_render->m_sortValues[item] ];
  1933. const uint64_t newFlags = state.m_flags;
  1934. uint64_t changedFlags = currentState.m_flags ^ state.m_flags;
  1935. currentState.m_flags = newFlags;
  1936. const uint64_t newStencil = state.m_stencil;
  1937. uint64_t changedStencil = currentState.m_stencil ^ state.m_stencil;
  1938. currentState.m_stencil = newStencil;
  1939. if (key.m_view != view)
  1940. {
  1941. currentState.clear();
  1942. currentState.m_scissor = !state.m_scissor;
  1943. changedFlags = BGFX_STATE_MASK;
  1944. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  1945. currentState.m_flags = newFlags;
  1946. currentState.m_stencil = newStencil;
  1947. PIX_ENDEVENT();
  1948. PIX_BEGINEVENT(D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), s_viewNameW[key.m_view]);
  1949. view = key.m_view;
  1950. programIdx = invalidHandle;
  1951. if (m_render->m_rt[view].idx != rt.idx)
  1952. {
  1953. rt = m_render->m_rt[view];
  1954. s_renderCtx->setRenderTarget(rt);
  1955. }
  1956. const Rect& rect = m_render->m_rect[view];
  1957. const Rect& scissorRect = m_render->m_scissor[view];
  1958. viewHasScissor = !scissorRect.isZero();
  1959. viewScissorRect = viewHasScissor ? scissorRect : rect;
  1960. D3DVIEWPORT9 vp;
  1961. vp.X = rect.m_x;
  1962. vp.Y = rect.m_y;
  1963. vp.Width = rect.m_width;
  1964. vp.Height = rect.m_height;
  1965. vp.MinZ = 0.0f;
  1966. vp.MaxZ = 1.0f;
  1967. DX_CHECK(device->SetViewport(&vp) );
  1968. Clear& clear = m_render->m_clear[view];
  1969. if (BGFX_CLEAR_NONE != clear.m_flags)
  1970. {
  1971. D3DCOLOR color = 0;
  1972. DWORD flags = 0;
  1973. if (BGFX_CLEAR_COLOR_BIT & clear.m_flags)
  1974. {
  1975. flags |= D3DCLEAR_TARGET;
  1976. uint32_t rgba = clear.m_rgba;
  1977. color = D3DCOLOR_RGBA(rgba>>24, (rgba>>16)&0xff, (rgba>>8)&0xff, rgba&0xff);
  1978. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA) );
  1979. }
  1980. if (BGFX_CLEAR_DEPTH_BIT & clear.m_flags)
  1981. {
  1982. flags |= D3DCLEAR_ZBUFFER;
  1983. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE) );
  1984. }
  1985. if (BGFX_CLEAR_STENCIL_BIT & clear.m_flags)
  1986. {
  1987. flags |= D3DCLEAR_STENCIL;
  1988. }
  1989. if (0 != flags)
  1990. {
  1991. RECT rc;
  1992. rc.left = rect.m_x;
  1993. rc.top = rect.m_y;
  1994. rc.right = rect.m_x + rect.m_width;
  1995. rc.bottom = rect.m_y + rect.m_height;
  1996. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE) );
  1997. DX_CHECK(device->SetScissorRect(&rc) );
  1998. DX_CHECK(device->Clear(0, NULL, flags, color, clear.m_depth, clear.m_stencil) );
  1999. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE) );
  2000. }
  2001. }
  2002. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, FALSE) );
  2003. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, TRUE) );
  2004. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS) );
  2005. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) );
  2006. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE) );
  2007. DX_CHECK(device->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER) );
  2008. }
  2009. uint16_t scissor = state.m_scissor;
  2010. if (currentState.m_scissor != scissor)
  2011. {
  2012. currentState.m_scissor = scissor;
  2013. if (UINT16_MAX == scissor)
  2014. {
  2015. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, viewHasScissor) );
  2016. if (viewHasScissor)
  2017. {
  2018. RECT rc;
  2019. rc.left = viewScissorRect.m_x;
  2020. rc.top = viewScissorRect.m_y;
  2021. rc.right = viewScissorRect.m_x + viewScissorRect.m_width;
  2022. rc.bottom = viewScissorRect.m_y + viewScissorRect.m_height;
  2023. DX_CHECK(device->SetScissorRect(&rc) );
  2024. }
  2025. }
  2026. else
  2027. {
  2028. Rect scissorRect;
  2029. scissorRect.intersect(viewScissorRect, m_render->m_rectCache.m_cache[scissor]);
  2030. DX_CHECK(device->SetRenderState(D3DRS_SCISSORTESTENABLE, true) );
  2031. RECT rc;
  2032. rc.left = scissorRect.m_x;
  2033. rc.top = scissorRect.m_y;
  2034. rc.right = scissorRect.m_x + scissorRect.m_width;
  2035. rc.bottom = scissorRect.m_y + scissorRect.m_height;
  2036. DX_CHECK(device->SetScissorRect(&rc) );
  2037. }
  2038. }
  2039. if (0 != changedStencil)
  2040. {
  2041. bool enable = 0 != newStencil;
  2042. DX_CHECK(device->SetRenderState(D3DRS_STENCILENABLE, enable) );
  2043. if (0 != newStencil)
  2044. {
  2045. uint32_t fstencil = unpackStencil(0, newStencil);
  2046. uint32_t bstencil = unpackStencil(1, newStencil);
  2047. uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  2048. DX_CHECK(device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, 0 != frontAndBack) );
  2049. uint32_t fchanged = unpackStencil(0, changedStencil);
  2050. if ( (BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & fchanged)
  2051. {
  2052. uint32_t ref = (fstencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  2053. DX_CHECK(device->SetRenderState(D3DRS_STENCILREF, ref) );
  2054. uint32_t rmask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2055. DX_CHECK(device->SetRenderState(D3DRS_STENCILMASK, rmask) );
  2056. }
  2057. // uint32_t bchanged = unpackStencil(1, changedStencil);
  2058. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  2059. // {
  2060. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  2061. // DX_CHECK(device->SetRenderState(D3DRS_STENCILWRITEMASK, wmask) );
  2062. // }
  2063. for (uint32_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  2064. {
  2065. uint32_t stencil = unpackStencil(ii, newStencil);
  2066. uint32_t changed = unpackStencil(ii, changedStencil);
  2067. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  2068. {
  2069. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  2070. DX_CHECK(device->SetRenderState(s_stencilFuncRs[ii], s_stencilFunc[func]) );
  2071. }
  2072. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  2073. {
  2074. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  2075. DX_CHECK(device->SetRenderState(s_stencilFailRs[ii], s_stencilOp[sfail]) );
  2076. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  2077. DX_CHECK(device->SetRenderState(s_stencilZFailRs[ii], s_stencilOp[zfail]) );
  2078. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  2079. DX_CHECK(device->SetRenderState(s_stencilZPassRs[ii], s_stencilOp[zpass]) );
  2080. }
  2081. }
  2082. }
  2083. }
  2084. if ( (0
  2085. | BGFX_STATE_CULL_MASK
  2086. | BGFX_STATE_DEPTH_WRITE
  2087. | BGFX_STATE_DEPTH_TEST_MASK
  2088. | BGFX_STATE_ALPHA_MASK
  2089. | BGFX_STATE_RGB_WRITE
  2090. | BGFX_STATE_BLEND_MASK
  2091. | BGFX_STATE_BLEND_EQUATION_MASK
  2092. | BGFX_STATE_ALPHA_REF_MASK
  2093. | BGFX_STATE_PT_MASK
  2094. | BGFX_STATE_POINT_SIZE_MASK
  2095. | BGFX_STATE_MSAA
  2096. ) & changedFlags)
  2097. {
  2098. if (BGFX_STATE_CULL_MASK & changedFlags)
  2099. {
  2100. uint32_t cull = (newFlags&BGFX_STATE_CULL_MASK)>>BGFX_STATE_CULL_SHIFT;
  2101. DX_CHECK(device->SetRenderState(D3DRS_CULLMODE, s_cullMode[cull]) );
  2102. }
  2103. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  2104. {
  2105. DX_CHECK(device->SetRenderState(D3DRS_ZWRITEENABLE, !!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  2106. }
  2107. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  2108. {
  2109. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  2110. DX_CHECK(device->SetRenderState(D3DRS_ZENABLE, 0 != func) );
  2111. if (0 != func)
  2112. {
  2113. DX_CHECK(device->SetRenderState(D3DRS_ZFUNC, s_depthFunc[func]) );
  2114. }
  2115. }
  2116. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  2117. {
  2118. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  2119. alphaRef = ref/255.0f;
  2120. }
  2121. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  2122. {
  2123. DX_CHECK(device->SetRenderState(D3DRS_POINTSIZE, castfu( (float)( (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) ) ) );
  2124. }
  2125. if (BGFX_STATE_MSAA & changedFlags)
  2126. {
  2127. DX_CHECK(device->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, (newFlags&BGFX_STATE_MSAA) == BGFX_STATE_MSAA) );
  2128. }
  2129. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  2130. {
  2131. uint32_t writeEnable = (newFlags&BGFX_STATE_ALPHA_WRITE) ? D3DCOLORWRITEENABLE_ALPHA : 0;
  2132. writeEnable |= (newFlags&BGFX_STATE_RGB_WRITE) ? D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE : 0;
  2133. DX_CHECK(device->SetRenderState(D3DRS_COLORWRITEENABLE, writeEnable) );
  2134. }
  2135. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK) & changedFlags)
  2136. {
  2137. bool alphaBlendEnabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  2138. DX_CHECK(device->SetRenderState(D3DRS_ALPHABLENDENABLE, alphaBlendEnabled) );
  2139. // DX_CHECK(device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, alphaBlendEnabled) );
  2140. if (alphaBlendEnabled)
  2141. {
  2142. uint32_t blend = (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT;
  2143. uint32_t equation = (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT;
  2144. uint32_t src = blend&0xf;
  2145. uint32_t dst = (blend>>4)&0xf;
  2146. DX_CHECK(device->SetRenderState(D3DRS_SRCBLEND, s_blendFactor[src].m_src) );
  2147. DX_CHECK(device->SetRenderState(D3DRS_DESTBLEND, s_blendFactor[dst].m_dst) );
  2148. DX_CHECK(device->SetRenderState(D3DRS_BLENDOP, s_blendEquation[equation]) );
  2149. // DX_CHECK(device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_SRCALPHA) );
  2150. // DX_CHECK(device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA) );
  2151. if ( (s_blendFactor[src].m_factor || s_blendFactor[dst].m_factor)
  2152. && blendFactor != state.m_rgba)
  2153. {
  2154. blendFactor = state.m_rgba;
  2155. D3DCOLOR color = D3DCOLOR_RGBA(blendFactor>>24, (blendFactor>>16)&0xff, (blendFactor>>8)&0xff, blendFactor&0xff);
  2156. DX_CHECK(device->SetRenderState(D3DRS_BLENDFACTOR, color) );
  2157. }
  2158. }
  2159. }
  2160. uint8_t primIndex = uint8_t( (newFlags&BGFX_STATE_PT_MASK)>>BGFX_STATE_PT_SHIFT);
  2161. primType = s_primType[primIndex];
  2162. primNumVerts = 3-primIndex;
  2163. }
  2164. bool programChanged = false;
  2165. bool constantsChanged = state.m_constBegin < state.m_constEnd;
  2166. rendererUpdateUniforms(m_render->m_constantBuffer, state.m_constBegin, state.m_constEnd);
  2167. if (key.m_program != programIdx)
  2168. {
  2169. programIdx = key.m_program;
  2170. if (invalidHandle == programIdx)
  2171. {
  2172. device->SetVertexShader(NULL);
  2173. device->SetPixelShader(NULL);
  2174. }
  2175. else
  2176. {
  2177. Program& program = s_renderCtx->m_program[programIdx];
  2178. device->SetVertexShader( (IDirect3DVertexShader9*)program.m_vsh->m_ptr);
  2179. device->SetPixelShader( (IDirect3DPixelShader9*)program.m_fsh->m_ptr);
  2180. }
  2181. programChanged =
  2182. constantsChanged = true;
  2183. }
  2184. if (invalidHandle != programIdx)
  2185. {
  2186. Program& program = s_renderCtx->m_program[programIdx];
  2187. if (constantsChanged)
  2188. {
  2189. program.commit();
  2190. }
  2191. for (uint32_t ii = 0, num = program.m_numPredefined; ii < num; ++ii)
  2192. {
  2193. PredefinedUniform& predefined = program.m_predefined[ii];
  2194. uint8_t flags = predefined.m_type&BGFX_UNIFORM_FRAGMENTBIT;
  2195. switch (predefined.m_type&(~BGFX_UNIFORM_FRAGMENTBIT) )
  2196. {
  2197. case PredefinedUniform::ViewRect:
  2198. {
  2199. float rect[4];
  2200. rect[0] = m_render->m_rect[view].m_x;
  2201. rect[1] = m_render->m_rect[view].m_y;
  2202. rect[2] = m_render->m_rect[view].m_width;
  2203. rect[3] = m_render->m_rect[view].m_height;
  2204. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, &rect[0], 1);
  2205. }
  2206. break;
  2207. case PredefinedUniform::ViewTexel:
  2208. {
  2209. float rect[4];
  2210. rect[0] = 1.0f/float(m_render->m_rect[view].m_width);
  2211. rect[1] = 1.0f/float(m_render->m_rect[view].m_height);
  2212. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, &rect[0], 1);
  2213. }
  2214. break;
  2215. case PredefinedUniform::View:
  2216. {
  2217. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, m_render->m_view[view].val, bx::uint32_min(4, predefined.m_count) );
  2218. }
  2219. break;
  2220. case PredefinedUniform::ViewProj:
  2221. {
  2222. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, viewProj[view].val, bx::uint32_min(4, predefined.m_count) );
  2223. }
  2224. break;
  2225. case PredefinedUniform::Model:
  2226. {
  2227. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2228. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, model.val, bx::uint32_min(state.m_num*4, predefined.m_count) );
  2229. }
  2230. break;
  2231. case PredefinedUniform::ModelView:
  2232. {
  2233. Matrix4 modelView;
  2234. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2235. mtxMul(modelView.val, model.val, m_render->m_view[view].val);
  2236. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, modelView.val, bx::uint32_min(4, predefined.m_count) );
  2237. }
  2238. break;
  2239. case PredefinedUniform::ModelViewProj:
  2240. {
  2241. Matrix4 modelViewProj;
  2242. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2243. mtxMul(modelViewProj.val, model.val, viewProj[view].val);
  2244. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, modelViewProj.val, bx::uint32_min(4, predefined.m_count) );
  2245. }
  2246. break;
  2247. case PredefinedUniform::ModelViewProjX:
  2248. {
  2249. const Matrix4& model = m_render->m_matrixCache.m_cache[state.m_matrix];
  2250. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2251. {
  2252. 0.5f, 0.0f, 0.0f, 0.0f,
  2253. 0.0f, 0.5f, 0.0f, 0.0f,
  2254. 0.0f, 0.0f, 0.5f, 0.0f,
  2255. 0.5f, 0.5f, 0.5f, 1.0f,
  2256. };
  2257. uint8_t other = m_render->m_other[view];
  2258. Matrix4 viewProjBias;
  2259. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2260. Matrix4 modelViewProj;
  2261. mtxMul(modelViewProj.val, model.val, viewProjBias.val);
  2262. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, modelViewProj.val, bx::uint32_min(4, predefined.m_count) );
  2263. }
  2264. break;
  2265. case PredefinedUniform::ViewProjX:
  2266. {
  2267. static const BX_ALIGN_STRUCT_16(float) s_bias[16] =
  2268. {
  2269. 0.5f, 0.0f, 0.0f, 0.0f,
  2270. 0.0f, 0.5f, 0.0f, 0.0f,
  2271. 0.0f, 0.0f, 0.5f, 0.0f,
  2272. 0.5f, 0.5f, 0.5f, 1.0f,
  2273. };
  2274. uint8_t other = m_render->m_other[view];
  2275. Matrix4 viewProjBias;
  2276. mtxMul(viewProjBias.val, viewProj[other].val, s_bias);
  2277. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, viewProjBias.val, bx::uint32_min(4, predefined.m_count) );
  2278. }
  2279. break;
  2280. case PredefinedUniform::AlphaRef:
  2281. {
  2282. s_renderCtx->setShaderConstantF(flags, predefined.m_loc, &alphaRef, 1);
  2283. }
  2284. break;
  2285. default:
  2286. BX_CHECK(false, "predefined %d not handled", predefined.m_type);
  2287. break;
  2288. }
  2289. }
  2290. }
  2291. // if (BGFX_STATE_TEX_MASK & changedFlags)
  2292. {
  2293. uint64_t flag = BGFX_STATE_TEX0;
  2294. for (uint32_t stage = 0; stage < BGFX_STATE_TEX_COUNT; ++stage)
  2295. {
  2296. const Sampler& sampler = state.m_sampler[stage];
  2297. Sampler& current = currentState.m_sampler[stage];
  2298. if (current.m_idx != sampler.m_idx
  2299. || current.m_flags != sampler.m_flags
  2300. || programChanged)
  2301. {
  2302. if (invalidHandle != sampler.m_idx)
  2303. {
  2304. switch (sampler.m_flags&BGFX_SAMPLER_TYPE_MASK)
  2305. {
  2306. case BGFX_SAMPLER_TEXTURE:
  2307. s_renderCtx->m_textures[sampler.m_idx].commit(stage, sampler.m_flags);
  2308. break;
  2309. case BGFX_SAMPLER_RENDERTARGET_COLOR:
  2310. s_renderCtx->m_renderTargets[sampler.m_idx].commit(stage, sampler.m_flags);
  2311. break;
  2312. case BGFX_SAMPLER_RENDERTARGET_DEPTH:
  2313. // id = s_renderCtx->m_renderTargets[sampler.m_idx].m_depth.m_id;
  2314. break;
  2315. }
  2316. }
  2317. else
  2318. {
  2319. DX_CHECK(device->SetTexture(stage, NULL) );
  2320. }
  2321. }
  2322. current = sampler;
  2323. flag <<= 1;
  2324. }
  2325. }
  2326. if (programChanged
  2327. || currentState.m_vertexBuffer.idx != state.m_vertexBuffer.idx
  2328. || currentState.m_instanceDataBuffer.idx != state.m_instanceDataBuffer.idx
  2329. || currentState.m_instanceDataOffset != state.m_instanceDataOffset
  2330. || currentState.m_instanceDataStride != state.m_instanceDataStride)
  2331. {
  2332. currentState.m_vertexBuffer = state.m_vertexBuffer;
  2333. currentState.m_instanceDataBuffer.idx = state.m_instanceDataBuffer.idx;
  2334. currentState.m_instanceDataOffset = state.m_instanceDataOffset;
  2335. currentState.m_instanceDataStride = state.m_instanceDataStride;
  2336. uint16_t handle = state.m_vertexBuffer.idx;
  2337. if (invalidHandle != handle)
  2338. {
  2339. const VertexBuffer& vb = s_renderCtx->m_vertexBuffers[handle];
  2340. uint16_t decl = !isValid(vb.m_decl) ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2341. const VertexDeclaration& vertexDecl = s_renderCtx->m_vertexDecls[decl];
  2342. DX_CHECK(device->SetStreamSource(0, vb.m_ptr, 0, vertexDecl.m_decl.m_stride) );
  2343. if (isValid(state.m_instanceDataBuffer)
  2344. && s_renderCtx->m_instancing)
  2345. {
  2346. const VertexBuffer& inst = s_renderCtx->m_vertexBuffers[state.m_instanceDataBuffer.idx];
  2347. DX_CHECK(device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA|state.m_numInstances) );
  2348. DX_CHECK(device->SetStreamSourceFreq(1, D3DSTREAMSOURCE_INSTANCEDATA|1) );
  2349. DX_CHECK(device->SetStreamSource(1, inst.m_ptr, state.m_instanceDataOffset, state.m_instanceDataStride) );
  2350. IDirect3DVertexDeclaration9* ptr = createVertexDecl(vertexDecl.m_decl, state.m_instanceDataStride/16);
  2351. DX_CHECK(device->SetVertexDeclaration(ptr) );
  2352. DX_RELEASE(ptr, 0);
  2353. }
  2354. else
  2355. {
  2356. DX_CHECK(device->SetStreamSourceFreq(0, 1) );
  2357. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  2358. DX_CHECK(device->SetVertexDeclaration(vertexDecl.m_ptr) );
  2359. }
  2360. }
  2361. else
  2362. {
  2363. DX_CHECK(device->SetStreamSource(0, NULL, 0, 0) );
  2364. DX_CHECK(device->SetStreamSource(1, NULL, 0, 0) );
  2365. }
  2366. }
  2367. if (currentState.m_indexBuffer.idx != state.m_indexBuffer.idx)
  2368. {
  2369. currentState.m_indexBuffer = state.m_indexBuffer;
  2370. uint16_t handle = state.m_indexBuffer.idx;
  2371. if (invalidHandle != handle)
  2372. {
  2373. const IndexBuffer& ib = s_renderCtx->m_indexBuffers[handle];
  2374. DX_CHECK(device->SetIndices(ib.m_ptr) );
  2375. }
  2376. else
  2377. {
  2378. DX_CHECK(device->SetIndices(NULL) );
  2379. }
  2380. }
  2381. if (isValid(currentState.m_vertexBuffer) )
  2382. {
  2383. uint32_t numVertices = state.m_numVertices;
  2384. if (UINT32_MAX == numVertices)
  2385. {
  2386. const VertexBuffer& vb = s_renderCtx->m_vertexBuffers[currentState.m_vertexBuffer.idx];
  2387. uint16_t decl = !isValid(vb.m_decl) ? state.m_vertexDecl.idx : vb.m_decl.idx;
  2388. const VertexDeclaration& vertexDecl = s_renderCtx->m_vertexDecls[decl];
  2389. numVertices = vb.m_size/vertexDecl.m_decl.m_stride;
  2390. }
  2391. uint32_t numIndices = 0;
  2392. uint32_t numPrimsSubmitted = 0;
  2393. uint32_t numInstances = 0;
  2394. uint32_t numPrimsRendered = 0;
  2395. if (isValid(state.m_indexBuffer) )
  2396. {
  2397. if (UINT32_MAX == state.m_numIndices)
  2398. {
  2399. numIndices = s_renderCtx->m_indexBuffers[state.m_indexBuffer.idx].m_size/2;
  2400. numPrimsSubmitted = numIndices/primNumVerts;
  2401. numInstances = state.m_numInstances;
  2402. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2403. DX_CHECK(device->DrawIndexedPrimitive(primType
  2404. , state.m_startVertex
  2405. , 0
  2406. , numVertices
  2407. , 0
  2408. , numPrimsSubmitted
  2409. ) );
  2410. }
  2411. else if (primNumVerts <= state.m_numIndices)
  2412. {
  2413. numIndices = state.m_numIndices;
  2414. numPrimsSubmitted = numIndices/primNumVerts;
  2415. numInstances = state.m_numInstances;
  2416. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2417. DX_CHECK(device->DrawIndexedPrimitive(primType
  2418. , state.m_startVertex
  2419. , 0
  2420. , numVertices
  2421. , state.m_startIndex
  2422. , numPrimsSubmitted
  2423. ) );
  2424. }
  2425. }
  2426. else
  2427. {
  2428. numPrimsSubmitted = numVertices/primNumVerts;
  2429. numInstances = state.m_numInstances;
  2430. numPrimsRendered = numPrimsSubmitted*state.m_numInstances;
  2431. DX_CHECK(device->DrawPrimitive(primType
  2432. , state.m_startVertex
  2433. , numPrimsSubmitted
  2434. ) );
  2435. }
  2436. statsNumPrimsSubmitted += numPrimsSubmitted;
  2437. statsNumIndices += numIndices;
  2438. statsNumInstances += numInstances;
  2439. statsNumPrimsRendered += numPrimsRendered;
  2440. }
  2441. }
  2442. PIX_ENDEVENT();
  2443. if (0 < m_render->m_num)
  2444. {
  2445. captureElapsed = -bx::getHPCounter();
  2446. s_renderCtx->capture();
  2447. captureElapsed += bx::getHPCounter();
  2448. }
  2449. }
  2450. int64_t now = bx::getHPCounter();
  2451. elapsed += now;
  2452. static int64_t last = now;
  2453. int64_t frameTime = now - last;
  2454. last = now;
  2455. static int64_t min = frameTime;
  2456. static int64_t max = frameTime;
  2457. min = min > frameTime ? frameTime : min;
  2458. max = max < frameTime ? frameTime : max;
  2459. if (m_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  2460. {
  2461. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugstats");
  2462. TextVideoMem& tvm = s_renderCtx->m_textVideoMem;
  2463. static int64_t next = now;
  2464. if (now >= next)
  2465. {
  2466. next = now + bx::getHPFrequency();
  2467. double freq = double(bx::getHPFrequency() );
  2468. double toMs = 1000.0/freq;
  2469. tvm.clear();
  2470. uint16_t pos = 0;
  2471. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " " BGFX_RENDERER_NAME " / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " ");
  2472. const D3DADAPTER_IDENTIFIER9& identifier = s_renderCtx->m_identifier;
  2473. tvm.printf(0, pos++, 0x0f, " Device: %s (%s)", identifier.Description, identifier.Driver);
  2474. pos = 10;
  2475. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS%s"
  2476. , double(frameTime)*toMs
  2477. , double(min)*toMs
  2478. , double(max)*toMs
  2479. , freq/frameTime
  2480. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? " (vsync)" : ""
  2481. );
  2482. double elapsedCpuMs = double(elapsed)*toMs;
  2483. tvm.printf(10, pos++, 0x8e, " Draw calls: %4d / CPU %3.4f [ms]"
  2484. , m_render->m_num
  2485. , elapsedCpuMs
  2486. );
  2487. tvm.printf(10, pos++, 0x8e, " Prims: %7d (#inst: %5d), submitted: %7d"
  2488. , statsNumPrimsRendered
  2489. , statsNumInstances
  2490. , statsNumPrimsSubmitted
  2491. );
  2492. double captureMs = double(captureElapsed)*toMs;
  2493. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  2494. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  2495. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", m_render->m_vboffset);
  2496. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", m_render->m_iboffset);
  2497. uint8_t attr[2] = { 0x89, 0x8a };
  2498. uint8_t attrIndex = m_render->m_waitSubmit < m_render->m_waitRender;
  2499. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", m_render->m_waitSubmit*toMs);
  2500. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", m_render->m_waitRender*toMs);
  2501. min = frameTime;
  2502. max = frameTime;
  2503. }
  2504. m_textVideoMemBlitter.blit(tvm);
  2505. PIX_ENDEVENT();
  2506. }
  2507. else if (m_render->m_debug & BGFX_DEBUG_TEXT)
  2508. {
  2509. PIX_BEGINEVENT(D3DCOLOR_RGBA(0x40, 0x40, 0x40, 0xff), L"debugtext");
  2510. m_textVideoMemBlitter.blit(m_render->m_textVideoMem);
  2511. PIX_ENDEVENT();
  2512. }
  2513. device->EndScene();
  2514. }
  2515. }
  2516. #endif // BGFX_CONFIG_RENDERER_DIRECT3D9