d3d11-subsystem.cpp 68 KB

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