renderer_d3d9.cpp 79 KB

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