d3d11-subsystem.cpp 68 KB

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