1
0

d3d11-subsystem.cpp 91 KB

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