d3d11-subsystem.cpp 86 KB

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