d3d11-subsystem.cpp 86 KB

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