d3d11-subsystem.cpp 60 KB

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