d3d11-subsystem.cpp 90 KB

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