d3d11-subsystem.cpp 90 KB

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