d3d11-subsystem.cpp 69 KB

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