d3d11-subsystem.cpp 89 KB

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