d3d11-subsystem.cpp 70 KB

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