d3d11-subsystem.cpp 88 KB

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