d3d11-subsystem.cpp 73 KB

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