d3d11-subsystem.cpp 69 KB

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