1
0

d3d11-subsystem.cpp 89 KB

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