d3d11-subsystem.cpp 59 KB

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