d3d11-subsystem.cpp 87 KB

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