d3d11-subsystem.cpp 73 KB

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