d3d11-subsystem.cpp 82 KB

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