d3d11-subsystem.cpp 59 KB

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