d3d11-subsystem.cpp 67 KB

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