d3d11-subsystem.cpp 86 KB

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