d3d11-subsystem.cpp 91 KB

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