d3d11-subsystem.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <cassert>
  15. #include <cinttypes>
  16. #include <util/base.h>
  17. #include <util/platform.h>
  18. #include <util/dstr.h>
  19. #include <util/util.hpp>
  20. #include <graphics/matrix3.h>
  21. #include <winternl.h>
  22. #include <d3d9.h>
  23. #include "d3d11-subsystem.hpp"
  24. #include "d3d11-config.h"
  25. #include "intel-nv12-support.hpp"
  26. struct UnsupportedHWError : HRError {
  27. inline UnsupportedHWError(const char *str, HRESULT hr)
  28. : HRError(str, hr)
  29. {
  30. }
  31. };
  32. #ifdef _MSC_VER
  33. /* alignment warning - despite the fact that alignment is already fixed */
  34. #pragma warning(disable : 4316)
  35. #endif
  36. static inline void LogD3D11ErrorDetails(HRError error, gs_device_t *device)
  37. {
  38. if (error.hr == DXGI_ERROR_DEVICE_REMOVED) {
  39. HRESULT DeviceRemovedReason =
  40. device->device->GetDeviceRemovedReason();
  41. blog(LOG_ERROR, " Device Removed Reason: %08lX",
  42. DeviceRemovedReason);
  43. }
  44. }
  45. static const IID dxgiFactory2 = {0x50c83a1c,
  46. 0xe072,
  47. 0x4c48,
  48. {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6,
  49. 0xd0}};
  50. gs_obj::gs_obj(gs_device_t *device_, gs_type type)
  51. : device(device_), obj_type(type)
  52. {
  53. prev_next = &device->first_obj;
  54. next = device->first_obj;
  55. device->first_obj = this;
  56. if (next)
  57. next->prev_next = &next;
  58. }
  59. gs_obj::~gs_obj()
  60. {
  61. if (prev_next)
  62. *prev_next = next;
  63. if (next)
  64. next->prev_next = prev_next;
  65. }
  66. static inline void make_swap_desc(DXGI_SWAP_CHAIN_DESC &desc,
  67. const gs_init_data *data,
  68. DXGI_SWAP_EFFECT effect, UINT flags)
  69. {
  70. memset(&desc, 0, sizeof(desc));
  71. desc.BufferDesc.Width = data->cx;
  72. desc.BufferDesc.Height = data->cy;
  73. desc.BufferDesc.Format = ConvertGSTextureFormatView(data->format);
  74. desc.SampleDesc.Count = 1;
  75. desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  76. desc.BufferCount = data->num_backbuffers;
  77. desc.OutputWindow = (HWND)data->window.hwnd;
  78. desc.Windowed = TRUE;
  79. desc.SwapEffect = effect;
  80. desc.Flags = flags;
  81. }
  82. void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy)
  83. {
  84. HRESULT hr;
  85. target.width = cx;
  86. target.height = cy;
  87. hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D),
  88. (void **)target.texture.Assign());
  89. if (FAILED(hr))
  90. throw HRError("Failed to get swap buffer texture", hr);
  91. D3D11_RENDER_TARGET_VIEW_DESC rtv;
  92. rtv.Format = target.dxgiFormatView;
  93. rtv.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  94. rtv.Texture2D.MipSlice = 0;
  95. hr = device->device->CreateRenderTargetView(
  96. target.texture, &rtv, target.renderTarget[0].Assign());
  97. if (FAILED(hr))
  98. throw HRError("Failed to create swap RTV", hr);
  99. if (target.dxgiFormatView == target.dxgiFormatViewLinear) {
  100. target.renderTargetLinear[0] = target.renderTarget[0];
  101. } else {
  102. rtv.Format = target.dxgiFormatViewLinear;
  103. hr = device->device->CreateRenderTargetView(
  104. target.texture, &rtv,
  105. target.renderTargetLinear[0].Assign());
  106. if (FAILED(hr))
  107. throw HRError("Failed to create linear swap RTV", hr);
  108. }
  109. }
  110. void gs_swap_chain::InitZStencilBuffer(uint32_t cx, uint32_t cy)
  111. {
  112. zs.width = cx;
  113. zs.height = cy;
  114. if (zs.format != GS_ZS_NONE && cx != 0 && cy != 0) {
  115. zs.InitBuffer();
  116. } else {
  117. zs.texture.Clear();
  118. zs.view.Clear();
  119. }
  120. }
  121. void gs_swap_chain::Resize(uint32_t cx, uint32_t cy)
  122. {
  123. RECT clientRect;
  124. HRESULT hr;
  125. target.texture.Clear();
  126. target.renderTarget[0].Clear();
  127. target.renderTargetLinear[0].Clear();
  128. zs.texture.Clear();
  129. zs.view.Clear();
  130. initData.cx = cx;
  131. initData.cy = cy;
  132. if (cx == 0 || cy == 0) {
  133. GetClientRect(hwnd, &clientRect);
  134. if (cx == 0)
  135. cx = clientRect.right;
  136. if (cy == 0)
  137. cy = clientRect.bottom;
  138. }
  139. hr = swap->ResizeBuffers(swapDesc.BufferCount, cx, cy,
  140. DXGI_FORMAT_UNKNOWN, swapDesc.Flags);
  141. if (FAILED(hr))
  142. throw HRError("Failed to resize swap buffers", hr);
  143. InitTarget(cx, cy);
  144. InitZStencilBuffer(cx, cy);
  145. }
  146. void gs_swap_chain::Init()
  147. {
  148. target.device = device;
  149. target.isRenderTarget = true;
  150. target.format = initData.format;
  151. target.dxgiFormatResource =
  152. ConvertGSTextureFormatResource(initData.format);
  153. target.dxgiFormatView = ConvertGSTextureFormatView(initData.format);
  154. target.dxgiFormatViewLinear =
  155. ConvertGSTextureFormatViewLinear(initData.format);
  156. InitTarget(initData.cx, initData.cy);
  157. zs.device = device;
  158. zs.format = initData.zsformat;
  159. zs.dxgiFormat = ConvertGSZStencilFormat(initData.zsformat);
  160. InitZStencilBuffer(initData.cx, initData.cy);
  161. }
  162. gs_swap_chain::gs_swap_chain(gs_device *device, const gs_init_data *data)
  163. : gs_obj(device, gs_type::gs_swap_chain),
  164. hwnd((HWND)data->window.hwnd),
  165. initData(*data)
  166. {
  167. struct win_version_info ver;
  168. get_win_ver(&ver);
  169. constexpr win_version_info minimum = [] {
  170. win_version_info ver{};
  171. ver.major = 10;
  172. ver.minor = 0;
  173. ver.build = 22000;
  174. ver.revis = 0;
  175. return ver;
  176. }();
  177. DXGI_SWAP_EFFECT effect = DXGI_SWAP_EFFECT_DISCARD;
  178. UINT flags = 0;
  179. if (win_version_compare(&ver, &minimum) >= 0) {
  180. initData.num_backbuffers = max(data->num_backbuffers, 2);
  181. effect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
  182. ComPtr<IDXGIFactory5> factory5;
  183. HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory5));
  184. if (SUCCEEDED(hr)) {
  185. BOOL featureSupportData = FALSE;
  186. hr = factory5->CheckFeatureSupport(
  187. DXGI_FEATURE_PRESENT_ALLOW_TEARING,
  188. &featureSupportData,
  189. sizeof(featureSupportData));
  190. if (SUCCEEDED(hr) && featureSupportData) {
  191. presentFlags |= DXGI_PRESENT_ALLOW_TEARING;
  192. flags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
  193. }
  194. }
  195. }
  196. make_swap_desc(swapDesc, &initData, effect, flags);
  197. const HRESULT hr = device->factory->CreateSwapChain(
  198. device->device, &swapDesc, swap.Assign());
  199. if (FAILED(hr))
  200. throw HRError("Failed to create swap chain", hr);
  201. /* Ignore Alt+Enter */
  202. device->factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER);
  203. Init();
  204. }
  205. void gs_device::InitCompiler()
  206. {
  207. char d3dcompiler[40] = {};
  208. int ver = 49;
  209. while (ver > 30) {
  210. sprintf(d3dcompiler, "D3DCompiler_%02d.dll", ver);
  211. HMODULE module = LoadLibraryA(d3dcompiler);
  212. if (module) {
  213. d3dCompile = (pD3DCompile)GetProcAddress(module,
  214. "D3DCompile");
  215. #ifdef DISASSEMBLE_SHADERS
  216. d3dDisassemble = (pD3DDisassemble)GetProcAddress(
  217. module, "D3DDisassemble");
  218. #endif
  219. if (d3dCompile) {
  220. return;
  221. }
  222. FreeLibrary(module);
  223. }
  224. ver--;
  225. }
  226. throw "Could not find any D3DCompiler libraries. Make sure you've "
  227. "installed the <a href=\"https://obsproject.com/go/dxwebsetup\">"
  228. "DirectX components</a> that OBS Studio requires.";
  229. }
  230. void gs_device::InitFactory()
  231. {
  232. HRESULT hr;
  233. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  234. : __uuidof(IDXGIFactory1);
  235. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  236. if (FAILED(hr))
  237. throw UnsupportedHWError("Failed to create DXGIFactory", hr);
  238. }
  239. #define VENDOR_ID_INTEL 0x8086
  240. #define IGPU_MEM (512 * 1024 * 1024)
  241. void gs_device::ReorderAdapters(uint32_t &adapterIdx)
  242. {
  243. std::vector<uint32_t> adapterOrder;
  244. ComPtr<IDXGIAdapter> adapter;
  245. DXGI_ADAPTER_DESC desc;
  246. uint32_t iGPUIndex = 0;
  247. bool hasIGPU = false;
  248. bool hasDGPU = false;
  249. int idx = 0;
  250. while (SUCCEEDED(factory->EnumAdapters(idx, &adapter))) {
  251. if (SUCCEEDED(adapter->GetDesc(&desc))) {
  252. if (desc.VendorId == VENDOR_ID_INTEL) {
  253. if (desc.DedicatedVideoMemory <= IGPU_MEM) {
  254. hasIGPU = true;
  255. iGPUIndex = (uint32_t)idx;
  256. } else {
  257. hasDGPU = true;
  258. }
  259. }
  260. }
  261. adapterOrder.push_back((uint32_t)idx++);
  262. }
  263. /* Intel specific adapter check for Intel integrated and Intel
  264. * dedicated. If both exist, then change adapter priority so that the
  265. * integrated comes first for the sake of improving overall
  266. * performance */
  267. if (hasIGPU && hasDGPU) {
  268. adapterOrder.erase(adapterOrder.begin() + iGPUIndex);
  269. adapterOrder.insert(adapterOrder.begin(), iGPUIndex);
  270. adapterIdx = adapterOrder[adapterIdx];
  271. }
  272. }
  273. void gs_device::InitAdapter(uint32_t adapterIdx)
  274. {
  275. HRESULT hr = factory->EnumAdapters1(adapterIdx, &adapter);
  276. if (FAILED(hr))
  277. throw UnsupportedHWError("Failed to enumerate DXGIAdapter", hr);
  278. }
  279. const static D3D_FEATURE_LEVEL featureLevels[] = {
  280. D3D_FEATURE_LEVEL_11_0,
  281. D3D_FEATURE_LEVEL_10_1,
  282. D3D_FEATURE_LEVEL_10_0,
  283. };
  284. /* ------------------------------------------------------------------------- */
  285. #define VERT_IN_OUT \
  286. "\
  287. struct VertInOut { \
  288. float4 pos : POSITION; \
  289. }; "
  290. #define NV12_Y_PS \
  291. VERT_IN_OUT "\
  292. float main(VertInOut vert_in) : TARGET \
  293. { \
  294. return 1.0; \
  295. }"
  296. #define NV12_UV_PS \
  297. VERT_IN_OUT "\
  298. float2 main(VertInOut vert_in) : TARGET \
  299. { \
  300. return float2(1.0, 1.0); \
  301. }"
  302. #define NV12_VS \
  303. VERT_IN_OUT "\
  304. VertInOut main(VertInOut vert_in) \
  305. { \
  306. VertInOut vert_out; \
  307. vert_out.pos = float4(vert_in.pos.xyz, 1.0); \
  308. return vert_out; \
  309. } "
  310. /* ------------------------------------------------------------------------- */
  311. #define NV12_CX 128
  312. #define NV12_CY 128
  313. bool gs_device::HasBadNV12Output()
  314. try {
  315. vec3 points[4];
  316. vec3_set(&points[0], -1.0f, -1.0f, 0.0f);
  317. vec3_set(&points[1], -1.0f, 1.0f, 0.0f);
  318. vec3_set(&points[2], 1.0f, -1.0f, 0.0f);
  319. vec3_set(&points[3], 1.0f, 1.0f, 0.0f);
  320. gs_texture_2d nv12_y(this, NV12_CX, NV12_CY, GS_R8, 1, nullptr,
  321. GS_RENDER_TARGET | GS_SHARED_KM_TEX, GS_TEXTURE_2D,
  322. false, true);
  323. gs_texture_2d nv12_uv(this, nv12_y.texture,
  324. GS_RENDER_TARGET | GS_SHARED_KM_TEX);
  325. gs_vertex_shader nv12_vs(this, "", NV12_VS);
  326. gs_pixel_shader nv12_y_ps(this, "", NV12_Y_PS);
  327. gs_pixel_shader nv12_uv_ps(this, "", NV12_UV_PS);
  328. gs_stage_surface nv12_stage(this, NV12_CX, NV12_CY);
  329. gs_vb_data *vbd = gs_vbdata_create();
  330. vbd->num = 4;
  331. vbd->points = (vec3 *)bmemdup(&points, sizeof(points));
  332. gs_vertex_buffer buf(this, vbd, 0);
  333. device_load_vertexbuffer(this, &buf);
  334. device_load_vertexshader(this, &nv12_vs);
  335. context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
  336. device_set_viewport(this, 0, 0, NV12_CX, NV12_CY);
  337. device_set_cull_mode(this, GS_NEITHER);
  338. device_enable_depth_test(this, false);
  339. device_enable_blending(this, false);
  340. LoadVertexBufferData();
  341. device_set_render_target(this, &nv12_y, nullptr);
  342. device_load_pixelshader(this, &nv12_y_ps);
  343. UpdateBlendState();
  344. UpdateRasterState();
  345. UpdateZStencilState();
  346. FlushOutputViews();
  347. context->Draw(4, 0);
  348. device_set_viewport(this, 0, 0, NV12_CX / 2, NV12_CY / 2);
  349. device_set_render_target(this, &nv12_uv, nullptr);
  350. device_load_pixelshader(this, &nv12_uv_ps);
  351. UpdateBlendState();
  352. UpdateRasterState();
  353. UpdateZStencilState();
  354. FlushOutputViews();
  355. context->Draw(4, 0);
  356. device_load_pixelshader(this, nullptr);
  357. device_load_vertexbuffer(this, nullptr);
  358. device_load_vertexshader(this, nullptr);
  359. device_set_render_target(this, nullptr, nullptr);
  360. device_stage_texture(this, &nv12_stage, &nv12_y);
  361. uint8_t *data;
  362. uint32_t linesize;
  363. bool bad_driver = false;
  364. if (gs_stagesurface_map(&nv12_stage, &data, &linesize)) {
  365. bad_driver = data[linesize * NV12_CY] == 0;
  366. gs_stagesurface_unmap(&nv12_stage);
  367. } else {
  368. throw "Could not map surface";
  369. }
  370. if (bad_driver) {
  371. blog(LOG_WARNING, "Bad NV12 texture handling detected! "
  372. "Disabling NV12 texture support.");
  373. }
  374. return bad_driver;
  375. } catch (const HRError &error) {
  376. blog(LOG_WARNING, "HasBadNV12Output failed: %s (%08lX)", error.str,
  377. error.hr);
  378. return false;
  379. } catch (const char *error) {
  380. blog(LOG_WARNING, "HasBadNV12Output failed: %s", error);
  381. return false;
  382. }
  383. static bool increase_maximum_frame_latency(ID3D11Device *device)
  384. {
  385. ComQIPtr<IDXGIDevice1> dxgiDevice(device);
  386. if (!dxgiDevice) {
  387. blog(LOG_DEBUG, "%s: Failed to get IDXGIDevice1", __FUNCTION__);
  388. return false;
  389. }
  390. const HRESULT hr = dxgiDevice->SetMaximumFrameLatency(16);
  391. if (FAILED(hr)) {
  392. blog(LOG_DEBUG, "%s: SetMaximumFrameLatency failed",
  393. __FUNCTION__);
  394. return false;
  395. }
  396. blog(LOG_INFO, "DXGI increase maximum frame latency success");
  397. return true;
  398. }
  399. #if USE_GPU_PRIORITY
  400. static bool set_priority(ID3D11Device *device)
  401. {
  402. typedef enum _D3DKMT_SCHEDULINGPRIORITYCLASS {
  403. D3DKMT_SCHEDULINGPRIORITYCLASS_IDLE,
  404. D3DKMT_SCHEDULINGPRIORITYCLASS_BELOW_NORMAL,
  405. D3DKMT_SCHEDULINGPRIORITYCLASS_NORMAL,
  406. D3DKMT_SCHEDULINGPRIORITYCLASS_ABOVE_NORMAL,
  407. D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH,
  408. D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME
  409. } D3DKMT_SCHEDULINGPRIORITYCLASS;
  410. ComQIPtr<IDXGIDevice> dxgiDevice(device);
  411. if (!dxgiDevice) {
  412. blog(LOG_DEBUG, "%s: Failed to get IDXGIDevice", __FUNCTION__);
  413. return false;
  414. }
  415. HMODULE gdi32 = GetModuleHandleW(L"GDI32");
  416. if (!gdi32) {
  417. blog(LOG_DEBUG, "%s: Failed to get GDI32", __FUNCTION__);
  418. return false;
  419. }
  420. NTSTATUS(WINAPI * d3dkmt_spspc)(HANDLE, D3DKMT_SCHEDULINGPRIORITYCLASS);
  421. d3dkmt_spspc = (decltype(d3dkmt_spspc))GetProcAddress(
  422. gdi32, "D3DKMTSetProcessSchedulingPriorityClass");
  423. if (!d3dkmt_spspc) {
  424. blog(LOG_DEBUG, "%s: Failed to get d3dkmt_spspc", __FUNCTION__);
  425. return false;
  426. }
  427. NTSTATUS status = d3dkmt_spspc(GetCurrentProcess(),
  428. D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME);
  429. if (status != 0) {
  430. blog(LOG_DEBUG, "%s: Failed to set process priority class: %d",
  431. __FUNCTION__, (int)status);
  432. return false;
  433. }
  434. HRESULT hr = dxgiDevice->SetGPUThreadPriority(GPU_PRIORITY_VAL);
  435. if (FAILED(hr)) {
  436. blog(LOG_DEBUG, "%s: SetGPUThreadPriority failed",
  437. __FUNCTION__);
  438. return false;
  439. }
  440. blog(LOG_INFO, "D3D11 GPU priority setup success");
  441. return true;
  442. }
  443. #endif
  444. void gs_device::InitDevice(uint32_t adapterIdx)
  445. {
  446. wstring adapterName;
  447. DXGI_ADAPTER_DESC desc;
  448. D3D_FEATURE_LEVEL levelUsed = D3D_FEATURE_LEVEL_10_0;
  449. HRESULT hr = 0;
  450. adpIdx = adapterIdx;
  451. uint32_t createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  452. #ifdef _DEBUG
  453. //createFlags |= D3D11_CREATE_DEVICE_DEBUG;
  454. #endif
  455. adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description
  456. : L"<unknown>";
  457. BPtr<char> adapterNameUTF8;
  458. os_wcs_to_utf8_ptr(adapterName.c_str(), 0, &adapterNameUTF8);
  459. blog(LOG_INFO, "Loading up D3D11 on adapter %s (%" PRIu32 ")",
  460. adapterNameUTF8.Get(), adapterIdx);
  461. hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL,
  462. createFlags, featureLevels,
  463. sizeof(featureLevels) /
  464. sizeof(D3D_FEATURE_LEVEL),
  465. D3D11_SDK_VERSION, device.Assign(), &levelUsed,
  466. context.Assign());
  467. if (FAILED(hr))
  468. throw UnsupportedHWError("Failed to create device", hr);
  469. blog(LOG_INFO, "D3D11 loaded successfully, feature level used: %x",
  470. (unsigned int)levelUsed);
  471. /* prevent stalls sometimes seen in Present calls */
  472. if (!increase_maximum_frame_latency(device)) {
  473. blog(LOG_INFO, "DXGI increase maximum frame latency failed");
  474. }
  475. /* adjust gpu thread priority on non-intel GPUs */
  476. #if USE_GPU_PRIORITY
  477. if (desc.VendorId != 0x8086 && !set_priority(device)) {
  478. blog(LOG_INFO, "D3D11 GPU priority setup "
  479. "failed (not admin?)");
  480. }
  481. #endif
  482. /* ---------------------------------------- */
  483. /* check for nv12 texture output support */
  484. nv12Supported = false;
  485. /* WARP NV12 support is suspected to be buggy on older Windows */
  486. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) {
  487. return;
  488. }
  489. /* Intel CopyResource is very slow with NV12 */
  490. if (desc.VendorId == 0x8086 && IsOldIntelPlatform(desc.DeviceId)) {
  491. return;
  492. }
  493. ComQIPtr<ID3D11Device1> d3d11_1(device);
  494. if (!d3d11_1) {
  495. return;
  496. }
  497. /* needs to support extended resource sharing */
  498. D3D11_FEATURE_DATA_D3D11_OPTIONS opts = {};
  499. hr = d3d11_1->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &opts,
  500. sizeof(opts));
  501. if (FAILED(hr) || !opts.ExtendedResourceSharing) {
  502. return;
  503. }
  504. /* needs to support the actual format */
  505. UINT support = 0;
  506. hr = device->CheckFormatSupport(DXGI_FORMAT_NV12, &support);
  507. if (FAILED(hr)) {
  508. return;
  509. }
  510. if ((support & D3D11_FORMAT_SUPPORT_TEXTURE2D) == 0) {
  511. return;
  512. }
  513. /* must be usable as a render target */
  514. if ((support & D3D11_FORMAT_SUPPORT_RENDER_TARGET) == 0) {
  515. return;
  516. }
  517. if (HasBadNV12Output()) {
  518. return;
  519. }
  520. nv12Supported = true;
  521. }
  522. static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc,
  523. const StencilSide &side)
  524. {
  525. desc.StencilFunc = ConvertGSDepthTest(side.test);
  526. desc.StencilFailOp = ConvertGSStencilOp(side.fail);
  527. desc.StencilDepthFailOp = ConvertGSStencilOp(side.zfail);
  528. desc.StencilPassOp = ConvertGSStencilOp(side.zpass);
  529. }
  530. ID3D11DepthStencilState *gs_device::AddZStencilState()
  531. {
  532. HRESULT hr;
  533. D3D11_DEPTH_STENCIL_DESC dsd;
  534. ID3D11DepthStencilState *state;
  535. dsd.DepthEnable = zstencilState.depthEnabled;
  536. dsd.DepthFunc = ConvertGSDepthTest(zstencilState.depthFunc);
  537. dsd.DepthWriteMask = zstencilState.depthWriteEnabled
  538. ? D3D11_DEPTH_WRITE_MASK_ALL
  539. : D3D11_DEPTH_WRITE_MASK_ZERO;
  540. dsd.StencilEnable = zstencilState.stencilEnabled;
  541. dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
  542. dsd.StencilWriteMask = zstencilState.stencilWriteEnabled
  543. ? D3D11_DEFAULT_STENCIL_WRITE_MASK
  544. : 0;
  545. ConvertStencilSide(dsd.FrontFace, zstencilState.stencilFront);
  546. ConvertStencilSide(dsd.BackFace, zstencilState.stencilBack);
  547. SavedZStencilState savedState(zstencilState, dsd);
  548. hr = device->CreateDepthStencilState(&dsd, savedState.state.Assign());
  549. if (FAILED(hr))
  550. throw HRError("Failed to create depth stencil state", hr);
  551. state = savedState.state;
  552. zstencilStates.push_back(savedState);
  553. return state;
  554. }
  555. ID3D11RasterizerState *gs_device::AddRasterState()
  556. {
  557. HRESULT hr;
  558. D3D11_RASTERIZER_DESC rd;
  559. ID3D11RasterizerState *state;
  560. memset(&rd, 0, sizeof(rd));
  561. /* use CCW to convert to a right-handed coordinate system */
  562. rd.FrontCounterClockwise = true;
  563. rd.FillMode = D3D11_FILL_SOLID;
  564. rd.CullMode = ConvertGSCullMode(rasterState.cullMode);
  565. rd.DepthClipEnable = true;
  566. rd.ScissorEnable = rasterState.scissorEnabled;
  567. SavedRasterState savedState(rasterState, rd);
  568. hr = device->CreateRasterizerState(&rd, savedState.state.Assign());
  569. if (FAILED(hr))
  570. throw HRError("Failed to create rasterizer state", hr);
  571. state = savedState.state;
  572. rasterStates.push_back(savedState);
  573. return state;
  574. }
  575. ID3D11BlendState *gs_device::AddBlendState()
  576. {
  577. HRESULT hr;
  578. D3D11_BLEND_DESC bd;
  579. ID3D11BlendState *state;
  580. memset(&bd, 0, sizeof(bd));
  581. for (int i = 0; i < 8; i++) {
  582. bd.RenderTarget[i].BlendEnable = blendState.blendEnabled;
  583. bd.RenderTarget[i].BlendOp = D3D11_BLEND_OP_ADD;
  584. bd.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD;
  585. bd.RenderTarget[i].SrcBlend =
  586. ConvertGSBlendType(blendState.srcFactorC);
  587. bd.RenderTarget[i].DestBlend =
  588. ConvertGSBlendType(blendState.destFactorC);
  589. bd.RenderTarget[i].SrcBlendAlpha =
  590. ConvertGSBlendType(blendState.srcFactorA);
  591. bd.RenderTarget[i].DestBlendAlpha =
  592. ConvertGSBlendType(blendState.destFactorA);
  593. bd.RenderTarget[i].RenderTargetWriteMask =
  594. (blendState.redEnabled ? D3D11_COLOR_WRITE_ENABLE_RED
  595. : 0) |
  596. (blendState.greenEnabled
  597. ? D3D11_COLOR_WRITE_ENABLE_GREEN
  598. : 0) |
  599. (blendState.blueEnabled ? D3D11_COLOR_WRITE_ENABLE_BLUE
  600. : 0) |
  601. (blendState.alphaEnabled
  602. ? D3D11_COLOR_WRITE_ENABLE_ALPHA
  603. : 0);
  604. }
  605. SavedBlendState savedState(blendState, bd);
  606. hr = device->CreateBlendState(&bd, savedState.state.Assign());
  607. if (FAILED(hr))
  608. throw HRError("Failed to create blend state", hr);
  609. state = savedState.state;
  610. blendStates.push_back(savedState);
  611. return state;
  612. }
  613. void gs_device::UpdateZStencilState()
  614. {
  615. ID3D11DepthStencilState *state = NULL;
  616. if (!zstencilStateChanged)
  617. return;
  618. for (size_t i = 0; i < zstencilStates.size(); i++) {
  619. SavedZStencilState &s = zstencilStates[i];
  620. if (memcmp(&s, &zstencilState, sizeof(zstencilState)) == 0) {
  621. state = s.state;
  622. break;
  623. }
  624. }
  625. if (!state)
  626. state = AddZStencilState();
  627. if (state != curDepthStencilState) {
  628. context->OMSetDepthStencilState(state, 0);
  629. curDepthStencilState = state;
  630. }
  631. zstencilStateChanged = false;
  632. }
  633. void gs_device::UpdateRasterState()
  634. {
  635. ID3D11RasterizerState *state = NULL;
  636. if (!rasterStateChanged)
  637. return;
  638. for (size_t i = 0; i < rasterStates.size(); i++) {
  639. SavedRasterState &s = rasterStates[i];
  640. if (memcmp(&s, &rasterState, sizeof(rasterState)) == 0) {
  641. state = s.state;
  642. break;
  643. }
  644. }
  645. if (!state)
  646. state = AddRasterState();
  647. if (state != curRasterState) {
  648. context->RSSetState(state);
  649. curRasterState = state;
  650. }
  651. rasterStateChanged = false;
  652. }
  653. void gs_device::UpdateBlendState()
  654. {
  655. ID3D11BlendState *state = NULL;
  656. if (!blendStateChanged)
  657. return;
  658. for (size_t i = 0; i < blendStates.size(); i++) {
  659. SavedBlendState &s = blendStates[i];
  660. if (memcmp(&s, &blendState, sizeof(blendState)) == 0) {
  661. state = s.state;
  662. break;
  663. }
  664. }
  665. if (!state)
  666. state = AddBlendState();
  667. if (state != curBlendState) {
  668. float f[4] = {1.0f, 1.0f, 1.0f, 1.0f};
  669. context->OMSetBlendState(state, f, 0xFFFFFFFF);
  670. curBlendState = state;
  671. }
  672. blendStateChanged = false;
  673. }
  674. void gs_device::UpdateViewProjMatrix()
  675. {
  676. gs_matrix_get(&curViewMatrix);
  677. /* negate Z col of the view matrix for right-handed coordinate system */
  678. curViewMatrix.x.z = -curViewMatrix.x.z;
  679. curViewMatrix.y.z = -curViewMatrix.y.z;
  680. curViewMatrix.z.z = -curViewMatrix.z.z;
  681. curViewMatrix.t.z = -curViewMatrix.t.z;
  682. matrix4_mul(&curViewProjMatrix, &curViewMatrix, &curProjMatrix);
  683. matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix);
  684. if (curVertexShader->viewProj)
  685. gs_shader_set_matrix4(curVertexShader->viewProj,
  686. &curViewProjMatrix);
  687. }
  688. void gs_device::FlushOutputViews()
  689. {
  690. if (curFramebufferInvalidate) {
  691. ID3D11RenderTargetView *rtv = nullptr;
  692. if (curRenderTarget) {
  693. const int i = curRenderSide;
  694. rtv = curFramebufferSrgb
  695. ? curRenderTarget->renderTargetLinear[i]
  696. .Get()
  697. : curRenderTarget->renderTarget[i].Get();
  698. if (!rtv) {
  699. blog(LOG_ERROR,
  700. "device_draw (D3D11): texture is not a render target");
  701. return;
  702. }
  703. }
  704. ID3D11DepthStencilView *dsv = nullptr;
  705. if (curZStencilBuffer)
  706. dsv = curZStencilBuffer->view;
  707. context->OMSetRenderTargets(1, &rtv, dsv);
  708. curFramebufferInvalidate = false;
  709. }
  710. }
  711. gs_device::gs_device(uint32_t adapterIdx)
  712. : curToplogy(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED)
  713. {
  714. matrix4_identity(&curProjMatrix);
  715. matrix4_identity(&curViewMatrix);
  716. matrix4_identity(&curViewProjMatrix);
  717. memset(&viewport, 0, sizeof(viewport));
  718. for (size_t i = 0; i < GS_MAX_TEXTURES; i++) {
  719. curTextures[i] = NULL;
  720. curSamplers[i] = NULL;
  721. }
  722. InitCompiler();
  723. InitFactory();
  724. ReorderAdapters(adapterIdx);
  725. InitAdapter(adapterIdx);
  726. InitDevice(adapterIdx);
  727. device_set_render_target(this, NULL, NULL);
  728. }
  729. gs_device::~gs_device()
  730. {
  731. context->ClearState();
  732. }
  733. const char *device_get_name(void)
  734. {
  735. return "Direct3D 11";
  736. }
  737. int device_get_type(void)
  738. {
  739. return GS_DEVICE_DIRECT3D_11;
  740. }
  741. const char *device_preprocessor_name(void)
  742. {
  743. return "_D3D11";
  744. }
  745. static inline void
  746. EnumD3DAdapters(bool (*callback)(void *, const char *, uint32_t), void *param)
  747. {
  748. ComPtr<IDXGIFactory1> factory;
  749. ComPtr<IDXGIAdapter1> adapter;
  750. HRESULT hr;
  751. UINT i;
  752. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  753. : __uuidof(IDXGIFactory1);
  754. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  755. if (FAILED(hr))
  756. throw HRError("Failed to create DXGIFactory", hr);
  757. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  758. DXGI_ADAPTER_DESC desc;
  759. char name[512] = "";
  760. hr = adapter->GetDesc(&desc);
  761. if (FAILED(hr))
  762. continue;
  763. /* ignore Microsoft's 'basic' renderer' */
  764. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  765. continue;
  766. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  767. if (!callback(param, name, i))
  768. break;
  769. }
  770. }
  771. bool device_enum_adapters(bool (*callback)(void *param, const char *name,
  772. uint32_t id),
  773. void *param)
  774. {
  775. try {
  776. EnumD3DAdapters(callback, param);
  777. return true;
  778. } catch (const HRError &error) {
  779. blog(LOG_WARNING, "Failed enumerating devices: %s (%08lX)",
  780. error.str, error.hr);
  781. return false;
  782. }
  783. }
  784. static bool GetMonitorTarget(const MONITORINFOEX &info,
  785. DISPLAYCONFIG_TARGET_DEVICE_NAME &target)
  786. {
  787. bool found = false;
  788. UINT32 numPath, numMode;
  789. if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath,
  790. &numMode) == ERROR_SUCCESS) {
  791. std::vector<DISPLAYCONFIG_PATH_INFO> paths(numPath);
  792. std::vector<DISPLAYCONFIG_MODE_INFO> modes(numMode);
  793. if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath,
  794. paths.data(), &numMode, modes.data(),
  795. nullptr) == ERROR_SUCCESS) {
  796. paths.resize(numPath);
  797. for (size_t i = 0; i < numPath; ++i) {
  798. const DISPLAYCONFIG_PATH_INFO &path = paths[i];
  799. DISPLAYCONFIG_SOURCE_DEVICE_NAME
  800. source;
  801. source.header.type =
  802. DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
  803. source.header.size = sizeof(source);
  804. source.header.adapterId =
  805. path.sourceInfo.adapterId;
  806. source.header.id = path.sourceInfo.id;
  807. if (DisplayConfigGetDeviceInfo(
  808. &source.header) == ERROR_SUCCESS &&
  809. wcscmp(info.szDevice,
  810. source.viewGdiDeviceName) == 0) {
  811. target.header.type =
  812. DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
  813. target.header.size = sizeof(target);
  814. target.header.adapterId =
  815. path.sourceInfo.adapterId;
  816. target.header.id = path.targetInfo.id;
  817. found = DisplayConfigGetDeviceInfo(
  818. &target.header) ==
  819. ERROR_SUCCESS;
  820. break;
  821. }
  822. }
  823. }
  824. }
  825. return found;
  826. }
  827. static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter)
  828. {
  829. UINT i;
  830. ComPtr<IDXGIOutput> output;
  831. for (i = 0; adapter->EnumOutputs(i, &output) == S_OK; ++i) {
  832. DXGI_OUTPUT_DESC desc;
  833. if (FAILED(output->GetDesc(&desc)))
  834. continue;
  835. unsigned refresh = 0;
  836. bool target_found = false;
  837. DISPLAYCONFIG_TARGET_DEVICE_NAME target;
  838. MONITORINFOEX info;
  839. info.cbSize = sizeof(info);
  840. if (GetMonitorInfo(desc.Monitor, &info)) {
  841. target_found = GetMonitorTarget(info, target);
  842. DEVMODE mode;
  843. mode.dmSize = sizeof(mode);
  844. mode.dmDriverExtra = 0;
  845. if (EnumDisplaySettings(info.szDevice,
  846. ENUM_CURRENT_SETTINGS, &mode)) {
  847. refresh = mode.dmDisplayFrequency;
  848. }
  849. }
  850. if (!target_found) {
  851. target.monitorFriendlyDeviceName[0] = 0;
  852. }
  853. const RECT &rect = desc.DesktopCoordinates;
  854. blog(LOG_INFO,
  855. "\t output %u: "
  856. "pos={%d, %d}, "
  857. "size={%d, %d}, "
  858. "attached=%s, "
  859. "refresh=%u, "
  860. "name=%ls",
  861. i, rect.left, rect.top, rect.right - rect.left,
  862. rect.bottom - rect.top,
  863. desc.AttachedToDesktop ? "true" : "false", refresh,
  864. target.monitorFriendlyDeviceName);
  865. }
  866. }
  867. static inline void LogD3DAdapters()
  868. {
  869. ComPtr<IDXGIFactory1> factory;
  870. ComPtr<IDXGIAdapter1> adapter;
  871. HRESULT hr;
  872. UINT i;
  873. blog(LOG_INFO, "Available Video Adapters: ");
  874. IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  875. : __uuidof(IDXGIFactory1);
  876. hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  877. if (FAILED(hr))
  878. throw HRError("Failed to create DXGIFactory", hr);
  879. for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  880. DXGI_ADAPTER_DESC desc;
  881. char name[512] = "";
  882. hr = adapter->GetDesc(&desc);
  883. if (FAILED(hr))
  884. continue;
  885. /* ignore Microsoft's 'basic' renderer' */
  886. if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
  887. continue;
  888. os_wcs_to_utf8(desc.Description, 0, name, sizeof(name));
  889. blog(LOG_INFO, "\tAdapter %u: %s", i, name);
  890. blog(LOG_INFO, "\t Dedicated VRAM: %u",
  891. desc.DedicatedVideoMemory);
  892. blog(LOG_INFO, "\t Shared VRAM: %u",
  893. desc.SharedSystemMemory);
  894. blog(LOG_INFO, "\t PCI ID: %x:%x", desc.VendorId,
  895. desc.DeviceId);
  896. /* driver version */
  897. LARGE_INTEGER umd;
  898. hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice),
  899. &umd);
  900. if (SUCCEEDED(hr)) {
  901. const uint64_t version = umd.QuadPart;
  902. const uint16_t aa = (version >> 48) & 0xffff;
  903. const uint16_t bb = (version >> 32) & 0xffff;
  904. const uint16_t ccccc = (version >> 16) & 0xffff;
  905. const uint16_t ddddd = version & 0xffff;
  906. blog(LOG_INFO,
  907. "\t Driver Version: %" PRIu16 ".%" PRIu16
  908. ".%" PRIu16 ".%" PRIu16,
  909. aa, bb, ccccc, ddddd);
  910. } else {
  911. blog(LOG_INFO, "\t Driver Version: Unknown (0x%X)",
  912. (unsigned)hr);
  913. }
  914. LogAdapterMonitors(adapter);
  915. }
  916. }
  917. int device_create(gs_device_t **p_device, uint32_t adapter)
  918. {
  919. gs_device *device = NULL;
  920. int errorcode = GS_SUCCESS;
  921. try {
  922. blog(LOG_INFO, "---------------------------------");
  923. blog(LOG_INFO, "Initializing D3D11...");
  924. LogD3DAdapters();
  925. device = new gs_device(adapter);
  926. } catch (const UnsupportedHWError &error) {
  927. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  928. error.hr);
  929. errorcode = GS_ERROR_NOT_SUPPORTED;
  930. } catch (const HRError &error) {
  931. blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str,
  932. error.hr);
  933. errorcode = GS_ERROR_FAIL;
  934. }
  935. *p_device = device;
  936. return errorcode;
  937. }
  938. void device_destroy(gs_device_t *device)
  939. {
  940. delete device;
  941. }
  942. void device_enter_context(gs_device_t *device)
  943. {
  944. /* does nothing */
  945. UNUSED_PARAMETER(device);
  946. }
  947. void device_leave_context(gs_device_t *device)
  948. {
  949. /* does nothing */
  950. UNUSED_PARAMETER(device);
  951. }
  952. void *device_get_device_obj(gs_device_t *device)
  953. {
  954. return (void *)device->device.Get();
  955. }
  956. gs_swapchain_t *device_swapchain_create(gs_device_t *device,
  957. const struct gs_init_data *data)
  958. {
  959. gs_swap_chain *swap = NULL;
  960. try {
  961. swap = new gs_swap_chain(device, data);
  962. } catch (const HRError &error) {
  963. blog(LOG_ERROR, "device_swapchain_create (D3D11): %s (%08lX)",
  964. error.str, error.hr);
  965. LogD3D11ErrorDetails(error, device);
  966. }
  967. return swap;
  968. }
  969. void device_resize(gs_device_t *device, uint32_t cx, uint32_t cy)
  970. {
  971. if (!device->curSwapChain) {
  972. blog(LOG_WARNING, "device_resize (D3D11): No active swap");
  973. return;
  974. }
  975. try {
  976. ID3D11RenderTargetView *renderView = NULL;
  977. device->context->OMSetRenderTargets(1, &renderView, NULL);
  978. device->curSwapChain->Resize(cx, cy);
  979. device->curFramebufferInvalidate = true;
  980. } catch (const HRError &error) {
  981. blog(LOG_ERROR, "device_resize (D3D11): %s (%08lX)", error.str,
  982. error.hr);
  983. LogD3D11ErrorDetails(error, device);
  984. }
  985. }
  986. void device_get_size(const gs_device_t *device, uint32_t *cx, uint32_t *cy)
  987. {
  988. if (device->curSwapChain) {
  989. *cx = device->curSwapChain->target.width;
  990. *cy = device->curSwapChain->target.height;
  991. } else {
  992. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  993. *cx = 0;
  994. *cy = 0;
  995. }
  996. }
  997. uint32_t device_get_width(const gs_device_t *device)
  998. {
  999. if (device->curSwapChain) {
  1000. return device->curSwapChain->target.width;
  1001. } else {
  1002. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  1003. return 0;
  1004. }
  1005. }
  1006. uint32_t device_get_height(const gs_device_t *device)
  1007. {
  1008. if (device->curSwapChain) {
  1009. return device->curSwapChain->target.height;
  1010. } else {
  1011. blog(LOG_ERROR, "device_get_size (D3D11): no active swap");
  1012. return 0;
  1013. }
  1014. }
  1015. gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width,
  1016. uint32_t height,
  1017. enum gs_color_format color_format,
  1018. uint32_t levels, const uint8_t **data,
  1019. uint32_t flags)
  1020. {
  1021. gs_texture *texture = NULL;
  1022. try {
  1023. texture = new gs_texture_2d(device, width, height, color_format,
  1024. levels, data, flags, GS_TEXTURE_2D,
  1025. false);
  1026. } catch (const HRError &error) {
  1027. blog(LOG_ERROR, "device_texture_create (D3D11): %s (%08lX)",
  1028. error.str, error.hr);
  1029. LogD3D11ErrorDetails(error, device);
  1030. } catch (const char *error) {
  1031. blog(LOG_ERROR, "device_texture_create (D3D11): %s", error);
  1032. }
  1033. return texture;
  1034. }
  1035. gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size,
  1036. enum gs_color_format color_format,
  1037. uint32_t levels, const uint8_t **data,
  1038. uint32_t flags)
  1039. {
  1040. gs_texture *texture = NULL;
  1041. try {
  1042. texture = new gs_texture_2d(device, size, size, color_format,
  1043. levels, data, flags,
  1044. GS_TEXTURE_CUBE, false);
  1045. } catch (const HRError &error) {
  1046. blog(LOG_ERROR,
  1047. "device_cubetexture_create (D3D11): %s "
  1048. "(%08lX)",
  1049. error.str, error.hr);
  1050. LogD3D11ErrorDetails(error, device);
  1051. } catch (const char *error) {
  1052. blog(LOG_ERROR, "device_cubetexture_create (D3D11): %s", error);
  1053. }
  1054. return texture;
  1055. }
  1056. gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width,
  1057. uint32_t height, uint32_t depth,
  1058. enum gs_color_format color_format,
  1059. uint32_t levels,
  1060. const uint8_t *const *data,
  1061. uint32_t flags)
  1062. {
  1063. gs_texture *texture = NULL;
  1064. try {
  1065. texture = new gs_texture_3d(device, width, height, depth,
  1066. color_format, levels, data, flags);
  1067. } catch (const HRError &error) {
  1068. blog(LOG_ERROR, "device_voltexture_create (D3D11): %s (%08lX)",
  1069. error.str, error.hr);
  1070. LogD3D11ErrorDetails(error, device);
  1071. } catch (const char *error) {
  1072. blog(LOG_ERROR, "device_voltexture_create (D3D11): %s", error);
  1073. }
  1074. return texture;
  1075. }
  1076. gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width,
  1077. uint32_t height,
  1078. enum gs_zstencil_format format)
  1079. {
  1080. gs_zstencil_buffer *zstencil = NULL;
  1081. try {
  1082. zstencil =
  1083. new gs_zstencil_buffer(device, width, height, format);
  1084. } catch (const HRError &error) {
  1085. blog(LOG_ERROR, "device_zstencil_create (D3D11): %s (%08lX)",
  1086. error.str, error.hr);
  1087. LogD3D11ErrorDetails(error, device);
  1088. }
  1089. return zstencil;
  1090. }
  1091. gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width,
  1092. uint32_t height,
  1093. enum gs_color_format color_format)
  1094. {
  1095. gs_stage_surface *surf = NULL;
  1096. try {
  1097. surf = new gs_stage_surface(device, width, height,
  1098. color_format);
  1099. } catch (const HRError &error) {
  1100. blog(LOG_ERROR,
  1101. "device_stagesurface_create (D3D11): %s "
  1102. "(%08lX)",
  1103. error.str, error.hr);
  1104. LogD3D11ErrorDetails(error, device);
  1105. }
  1106. return surf;
  1107. }
  1108. gs_samplerstate_t *
  1109. device_samplerstate_create(gs_device_t *device,
  1110. const struct gs_sampler_info *info)
  1111. {
  1112. gs_sampler_state *ss = NULL;
  1113. try {
  1114. ss = new gs_sampler_state(device, info);
  1115. } catch (const HRError &error) {
  1116. blog(LOG_ERROR,
  1117. "device_samplerstate_create (D3D11): %s "
  1118. "(%08lX)",
  1119. error.str, error.hr);
  1120. LogD3D11ErrorDetails(error, device);
  1121. }
  1122. return ss;
  1123. }
  1124. gs_shader_t *device_vertexshader_create(gs_device_t *device,
  1125. const char *shader_string,
  1126. const char *file, char **error_string)
  1127. {
  1128. gs_vertex_shader *shader = NULL;
  1129. try {
  1130. shader = new gs_vertex_shader(device, file, shader_string);
  1131. } catch (const HRError &error) {
  1132. blog(LOG_ERROR,
  1133. "device_vertexshader_create (D3D11): %s "
  1134. "(%08lX)",
  1135. error.str, error.hr);
  1136. LogD3D11ErrorDetails(error, device);
  1137. } catch (const ShaderError &error) {
  1138. const char *buf =
  1139. (const char *)error.errors->GetBufferPointer();
  1140. if (error_string)
  1141. *error_string = bstrdup(buf);
  1142. blog(LOG_ERROR,
  1143. "device_vertexshader_create (D3D11): "
  1144. "Compile warnings/errors for %s:\n%s",
  1145. file, buf);
  1146. } catch (const char *error) {
  1147. blog(LOG_ERROR, "device_vertexshader_create (D3D11): %s",
  1148. error);
  1149. }
  1150. return shader;
  1151. }
  1152. gs_shader_t *device_pixelshader_create(gs_device_t *device,
  1153. const char *shader_string,
  1154. const char *file, char **error_string)
  1155. {
  1156. gs_pixel_shader *shader = NULL;
  1157. try {
  1158. shader = new gs_pixel_shader(device, file, shader_string);
  1159. } catch (const HRError &error) {
  1160. blog(LOG_ERROR,
  1161. "device_pixelshader_create (D3D11): %s "
  1162. "(%08lX)",
  1163. error.str, error.hr);
  1164. LogD3D11ErrorDetails(error, device);
  1165. } catch (const ShaderError &error) {
  1166. const char *buf =
  1167. (const char *)error.errors->GetBufferPointer();
  1168. if (error_string)
  1169. *error_string = bstrdup(buf);
  1170. blog(LOG_ERROR,
  1171. "device_pixelshader_create (D3D11): "
  1172. "Compiler warnings/errors for %s:\n%s",
  1173. file, buf);
  1174. } catch (const char *error) {
  1175. blog(LOG_ERROR, "device_pixelshader_create (D3D11): %s", error);
  1176. }
  1177. return shader;
  1178. }
  1179. gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device,
  1180. struct gs_vb_data *data,
  1181. uint32_t flags)
  1182. {
  1183. gs_vertex_buffer *buffer = NULL;
  1184. try {
  1185. buffer = new gs_vertex_buffer(device, data, flags);
  1186. } catch (const HRError &error) {
  1187. blog(LOG_ERROR,
  1188. "device_vertexbuffer_create (D3D11): %s "
  1189. "(%08lX)",
  1190. error.str, error.hr);
  1191. LogD3D11ErrorDetails(error, device);
  1192. } catch (const char *error) {
  1193. blog(LOG_ERROR, "device_vertexbuffer_create (D3D11): %s",
  1194. error);
  1195. }
  1196. return buffer;
  1197. }
  1198. gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device,
  1199. enum gs_index_type type,
  1200. void *indices, size_t num,
  1201. uint32_t flags)
  1202. {
  1203. gs_index_buffer *buffer = NULL;
  1204. try {
  1205. buffer = new gs_index_buffer(device, type, indices, num, flags);
  1206. } catch (const HRError &error) {
  1207. blog(LOG_ERROR, "device_indexbuffer_create (D3D11): %s (%08lX)",
  1208. error.str, error.hr);
  1209. LogD3D11ErrorDetails(error, device);
  1210. }
  1211. return buffer;
  1212. }
  1213. gs_timer_t *device_timer_create(gs_device_t *device)
  1214. {
  1215. gs_timer *timer = NULL;
  1216. try {
  1217. timer = new gs_timer(device);
  1218. } catch (const HRError &error) {
  1219. blog(LOG_ERROR, "device_timer_create (D3D11): %s (%08lX)",
  1220. error.str, error.hr);
  1221. LogD3D11ErrorDetails(error, device);
  1222. }
  1223. return timer;
  1224. }
  1225. gs_timer_range_t *device_timer_range_create(gs_device_t *device)
  1226. {
  1227. gs_timer_range *range = NULL;
  1228. try {
  1229. range = new gs_timer_range(device);
  1230. } catch (const HRError &error) {
  1231. blog(LOG_ERROR, "device_timer_range_create (D3D11): %s (%08lX)",
  1232. error.str, error.hr);
  1233. LogD3D11ErrorDetails(error, device);
  1234. }
  1235. return range;
  1236. }
  1237. enum gs_texture_type device_get_texture_type(const gs_texture_t *texture)
  1238. {
  1239. return texture->type;
  1240. }
  1241. void gs_device::LoadVertexBufferData()
  1242. {
  1243. if (curVertexBuffer == lastVertexBuffer &&
  1244. curVertexShader == lastVertexShader)
  1245. return;
  1246. ID3D11Buffer *buffers[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
  1247. uint32_t strides[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
  1248. uint32_t offsets[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
  1249. UINT numBuffers{};
  1250. assert(curVertexShader->NumBuffersExpected() <= _countof(buffers));
  1251. assert(curVertexShader->NumBuffersExpected() <= _countof(strides));
  1252. assert(curVertexShader->NumBuffersExpected() <= _countof(offsets));
  1253. if (curVertexBuffer && curVertexShader) {
  1254. numBuffers = curVertexBuffer->MakeBufferList(curVertexShader,
  1255. buffers, strides);
  1256. } else {
  1257. numBuffers = curVertexShader
  1258. ? curVertexShader->NumBuffersExpected()
  1259. : 0;
  1260. std::fill_n(buffers, numBuffers, nullptr);
  1261. std::fill_n(strides, numBuffers, 0);
  1262. }
  1263. std::fill_n(offsets, numBuffers, 0);
  1264. context->IASetVertexBuffers(0, numBuffers, buffers, strides, offsets);
  1265. lastVertexBuffer = curVertexBuffer;
  1266. lastVertexShader = curVertexShader;
  1267. }
  1268. void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vertbuffer)
  1269. {
  1270. if (device->curVertexBuffer == vertbuffer)
  1271. return;
  1272. device->curVertexBuffer = vertbuffer;
  1273. }
  1274. void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer)
  1275. {
  1276. DXGI_FORMAT format;
  1277. ID3D11Buffer *buffer;
  1278. if (device->curIndexBuffer == indexbuffer)
  1279. return;
  1280. if (indexbuffer) {
  1281. switch (indexbuffer->indexSize) {
  1282. case 2:
  1283. format = DXGI_FORMAT_R16_UINT;
  1284. break;
  1285. default:
  1286. case 4:
  1287. format = DXGI_FORMAT_R32_UINT;
  1288. break;
  1289. }
  1290. buffer = indexbuffer->indexBuffer;
  1291. } else {
  1292. buffer = NULL;
  1293. format = DXGI_FORMAT_R32_UINT;
  1294. }
  1295. device->curIndexBuffer = indexbuffer;
  1296. device->context->IASetIndexBuffer(buffer, format, 0);
  1297. }
  1298. static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex,
  1299. int unit,
  1300. ID3D11ShaderResourceView *view)
  1301. {
  1302. if (device->curTextures[unit] == tex)
  1303. return;
  1304. device->curTextures[unit] = tex;
  1305. device->context->PSSetShaderResources(unit, 1, &view);
  1306. }
  1307. void device_load_texture(gs_device_t *device, gs_texture_t *tex, int unit)
  1308. {
  1309. ID3D11ShaderResourceView *view;
  1310. if (tex)
  1311. view = tex->shaderRes;
  1312. else
  1313. view = NULL;
  1314. return device_load_texture_internal(device, tex, unit, view);
  1315. }
  1316. void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, int unit)
  1317. {
  1318. ID3D11ShaderResourceView *view;
  1319. if (tex)
  1320. view = tex->shaderResLinear;
  1321. else
  1322. view = NULL;
  1323. return device_load_texture_internal(device, tex, unit, view);
  1324. }
  1325. void device_load_samplerstate(gs_device_t *device,
  1326. gs_samplerstate_t *samplerstate, int unit)
  1327. {
  1328. ID3D11SamplerState *state = NULL;
  1329. if (device->curSamplers[unit] == samplerstate)
  1330. return;
  1331. if (samplerstate)
  1332. state = samplerstate->state;
  1333. device->curSamplers[unit] = samplerstate;
  1334. device->context->PSSetSamplers(unit, 1, &state);
  1335. }
  1336. void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader)
  1337. {
  1338. ID3D11VertexShader *shader = NULL;
  1339. ID3D11InputLayout *layout = NULL;
  1340. ID3D11Buffer *constants = NULL;
  1341. if (device->curVertexShader == vertshader)
  1342. return;
  1343. gs_vertex_shader *vs = static_cast<gs_vertex_shader *>(vertshader);
  1344. if (vertshader) {
  1345. if (vertshader->type != GS_SHADER_VERTEX) {
  1346. blog(LOG_ERROR, "device_load_vertexshader (D3D11): "
  1347. "Specified shader is not a vertex "
  1348. "shader");
  1349. return;
  1350. }
  1351. shader = vs->shader;
  1352. layout = vs->layout;
  1353. constants = vs->constants;
  1354. }
  1355. device->curVertexShader = vs;
  1356. device->context->VSSetShader(shader, NULL, 0);
  1357. device->context->IASetInputLayout(layout);
  1358. device->context->VSSetConstantBuffers(0, 1, &constants);
  1359. }
  1360. static inline void clear_textures(gs_device_t *device)
  1361. {
  1362. ID3D11ShaderResourceView *views[GS_MAX_TEXTURES];
  1363. memset(views, 0, sizeof(views));
  1364. memset(device->curTextures, 0, sizeof(device->curTextures));
  1365. device->context->PSSetShaderResources(0, GS_MAX_TEXTURES, views);
  1366. }
  1367. void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader)
  1368. {
  1369. ID3D11PixelShader *shader = NULL;
  1370. ID3D11Buffer *constants = NULL;
  1371. ID3D11SamplerState *states[GS_MAX_TEXTURES];
  1372. if (device->curPixelShader == pixelshader)
  1373. return;
  1374. gs_pixel_shader *ps = static_cast<gs_pixel_shader *>(pixelshader);
  1375. if (pixelshader) {
  1376. if (pixelshader->type != GS_SHADER_PIXEL) {
  1377. blog(LOG_ERROR, "device_load_pixelshader (D3D11): "
  1378. "Specified shader is not a pixel "
  1379. "shader");
  1380. return;
  1381. }
  1382. shader = ps->shader;
  1383. constants = ps->constants;
  1384. ps->GetSamplerStates(states);
  1385. } else {
  1386. memset(states, 0, sizeof(states));
  1387. }
  1388. clear_textures(device);
  1389. device->curPixelShader = ps;
  1390. device->context->PSSetShader(shader, NULL, 0);
  1391. device->context->PSSetConstantBuffers(0, 1, &constants);
  1392. device->context->PSSetSamplers(0, GS_MAX_TEXTURES, states);
  1393. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  1394. if (device->curSamplers[i] &&
  1395. device->curSamplers[i]->state != states[i])
  1396. device->curSamplers[i] = nullptr;
  1397. }
  1398. void device_load_default_samplerstate(gs_device_t *device, bool b_3d, int unit)
  1399. {
  1400. /* TODO */
  1401. UNUSED_PARAMETER(device);
  1402. UNUSED_PARAMETER(b_3d);
  1403. UNUSED_PARAMETER(unit);
  1404. }
  1405. gs_shader_t *device_get_vertex_shader(const gs_device_t *device)
  1406. {
  1407. return device->curVertexShader;
  1408. }
  1409. gs_shader_t *device_get_pixel_shader(const gs_device_t *device)
  1410. {
  1411. return device->curPixelShader;
  1412. }
  1413. gs_texture_t *device_get_render_target(const gs_device_t *device)
  1414. {
  1415. if (device->curRenderTarget == &device->curSwapChain->target)
  1416. return NULL;
  1417. return device->curRenderTarget;
  1418. }
  1419. gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device)
  1420. {
  1421. if (device->curZStencilBuffer == &device->curSwapChain->zs)
  1422. return NULL;
  1423. return device->curZStencilBuffer;
  1424. }
  1425. void device_set_render_target(gs_device_t *device, gs_texture_t *tex,
  1426. gs_zstencil_t *zstencil)
  1427. {
  1428. if (device->curSwapChain) {
  1429. if (!tex)
  1430. tex = &device->curSwapChain->target;
  1431. if (!zstencil)
  1432. zstencil = &device->curSwapChain->zs;
  1433. }
  1434. if (device->curRenderTarget == tex &&
  1435. device->curZStencilBuffer == zstencil)
  1436. return;
  1437. if (tex && tex->type != GS_TEXTURE_2D) {
  1438. blog(LOG_ERROR,
  1439. "device_set_render_target (D3D11): texture is not a 2D texture");
  1440. return;
  1441. }
  1442. gs_texture_2d *const tex2d = static_cast<gs_texture_2d *>(tex);
  1443. if (device->curRenderTarget != tex2d || device->curRenderSide != 0 ||
  1444. device->curZStencilBuffer != zstencil) {
  1445. device->curRenderTarget = tex2d;
  1446. device->curRenderSide = 0;
  1447. device->curZStencilBuffer = zstencil;
  1448. device->curFramebufferInvalidate = true;
  1449. }
  1450. }
  1451. void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex,
  1452. int side, gs_zstencil_t *zstencil)
  1453. {
  1454. if (device->curSwapChain) {
  1455. if (!tex) {
  1456. tex = &device->curSwapChain->target;
  1457. side = 0;
  1458. }
  1459. if (!zstencil)
  1460. zstencil = &device->curSwapChain->zs;
  1461. }
  1462. if (device->curRenderTarget == tex && device->curRenderSide == side &&
  1463. device->curZStencilBuffer == zstencil)
  1464. return;
  1465. if (tex->type != GS_TEXTURE_CUBE) {
  1466. blog(LOG_ERROR, "device_set_cube_render_target (D3D11): "
  1467. "texture is not a cube texture");
  1468. return;
  1469. }
  1470. gs_texture_2d *const tex2d = static_cast<gs_texture_2d *>(tex);
  1471. if (device->curRenderTarget != tex2d || device->curRenderSide != side ||
  1472. device->curZStencilBuffer != zstencil) {
  1473. device->curRenderTarget = tex2d;
  1474. device->curRenderSide = side;
  1475. device->curZStencilBuffer = zstencil;
  1476. device->curFramebufferInvalidate = true;
  1477. }
  1478. }
  1479. void device_enable_framebuffer_srgb(gs_device_t *device, bool enable)
  1480. {
  1481. if (device->curFramebufferSrgb != enable) {
  1482. device->curFramebufferSrgb = enable;
  1483. device->curFramebufferInvalidate = true;
  1484. }
  1485. }
  1486. bool device_framebuffer_srgb_enabled(gs_device_t *device)
  1487. {
  1488. return device->curFramebufferSrgb;
  1489. }
  1490. inline void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x,
  1491. uint32_t dst_y, gs_texture_t *src,
  1492. uint32_t src_x, uint32_t src_y, uint32_t src_w,
  1493. uint32_t src_h)
  1494. {
  1495. if (src->type != GS_TEXTURE_2D)
  1496. throw "Source texture must be a 2D texture";
  1497. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(src);
  1498. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1499. src_w == 0 && src_h == 0) {
  1500. context->CopyResource(dst, tex2d->texture);
  1501. } else {
  1502. D3D11_BOX sbox;
  1503. sbox.left = src_x;
  1504. if (src_w > 0)
  1505. sbox.right = src_x + src_w;
  1506. else
  1507. sbox.right = tex2d->width - 1;
  1508. sbox.top = src_y;
  1509. if (src_h > 0)
  1510. sbox.bottom = src_y + src_h;
  1511. else
  1512. sbox.bottom = tex2d->height - 1;
  1513. sbox.front = 0;
  1514. sbox.back = 1;
  1515. context->CopySubresourceRegion(dst, 0, dst_x, dst_y, 0,
  1516. tex2d->texture, 0, &sbox);
  1517. }
  1518. }
  1519. static DXGI_FORMAT get_copy_compare_format(gs_color_format format)
  1520. {
  1521. switch (format) {
  1522. case GS_RGBA_UNORM:
  1523. return DXGI_FORMAT_R8G8B8A8_TYPELESS;
  1524. case GS_BGRX_UNORM:
  1525. return DXGI_FORMAT_B8G8R8X8_TYPELESS;
  1526. case GS_BGRA_UNORM:
  1527. return DXGI_FORMAT_B8G8R8A8_TYPELESS;
  1528. default:
  1529. return ConvertGSTextureFormatResource(format);
  1530. }
  1531. }
  1532. void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst,
  1533. uint32_t dst_x, uint32_t dst_y,
  1534. gs_texture_t *src, uint32_t src_x,
  1535. uint32_t src_y, uint32_t src_w, uint32_t src_h)
  1536. {
  1537. try {
  1538. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1539. gs_texture_2d *dst2d = static_cast<gs_texture_2d *>(dst);
  1540. if (!src)
  1541. throw "Source texture is NULL";
  1542. if (!dst)
  1543. throw "Destination texture is NULL";
  1544. if (src->type != GS_TEXTURE_2D || dst->type != GS_TEXTURE_2D)
  1545. throw "Source and destination textures must be a 2D "
  1546. "textures";
  1547. if (get_copy_compare_format(dst->format) !=
  1548. get_copy_compare_format(src->format))
  1549. throw "Source and destination formats do not match";
  1550. /* apparently casting to the same type that the variable
  1551. * already exists as is supposed to prevent some warning
  1552. * when used with the conditional operator? */
  1553. uint32_t copyWidth = (uint32_t)src_w ? (uint32_t)src_w
  1554. : (src2d->width - src_x);
  1555. uint32_t copyHeight = (uint32_t)src_h ? (uint32_t)src_h
  1556. : (src2d->height - src_y);
  1557. uint32_t dstWidth = dst2d->width - dst_x;
  1558. uint32_t dstHeight = dst2d->height - dst_y;
  1559. if (dstWidth < copyWidth || dstHeight < copyHeight)
  1560. throw "Destination texture region is not big "
  1561. "enough to hold the source region";
  1562. if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 &&
  1563. src_w == 0 && src_h == 0) {
  1564. copyWidth = 0;
  1565. copyHeight = 0;
  1566. }
  1567. device->CopyTex(dst2d->texture, dst_x, dst_y, src, src_x, src_y,
  1568. copyWidth, copyHeight);
  1569. } catch (const char *error) {
  1570. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1571. }
  1572. }
  1573. void device_copy_texture(gs_device_t *device, gs_texture_t *dst,
  1574. gs_texture_t *src)
  1575. {
  1576. device_copy_texture_region(device, dst, 0, 0, src, 0, 0, 0, 0);
  1577. }
  1578. void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst,
  1579. gs_texture_t *src)
  1580. {
  1581. try {
  1582. gs_texture_2d *src2d = static_cast<gs_texture_2d *>(src);
  1583. if (!src)
  1584. throw "Source texture is NULL";
  1585. if (src->type != GS_TEXTURE_2D)
  1586. throw "Source texture must be a 2D texture";
  1587. if (!dst)
  1588. throw "Destination surface is NULL";
  1589. if (dst->format != GS_UNKNOWN && dst->format != src->format)
  1590. throw "Source and destination formats do not match";
  1591. if (dst->width != src2d->width || dst->height != src2d->height)
  1592. throw "Source and destination must have the same "
  1593. "dimensions";
  1594. device->CopyTex(dst->texture, 0, 0, src, 0, 0, 0, 0);
  1595. } catch (const char *error) {
  1596. blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error);
  1597. }
  1598. }
  1599. extern "C" void reset_duplicators(void);
  1600. void device_begin_frame(gs_device_t *device)
  1601. {
  1602. /* does nothing in D3D11 */
  1603. UNUSED_PARAMETER(device);
  1604. reset_duplicators();
  1605. }
  1606. void device_begin_scene(gs_device_t *device)
  1607. {
  1608. clear_textures(device);
  1609. }
  1610. void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode,
  1611. uint32_t start_vert, uint32_t num_verts)
  1612. {
  1613. try {
  1614. if (!device->curVertexShader)
  1615. throw "No vertex shader specified";
  1616. if (!device->curPixelShader)
  1617. throw "No pixel shader specified";
  1618. if (!device->curVertexBuffer && (num_verts == 0))
  1619. throw "No vertex buffer specified";
  1620. if (!device->curSwapChain && !device->curRenderTarget)
  1621. throw "No render target or swap chain to render to";
  1622. device->FlushOutputViews();
  1623. gs_effect_t *effect = gs_get_effect();
  1624. if (effect)
  1625. gs_effect_update_params(effect);
  1626. device->LoadVertexBufferData();
  1627. device->UpdateBlendState();
  1628. device->UpdateRasterState();
  1629. device->UpdateZStencilState();
  1630. device->UpdateViewProjMatrix();
  1631. device->curVertexShader->UploadParams();
  1632. device->curPixelShader->UploadParams();
  1633. } catch (const char *error) {
  1634. blog(LOG_ERROR, "device_draw (D3D11): %s", error);
  1635. return;
  1636. } catch (const HRError &error) {
  1637. blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str,
  1638. error.hr);
  1639. LogD3D11ErrorDetails(error, device);
  1640. return;
  1641. }
  1642. D3D11_PRIMITIVE_TOPOLOGY newTopology = ConvertGSTopology(draw_mode);
  1643. if (device->curToplogy != newTopology) {
  1644. device->context->IASetPrimitiveTopology(newTopology);
  1645. device->curToplogy = newTopology;
  1646. }
  1647. if (device->curIndexBuffer) {
  1648. if (num_verts == 0)
  1649. num_verts = (uint32_t)device->curIndexBuffer->num;
  1650. device->context->DrawIndexed(num_verts, start_vert, 0);
  1651. } else {
  1652. if (num_verts == 0)
  1653. num_verts = (uint32_t)device->curVertexBuffer->numVerts;
  1654. device->context->Draw(num_verts, start_vert);
  1655. }
  1656. }
  1657. void device_end_scene(gs_device_t *device)
  1658. {
  1659. /* does nothing in D3D11 */
  1660. UNUSED_PARAMETER(device);
  1661. }
  1662. void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain)
  1663. {
  1664. gs_texture_t *target = device->curRenderTarget;
  1665. gs_zstencil_t *zs = device->curZStencilBuffer;
  1666. bool is_cube =
  1667. device->curRenderTarget
  1668. ? (device->curRenderTarget->type == GS_TEXTURE_CUBE)
  1669. : false;
  1670. if (device->curSwapChain) {
  1671. if (target == &device->curSwapChain->target)
  1672. target = NULL;
  1673. if (zs == &device->curSwapChain->zs)
  1674. zs = NULL;
  1675. }
  1676. device->curSwapChain = swapchain;
  1677. if (is_cube)
  1678. device_set_cube_render_target(device, target,
  1679. device->curRenderSide, zs);
  1680. else
  1681. device_set_render_target(device, target, zs);
  1682. }
  1683. void device_clear(gs_device_t *device, uint32_t clear_flags,
  1684. const struct vec4 *color, float depth, uint8_t stencil)
  1685. {
  1686. int side = device->curRenderSide;
  1687. if ((clear_flags & GS_CLEAR_COLOR) != 0 && device->curRenderTarget)
  1688. device->context->ClearRenderTargetView(
  1689. device->curRenderTarget->renderTarget[side],
  1690. color->ptr);
  1691. if (device->curZStencilBuffer) {
  1692. uint32_t flags = 0;
  1693. if ((clear_flags & GS_CLEAR_DEPTH) != 0)
  1694. flags |= D3D11_CLEAR_DEPTH;
  1695. if ((clear_flags & GS_CLEAR_STENCIL) != 0)
  1696. flags |= D3D11_CLEAR_STENCIL;
  1697. if (flags && device->curZStencilBuffer->view)
  1698. device->context->ClearDepthStencilView(
  1699. device->curZStencilBuffer->view, flags, depth,
  1700. stencil);
  1701. }
  1702. }
  1703. void device_present(gs_device_t *device)
  1704. {
  1705. gs_swap_chain *const curSwapChain = device->curSwapChain;
  1706. if (curSwapChain) {
  1707. const HRESULT hr = curSwapChain->swap->Present(
  1708. 0, curSwapChain->presentFlags);
  1709. if (hr == DXGI_ERROR_DEVICE_REMOVED ||
  1710. hr == DXGI_ERROR_DEVICE_RESET) {
  1711. device->RebuildDevice();
  1712. }
  1713. } else {
  1714. blog(LOG_WARNING, "device_present (D3D11): No active swap");
  1715. }
  1716. }
  1717. void device_flush(gs_device_t *device)
  1718. {
  1719. device->context->Flush();
  1720. }
  1721. void device_set_cull_mode(gs_device_t *device, enum gs_cull_mode mode)
  1722. {
  1723. if (mode == device->rasterState.cullMode)
  1724. return;
  1725. device->rasterState.cullMode = mode;
  1726. device->rasterStateChanged = true;
  1727. }
  1728. enum gs_cull_mode device_get_cull_mode(const gs_device_t *device)
  1729. {
  1730. return device->rasterState.cullMode;
  1731. }
  1732. void device_enable_blending(gs_device_t *device, bool enable)
  1733. {
  1734. if (enable == device->blendState.blendEnabled)
  1735. return;
  1736. device->blendState.blendEnabled = enable;
  1737. device->blendStateChanged = true;
  1738. }
  1739. void device_enable_depth_test(gs_device_t *device, bool enable)
  1740. {
  1741. if (enable == device->zstencilState.depthEnabled)
  1742. return;
  1743. device->zstencilState.depthEnabled = enable;
  1744. device->zstencilStateChanged = true;
  1745. }
  1746. void device_enable_stencil_test(gs_device_t *device, bool enable)
  1747. {
  1748. if (enable == device->zstencilState.stencilEnabled)
  1749. return;
  1750. device->zstencilState.stencilEnabled = enable;
  1751. device->zstencilStateChanged = true;
  1752. }
  1753. void device_enable_stencil_write(gs_device_t *device, bool enable)
  1754. {
  1755. if (enable == device->zstencilState.stencilWriteEnabled)
  1756. return;
  1757. device->zstencilState.stencilWriteEnabled = enable;
  1758. device->zstencilStateChanged = true;
  1759. }
  1760. void device_enable_color(gs_device_t *device, bool red, bool green, bool blue,
  1761. bool alpha)
  1762. {
  1763. if (device->blendState.redEnabled == red &&
  1764. device->blendState.greenEnabled == green &&
  1765. device->blendState.blueEnabled == blue &&
  1766. device->blendState.alphaEnabled == alpha)
  1767. return;
  1768. device->blendState.redEnabled = red;
  1769. device->blendState.greenEnabled = green;
  1770. device->blendState.blueEnabled = blue;
  1771. device->blendState.alphaEnabled = alpha;
  1772. device->blendStateChanged = true;
  1773. }
  1774. void device_blend_function(gs_device_t *device, enum gs_blend_type src,
  1775. enum gs_blend_type dest)
  1776. {
  1777. if (device->blendState.srcFactorC == src &&
  1778. device->blendState.destFactorC == dest &&
  1779. device->blendState.srcFactorA == src &&
  1780. device->blendState.destFactorA == dest)
  1781. return;
  1782. device->blendState.srcFactorC = src;
  1783. device->blendState.destFactorC = dest;
  1784. device->blendState.srcFactorA = src;
  1785. device->blendState.destFactorA = dest;
  1786. device->blendStateChanged = true;
  1787. }
  1788. void device_blend_function_separate(gs_device_t *device,
  1789. enum gs_blend_type src_c,
  1790. enum gs_blend_type dest_c,
  1791. enum gs_blend_type src_a,
  1792. enum gs_blend_type dest_a)
  1793. {
  1794. if (device->blendState.srcFactorC == src_c &&
  1795. device->blendState.destFactorC == dest_c &&
  1796. device->blendState.srcFactorA == src_a &&
  1797. device->blendState.destFactorA == dest_a)
  1798. return;
  1799. device->blendState.srcFactorC = src_c;
  1800. device->blendState.destFactorC = dest_c;
  1801. device->blendState.srcFactorA = src_a;
  1802. device->blendState.destFactorA = dest_a;
  1803. device->blendStateChanged = true;
  1804. }
  1805. void device_depth_function(gs_device_t *device, enum gs_depth_test test)
  1806. {
  1807. if (device->zstencilState.depthFunc == test)
  1808. return;
  1809. device->zstencilState.depthFunc = test;
  1810. device->zstencilStateChanged = true;
  1811. }
  1812. static inline void update_stencilside_test(gs_device_t *device,
  1813. StencilSide &side,
  1814. gs_depth_test test)
  1815. {
  1816. if (side.test == test)
  1817. return;
  1818. side.test = test;
  1819. device->zstencilStateChanged = true;
  1820. }
  1821. void device_stencil_function(gs_device_t *device, enum gs_stencil_side side,
  1822. enum gs_depth_test test)
  1823. {
  1824. int sideVal = (int)side;
  1825. if (sideVal & GS_STENCIL_FRONT)
  1826. update_stencilside_test(
  1827. device, device->zstencilState.stencilFront, test);
  1828. if (sideVal & GS_STENCIL_BACK)
  1829. update_stencilside_test(
  1830. device, device->zstencilState.stencilBack, test);
  1831. }
  1832. static inline void update_stencilside_op(gs_device_t *device, StencilSide &side,
  1833. enum gs_stencil_op_type fail,
  1834. enum gs_stencil_op_type zfail,
  1835. enum gs_stencil_op_type zpass)
  1836. {
  1837. if (side.fail == fail && side.zfail == zfail && side.zpass == zpass)
  1838. return;
  1839. side.fail = fail;
  1840. side.zfail = zfail;
  1841. side.zpass = zpass;
  1842. device->zstencilStateChanged = true;
  1843. }
  1844. void device_stencil_op(gs_device_t *device, enum gs_stencil_side side,
  1845. enum gs_stencil_op_type fail,
  1846. enum gs_stencil_op_type zfail,
  1847. enum gs_stencil_op_type zpass)
  1848. {
  1849. int sideVal = (int)side;
  1850. if (sideVal & GS_STENCIL_FRONT)
  1851. update_stencilside_op(device,
  1852. device->zstencilState.stencilFront, fail,
  1853. zfail, zpass);
  1854. if (sideVal & GS_STENCIL_BACK)
  1855. update_stencilside_op(device, device->zstencilState.stencilBack,
  1856. fail, zfail, zpass);
  1857. }
  1858. void device_set_viewport(gs_device_t *device, int x, int y, int width,
  1859. int height)
  1860. {
  1861. D3D11_VIEWPORT vp;
  1862. memset(&vp, 0, sizeof(vp));
  1863. vp.MaxDepth = 1.0f;
  1864. vp.TopLeftX = (float)x;
  1865. vp.TopLeftY = (float)y;
  1866. vp.Width = (float)width;
  1867. vp.Height = (float)height;
  1868. device->context->RSSetViewports(1, &vp);
  1869. device->viewport.x = x;
  1870. device->viewport.y = y;
  1871. device->viewport.cx = width;
  1872. device->viewport.cy = height;
  1873. }
  1874. void device_get_viewport(const gs_device_t *device, struct gs_rect *rect)
  1875. {
  1876. memcpy(rect, &device->viewport, sizeof(gs_rect));
  1877. }
  1878. void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect)
  1879. {
  1880. D3D11_RECT d3drect;
  1881. device->rasterState.scissorEnabled = (rect != NULL);
  1882. if (rect != NULL) {
  1883. d3drect.left = rect->x;
  1884. d3drect.top = rect->y;
  1885. d3drect.right = rect->x + rect->cx;
  1886. d3drect.bottom = rect->y + rect->cy;
  1887. device->context->RSSetScissorRects(1, &d3drect);
  1888. }
  1889. device->rasterStateChanged = true;
  1890. }
  1891. void device_ortho(gs_device_t *device, float left, float right, float top,
  1892. float bottom, float zNear, float zFar)
  1893. {
  1894. matrix4 *dst = &device->curProjMatrix;
  1895. float rml = right - left;
  1896. float bmt = bottom - top;
  1897. float fmn = zFar - zNear;
  1898. vec4_zero(&dst->x);
  1899. vec4_zero(&dst->y);
  1900. vec4_zero(&dst->z);
  1901. vec4_zero(&dst->t);
  1902. dst->x.x = 2.0f / rml;
  1903. dst->t.x = (left + right) / -rml;
  1904. dst->y.y = 2.0f / -bmt;
  1905. dst->t.y = (bottom + top) / bmt;
  1906. dst->z.z = 1.0f / fmn;
  1907. dst->t.z = zNear / -fmn;
  1908. dst->t.w = 1.0f;
  1909. }
  1910. void device_frustum(gs_device_t *device, float left, float right, float top,
  1911. float bottom, float zNear, float zFar)
  1912. {
  1913. matrix4 *dst = &device->curProjMatrix;
  1914. float rml = right - left;
  1915. float bmt = bottom - top;
  1916. float fmn = zFar - zNear;
  1917. float nearx2 = 2.0f * zNear;
  1918. vec4_zero(&dst->x);
  1919. vec4_zero(&dst->y);
  1920. vec4_zero(&dst->z);
  1921. vec4_zero(&dst->t);
  1922. dst->x.x = nearx2 / rml;
  1923. dst->z.x = (left + right) / -rml;
  1924. dst->y.y = nearx2 / -bmt;
  1925. dst->z.y = (bottom + top) / bmt;
  1926. dst->z.z = zFar / fmn;
  1927. dst->t.z = (zNear * zFar) / -fmn;
  1928. dst->z.w = 1.0f;
  1929. }
  1930. void device_projection_push(gs_device_t *device)
  1931. {
  1932. mat4float mat;
  1933. memcpy(&mat, &device->curProjMatrix, sizeof(matrix4));
  1934. device->projStack.push_back(mat);
  1935. }
  1936. void device_projection_pop(gs_device_t *device)
  1937. {
  1938. if (device->projStack.empty())
  1939. return;
  1940. const mat4float &mat = device->projStack.back();
  1941. memcpy(&device->curProjMatrix, &mat, sizeof(matrix4));
  1942. device->projStack.pop_back();
  1943. }
  1944. void gs_swapchain_destroy(gs_swapchain_t *swapchain)
  1945. {
  1946. if (swapchain->device->curSwapChain == swapchain)
  1947. device_load_swapchain(swapchain->device, nullptr);
  1948. delete swapchain;
  1949. }
  1950. void gs_texture_destroy(gs_texture_t *tex)
  1951. {
  1952. delete tex;
  1953. }
  1954. uint32_t gs_texture_get_width(const gs_texture_t *tex)
  1955. {
  1956. if (tex->type != GS_TEXTURE_2D)
  1957. return 0;
  1958. return static_cast<const gs_texture_2d *>(tex)->width;
  1959. }
  1960. uint32_t gs_texture_get_height(const gs_texture_t *tex)
  1961. {
  1962. if (tex->type != GS_TEXTURE_2D)
  1963. return 0;
  1964. return static_cast<const gs_texture_2d *>(tex)->height;
  1965. }
  1966. enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex)
  1967. {
  1968. if (tex->type != GS_TEXTURE_2D)
  1969. return GS_UNKNOWN;
  1970. return static_cast<const gs_texture_2d *>(tex)->format;
  1971. }
  1972. bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize)
  1973. {
  1974. HRESULT hr;
  1975. if (tex->type != GS_TEXTURE_2D)
  1976. return false;
  1977. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1978. D3D11_MAPPED_SUBRESOURCE map;
  1979. hr = tex2d->device->context->Map(tex2d->texture, 0,
  1980. D3D11_MAP_WRITE_DISCARD, 0, &map);
  1981. if (FAILED(hr))
  1982. return false;
  1983. *ptr = (uint8_t *)map.pData;
  1984. *linesize = map.RowPitch;
  1985. return true;
  1986. }
  1987. void gs_texture_unmap(gs_texture_t *tex)
  1988. {
  1989. if (tex->type != GS_TEXTURE_2D)
  1990. return;
  1991. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1992. tex2d->device->context->Unmap(tex2d->texture, 0);
  1993. }
  1994. void *gs_texture_get_obj(gs_texture_t *tex)
  1995. {
  1996. if (tex->type != GS_TEXTURE_2D)
  1997. return nullptr;
  1998. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  1999. return tex2d->texture.Get();
  2000. }
  2001. void gs_cubetexture_destroy(gs_texture_t *cubetex)
  2002. {
  2003. delete cubetex;
  2004. }
  2005. uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex)
  2006. {
  2007. if (cubetex->type != GS_TEXTURE_CUBE)
  2008. return 0;
  2009. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  2010. return tex->width;
  2011. }
  2012. enum gs_color_format
  2013. gs_cubetexture_get_color_format(const gs_texture_t *cubetex)
  2014. {
  2015. if (cubetex->type != GS_TEXTURE_CUBE)
  2016. return GS_UNKNOWN;
  2017. const gs_texture_2d *tex = static_cast<const gs_texture_2d *>(cubetex);
  2018. return tex->format;
  2019. }
  2020. void gs_voltexture_destroy(gs_texture_t *voltex)
  2021. {
  2022. delete voltex;
  2023. }
  2024. uint32_t gs_voltexture_get_width(const gs_texture_t *voltex)
  2025. {
  2026. /* TODO */
  2027. UNUSED_PARAMETER(voltex);
  2028. return 0;
  2029. }
  2030. uint32_t gs_voltexture_get_height(const gs_texture_t *voltex)
  2031. {
  2032. /* TODO */
  2033. UNUSED_PARAMETER(voltex);
  2034. return 0;
  2035. }
  2036. uint32_t gs_voltexture_get_depth(const gs_texture_t *voltex)
  2037. {
  2038. /* TODO */
  2039. UNUSED_PARAMETER(voltex);
  2040. return 0;
  2041. }
  2042. enum gs_color_format gs_voltexture_get_color_format(const gs_texture_t *voltex)
  2043. {
  2044. /* TODO */
  2045. UNUSED_PARAMETER(voltex);
  2046. return GS_UNKNOWN;
  2047. }
  2048. void gs_stagesurface_destroy(gs_stagesurf_t *stagesurf)
  2049. {
  2050. delete stagesurf;
  2051. }
  2052. uint32_t gs_stagesurface_get_width(const gs_stagesurf_t *stagesurf)
  2053. {
  2054. return stagesurf->width;
  2055. }
  2056. uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf)
  2057. {
  2058. return stagesurf->height;
  2059. }
  2060. enum gs_color_format
  2061. gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf)
  2062. {
  2063. return stagesurf->format;
  2064. }
  2065. bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data,
  2066. uint32_t *linesize)
  2067. {
  2068. D3D11_MAPPED_SUBRESOURCE map;
  2069. if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0,
  2070. D3D11_MAP_READ, 0, &map)))
  2071. return false;
  2072. *data = (uint8_t *)map.pData;
  2073. *linesize = map.RowPitch;
  2074. return true;
  2075. }
  2076. void gs_stagesurface_unmap(gs_stagesurf_t *stagesurf)
  2077. {
  2078. stagesurf->device->context->Unmap(stagesurf->texture, 0);
  2079. }
  2080. void gs_zstencil_destroy(gs_zstencil_t *zstencil)
  2081. {
  2082. delete zstencil;
  2083. }
  2084. void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate)
  2085. {
  2086. if (!samplerstate)
  2087. return;
  2088. if (samplerstate->device)
  2089. for (int i = 0; i < GS_MAX_TEXTURES; i++)
  2090. if (samplerstate->device->curSamplers[i] ==
  2091. samplerstate)
  2092. samplerstate->device->curSamplers[i] = nullptr;
  2093. delete samplerstate;
  2094. }
  2095. void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer)
  2096. {
  2097. if (vertbuffer && vertbuffer->device->lastVertexBuffer == vertbuffer)
  2098. vertbuffer->device->lastVertexBuffer = nullptr;
  2099. delete vertbuffer;
  2100. }
  2101. static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer,
  2102. const gs_vb_data *data)
  2103. {
  2104. size_t num_tex = data->num_tex < vertbuffer->uvBuffers.size()
  2105. ? data->num_tex
  2106. : vertbuffer->uvBuffers.size();
  2107. if (!vertbuffer->dynamic) {
  2108. blog(LOG_ERROR, "gs_vertexbuffer_flush: vertex buffer is "
  2109. "not dynamic");
  2110. return;
  2111. }
  2112. if (data->points)
  2113. vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points,
  2114. sizeof(vec3));
  2115. if (vertbuffer->normalBuffer && data->normals)
  2116. vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals,
  2117. sizeof(vec3));
  2118. if (vertbuffer->tangentBuffer && data->tangents)
  2119. vertbuffer->FlushBuffer(vertbuffer->tangentBuffer,
  2120. data->tangents, sizeof(vec3));
  2121. if (vertbuffer->colorBuffer && data->colors)
  2122. vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors,
  2123. sizeof(uint32_t));
  2124. for (size_t i = 0; i < num_tex; i++) {
  2125. gs_tvertarray &tv = data->tvarray[i];
  2126. vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], tv.array,
  2127. tv.width * sizeof(float));
  2128. }
  2129. }
  2130. void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer)
  2131. {
  2132. gs_vertexbuffer_flush_internal(vertbuffer, vertbuffer->vbd.data);
  2133. }
  2134. void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer,
  2135. const gs_vb_data *data)
  2136. {
  2137. gs_vertexbuffer_flush_internal(vertbuffer, data);
  2138. }
  2139. struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vertbuffer)
  2140. {
  2141. return vertbuffer->vbd.data;
  2142. }
  2143. void gs_indexbuffer_destroy(gs_indexbuffer_t *indexbuffer)
  2144. {
  2145. delete indexbuffer;
  2146. }
  2147. static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer,
  2148. const void *data)
  2149. {
  2150. HRESULT hr;
  2151. if (!indexbuffer->dynamic)
  2152. return;
  2153. D3D11_MAPPED_SUBRESOURCE map;
  2154. hr = indexbuffer->device->context->Map(
  2155. indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
  2156. if (FAILED(hr))
  2157. return;
  2158. memcpy(map.pData, data, indexbuffer->num * indexbuffer->indexSize);
  2159. indexbuffer->device->context->Unmap(indexbuffer->indexBuffer, 0);
  2160. }
  2161. void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer)
  2162. {
  2163. gs_indexbuffer_flush_internal(indexbuffer, indexbuffer->indices.data);
  2164. }
  2165. void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer,
  2166. const void *data)
  2167. {
  2168. gs_indexbuffer_flush_internal(indexbuffer, data);
  2169. }
  2170. void *gs_indexbuffer_get_data(const gs_indexbuffer_t *indexbuffer)
  2171. {
  2172. return indexbuffer->indices.data;
  2173. }
  2174. size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer)
  2175. {
  2176. return indexbuffer->num;
  2177. }
  2178. enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer)
  2179. {
  2180. return indexbuffer->type;
  2181. }
  2182. void gs_timer_destroy(gs_timer_t *timer)
  2183. {
  2184. delete timer;
  2185. }
  2186. void gs_timer_begin(gs_timer_t *timer)
  2187. {
  2188. timer->device->context->End(timer->query_begin);
  2189. }
  2190. void gs_timer_end(gs_timer_t *timer)
  2191. {
  2192. timer->device->context->End(timer->query_end);
  2193. }
  2194. bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks)
  2195. {
  2196. uint64_t begin, end;
  2197. HRESULT hr_begin, hr_end;
  2198. do {
  2199. hr_begin = timer->device->context->GetData(
  2200. timer->query_begin, &begin, sizeof(begin), 0);
  2201. } while (hr_begin == S_FALSE);
  2202. do {
  2203. hr_end = timer->device->context->GetData(timer->query_end, &end,
  2204. sizeof(end), 0);
  2205. } while (hr_end == S_FALSE);
  2206. const bool succeeded = SUCCEEDED(hr_begin) && SUCCEEDED(hr_end);
  2207. if (succeeded)
  2208. *ticks = end - begin;
  2209. return succeeded;
  2210. }
  2211. void gs_timer_range_destroy(gs_timer_range_t *range)
  2212. {
  2213. delete range;
  2214. }
  2215. void gs_timer_range_begin(gs_timer_range_t *range)
  2216. {
  2217. range->device->context->Begin(range->query_disjoint);
  2218. }
  2219. void gs_timer_range_end(gs_timer_range_t *range)
  2220. {
  2221. range->device->context->End(range->query_disjoint);
  2222. }
  2223. bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint,
  2224. uint64_t *frequency)
  2225. {
  2226. D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timestamp_disjoint;
  2227. HRESULT hr;
  2228. do {
  2229. hr = range->device->context->GetData(range->query_disjoint,
  2230. &timestamp_disjoint,
  2231. sizeof(timestamp_disjoint),
  2232. 0);
  2233. } while (hr == S_FALSE);
  2234. const bool succeeded = SUCCEEDED(hr);
  2235. if (succeeded) {
  2236. *disjoint = timestamp_disjoint.Disjoint;
  2237. *frequency = timestamp_disjoint.Frequency;
  2238. }
  2239. return succeeded;
  2240. }
  2241. gs_timer::gs_timer(gs_device_t *device) : gs_obj(device, gs_type::gs_timer)
  2242. {
  2243. Rebuild(device->device);
  2244. }
  2245. gs_timer_range::gs_timer_range(gs_device_t *device)
  2246. : gs_obj(device, gs_type::gs_timer_range)
  2247. {
  2248. Rebuild(device->device);
  2249. }
  2250. extern "C" EXPORT bool device_gdi_texture_available(void)
  2251. {
  2252. return true;
  2253. }
  2254. extern "C" EXPORT bool device_shared_texture_available(void)
  2255. {
  2256. return true;
  2257. }
  2258. extern "C" EXPORT bool device_nv12_available(gs_device_t *device)
  2259. {
  2260. return device->nv12Supported;
  2261. }
  2262. extern "C" EXPORT void device_debug_marker_begin(gs_device_t *,
  2263. const char *markername,
  2264. const float color[4])
  2265. {
  2266. D3DCOLOR bgra = D3DCOLOR_ARGB((DWORD)(255.0f * color[3]),
  2267. (DWORD)(255.0f * color[0]),
  2268. (DWORD)(255.0f * color[1]),
  2269. (DWORD)(255.0f * color[2]));
  2270. wchar_t wide[64];
  2271. os_utf8_to_wcs(markername, 0, wide, _countof(wide));
  2272. D3DPERF_BeginEvent(bgra, wide);
  2273. }
  2274. extern "C" EXPORT void device_debug_marker_end(gs_device_t *)
  2275. {
  2276. D3DPERF_EndEvent();
  2277. }
  2278. extern "C" EXPORT gs_texture_t *
  2279. device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height)
  2280. {
  2281. gs_texture *texture = nullptr;
  2282. try {
  2283. texture = new gs_texture_2d(device, width, height,
  2284. GS_BGRA_UNORM, 1, nullptr,
  2285. GS_RENDER_TARGET, GS_TEXTURE_2D,
  2286. true);
  2287. } catch (const HRError &error) {
  2288. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s (%08lX)",
  2289. error.str, error.hr);
  2290. LogD3D11ErrorDetails(error, device);
  2291. } catch (const char *error) {
  2292. blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s", error);
  2293. }
  2294. return texture;
  2295. }
  2296. static inline bool TextureGDICompatible(gs_texture_2d *tex2d, const char *func)
  2297. {
  2298. if (!tex2d->isGDICompatible) {
  2299. blog(LOG_ERROR, "%s (D3D11): Texture is not GDI compatible",
  2300. func);
  2301. return false;
  2302. }
  2303. return true;
  2304. }
  2305. extern "C" EXPORT void *gs_texture_get_dc(gs_texture_t *tex)
  2306. {
  2307. HDC hDC = nullptr;
  2308. if (tex->type != GS_TEXTURE_2D)
  2309. return nullptr;
  2310. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2311. if (!TextureGDICompatible(tex2d, "gs_texture_get_dc"))
  2312. return nullptr;
  2313. if (!tex2d->gdiSurface)
  2314. return nullptr;
  2315. tex2d->gdiSurface->GetDC(true, &hDC);
  2316. return hDC;
  2317. }
  2318. extern "C" EXPORT void gs_texture_release_dc(gs_texture_t *tex)
  2319. {
  2320. if (tex->type != GS_TEXTURE_2D)
  2321. return;
  2322. gs_texture_2d *tex2d = static_cast<gs_texture_2d *>(tex);
  2323. if (!TextureGDICompatible(tex2d, "gs_texture_release_dc"))
  2324. return;
  2325. tex2d->gdiSurface->ReleaseDC(nullptr);
  2326. }
  2327. extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device,
  2328. uint32_t handle)
  2329. {
  2330. gs_texture *texture = nullptr;
  2331. try {
  2332. texture = new gs_texture_2d(device, handle);
  2333. } catch (const HRError &error) {
  2334. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s (%08lX)",
  2335. error.str, error.hr);
  2336. LogD3D11ErrorDetails(error, device);
  2337. } catch (const char *error) {
  2338. blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s", error);
  2339. }
  2340. return texture;
  2341. }
  2342. extern "C" EXPORT uint32_t device_texture_get_shared_handle(gs_texture_t *tex)
  2343. {
  2344. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2345. if (tex->type != GS_TEXTURE_2D)
  2346. return GS_INVALID_HANDLE;
  2347. return tex2d->isShared ? tex2d->sharedHandle : GS_INVALID_HANDLE;
  2348. }
  2349. extern "C" EXPORT gs_texture_t *device_texture_wrap_obj(gs_device_t *device,
  2350. void *obj)
  2351. {
  2352. gs_texture *texture = nullptr;
  2353. try {
  2354. texture = new gs_texture_2d(device, (ID3D11Texture2D *)obj);
  2355. } catch (const HRError &error) {
  2356. blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s (%08lX)",
  2357. error.str, error.hr);
  2358. LogD3D11ErrorDetails(error, device);
  2359. } catch (const char *error) {
  2360. blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s", error);
  2361. }
  2362. return texture;
  2363. }
  2364. int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms)
  2365. {
  2366. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2367. if (tex->type != GS_TEXTURE_2D)
  2368. return -1;
  2369. if (tex2d->acquired)
  2370. return 0;
  2371. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2372. if (!keyedMutex)
  2373. return -1;
  2374. HRESULT hr = keyedMutex->AcquireSync(key, ms);
  2375. if (hr == S_OK) {
  2376. tex2d->acquired = true;
  2377. return 0;
  2378. } else if (hr == WAIT_TIMEOUT) {
  2379. return ETIMEDOUT;
  2380. }
  2381. return -1;
  2382. }
  2383. extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex,
  2384. uint64_t key)
  2385. {
  2386. gs_texture_2d *tex2d = reinterpret_cast<gs_texture_2d *>(tex);
  2387. if (tex->type != GS_TEXTURE_2D)
  2388. return -1;
  2389. if (!tex2d->acquired)
  2390. return 0;
  2391. ComQIPtr<IDXGIKeyedMutex> keyedMutex(tex2d->texture);
  2392. if (!keyedMutex)
  2393. return -1;
  2394. HRESULT hr = keyedMutex->ReleaseSync(key);
  2395. if (hr == S_OK) {
  2396. tex2d->acquired = false;
  2397. return 0;
  2398. }
  2399. return -1;
  2400. }
  2401. extern "C" EXPORT bool
  2402. device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y,
  2403. gs_texture_t **p_tex_uv, uint32_t width,
  2404. uint32_t height, uint32_t flags)
  2405. {
  2406. if (!device->nv12Supported)
  2407. return false;
  2408. *p_tex_y = nullptr;
  2409. *p_tex_uv = nullptr;
  2410. gs_texture_2d *tex_y;
  2411. gs_texture_2d *tex_uv;
  2412. try {
  2413. tex_y = new gs_texture_2d(device, width, height, GS_R8, 1,
  2414. nullptr, flags, GS_TEXTURE_2D, false,
  2415. true);
  2416. tex_uv = new gs_texture_2d(device, tex_y->texture, flags);
  2417. } catch (const HRError &error) {
  2418. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s (%08lX)",
  2419. error.str, error.hr);
  2420. LogD3D11ErrorDetails(error, device);
  2421. return false;
  2422. } catch (const char *error) {
  2423. blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s", error);
  2424. return false;
  2425. }
  2426. tex_y->pairedNV12texture = tex_uv;
  2427. tex_uv->pairedNV12texture = tex_y;
  2428. *p_tex_y = tex_y;
  2429. *p_tex_uv = tex_uv;
  2430. return true;
  2431. }
  2432. extern "C" EXPORT gs_stagesurf_t *
  2433. device_stagesurface_create_nv12(gs_device_t *device, uint32_t width,
  2434. uint32_t height)
  2435. {
  2436. gs_stage_surface *surf = NULL;
  2437. try {
  2438. surf = new gs_stage_surface(device, width, height);
  2439. } catch (const HRError &error) {
  2440. blog(LOG_ERROR,
  2441. "device_stagesurface_create (D3D11): %s "
  2442. "(%08lX)",
  2443. error.str, error.hr);
  2444. LogD3D11ErrorDetails(error, device);
  2445. }
  2446. return surf;
  2447. }
  2448. extern "C" EXPORT void
  2449. device_register_loss_callbacks(gs_device_t *device,
  2450. const gs_device_loss *callbacks)
  2451. {
  2452. device->loss_callbacks.emplace_back(*callbacks);
  2453. }
  2454. extern "C" EXPORT void device_unregister_loss_callbacks(gs_device_t *device,
  2455. void *data)
  2456. {
  2457. for (auto iter = device->loss_callbacks.begin();
  2458. iter != device->loss_callbacks.end(); ++iter) {
  2459. if (iter->data == data) {
  2460. device->loss_callbacks.erase(iter);
  2461. break;
  2462. }
  2463. }
  2464. }
  2465. uint32_t gs_get_adapter_count(void)
  2466. {
  2467. uint32_t count = 0;
  2468. const IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2
  2469. : __uuidof(IDXGIFactory1);
  2470. ComPtr<IDXGIFactory1> factory;
  2471. HRESULT hr = CreateDXGIFactory1(factoryIID, (void **)factory.Assign());
  2472. if (SUCCEEDED(hr)) {
  2473. ComPtr<IDXGIAdapter1> adapter;
  2474. for (UINT i = 0;
  2475. factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) {
  2476. DXGI_ADAPTER_DESC desc;
  2477. if (SUCCEEDED(adapter->GetDesc(&desc))) {
  2478. /* ignore Microsoft's 'basic' renderer' */
  2479. if (desc.VendorId != 0x1414 &&
  2480. desc.DeviceId != 0x8c) {
  2481. ++count;
  2482. }
  2483. }
  2484. }
  2485. }
  2486. return count;
  2487. }