d3d11-subsystem.cpp 87 KB

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