public static ID3D11Device CreateD3Device() { Vortice.Direct3D.FeatureLevel[] supportedFeatureLevels = new[] { Vortice.Direct3D.FeatureLevel.Level_11_1, Vortice.Direct3D.FeatureLevel.Level_11_0, Vortice.Direct3D.FeatureLevel.Level_10_1, Vortice.Direct3D.FeatureLevel.Level_10_0, }; DriverType[] supportedDrivers = new[] { DriverType.Hardware, DriverType.Warp, }; Result result = default; foreach (DriverType driver in supportedDrivers) { result = D3D11.D3D11CreateDevice(null, driver, DeviceCreationFlags.BgraSupport, supportedFeatureLevels, out ID3D11Device device); if (result.Success) { return(device); } } throw new SharpGenException(result); }
private void StartDesktopDuplicator(int adapterId, int outputId) { var adapter = factory.GetAdapter1(adapterId); D3D11.D3D11CreateDevice(adapter, DriverType.Unknown, DeviceCreationFlags.None, s_featureLevels, out device); var output = adapter.GetOutput(outputId); var output1 = output.QueryInterface <IDXGIOutput1>(); var bounds = output1.Description.DesktopCoordinates; var width = bounds.Right - bounds.Left; var height = bounds.Bottom - bounds.Top; var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = width / 2, Height = height / 2, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = Usage.Staging }; stagingTexture = device.CreateTexture2D(textureDesc); var smallerTextureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, OptionFlags = ResourceOptionFlags.GenerateMips, MipLevels = 4, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = Usage.Default }; smallerTexture = device.CreateTexture2D(smallerTextureDesc); smallerTextureView = device.CreateShaderResourceView(smallerTexture); duplication = output1.DuplicateOutput(device); }
public static Bitmap CaptureScreenFrames(int screenId) { var factory = DXGI.CreateDXGIFactory1 <IDXGIFactory1>(); var adapter = factory.GetAdapter(0); var output = adapter.GetOutput(screenId); var output1 = output.QueryInterface <IDXGIOutput1>(); D3D11.D3D11CreateDevice(adapter, DriverType.Unknown, DeviceCreationFlags.None, s_featureLevels, out var device); var bounds = output1.Description.DesktopCoordinates; var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = bounds.Right - bounds.Left, Height = bounds.Bottom - bounds.Top, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = Vortice.Direct3D11.Usage.Staging }; var duplication = output1.DuplicateOutput(device); var currentFrame = device.CreateTexture2D(textureDesc); Thread.Sleep(100); duplication.AcquireNextFrame(500, out var frameInfo, out var desktopResource); var tempTexture = desktopResource.QueryInterface <ID3D11Texture2D>(); device.ImmediateContext.CopyResource(currentFrame, tempTexture); var dataBox = device.ImmediateContext.Map(currentFrame, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None); var frame = new Bitmap(1920, 1080, PixelFormat.Format32bppRgb); var mapDest = frame.LockBits(new Rectangle(0, 0, 1920, 1080), ImageLockMode.WriteOnly, frame.PixelFormat); for (int y = 0, sizeInBytesToCopy = 1920 * 4; y < 1080; y++) { MemoryHelpers.CopyMemory(mapDest.Scan0 + y * mapDest.Stride, dataBox.DataPointer + y * dataBox.RowPitch, sizeInBytesToCopy); } frame.UnlockBits(mapDest); return(frame); }
void Run() { D3D11.D3D11CreateDevice(null, DriverType.Hardware, DeviceCreationFlags.None, null, out device, out deviceContext); var moduleHandle = GetModuleHandle(null); var wndClass = new WNDCLASSEX { Size = Unsafe.SizeOf <WNDCLASSEX>(), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW | WindowClassStyles.CS_OWNDC, WindowProc = WndProc, InstanceHandle = moduleHandle, CursorHandle = LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), BackgroundBrushHandle = IntPtr.Zero, IconHandle = IntPtr.Zero, ClassName = "WndClass", }; RegisterClassEx(ref wndClass); var win32window = new Win32Window(wndClass.ClassName, "Vortice ImGui", 800, 600); var mainWindow = new MainWindow(win32window, device, deviceContext); windows.Add(mainWindow.Win32Window.Handle, mainWindow); mainWindow.Show(); while (!quitRequested) { if (PeekMessage(out var msg, IntPtr.Zero, 0, 0, PM_REMOVE)) { TranslateMessage(ref msg); DispatchMessage(ref msg); if (msg.Value == (uint)WindowMessage.Quit) { quitRequested = true; break; } } foreach (var window in windows.Values) { window.UpdateAndDraw(); } } }
public static DesktopDuplicatorInternal CreateDesktopDuplicator(ILogger logger, int adapterIndex, int outputDeviceIndex) { var dd = new DesktopDuplicatorInternal { _outputDeviceIndex = outputDeviceIndex }; var createFactoryResult = DXGI.CreateDXGIFactory1(out IDXGIFactory1 factory); if (!createFactoryResult.Success) { throw new DesktopDuplicationException("Couldn't create a DXGI Factory."); } IDXGIAdapter1 adapter = null; IDXGIOutput output = null; try { var result = factory.EnumAdapters1(adapterIndex, out adapter); if (result.Failure) { throw new DesktopDuplicationException($"An error occurred attempting to retrieve the adapter at the specified index ({adapterIndex}): {result}"); } if (adapter == null) { throw new DesktopDuplicationException($"An adapter was not found at the specified index ({adapterIndex})."); } logger.LogInformation($"Using adapter at index {adapterIndex} - {adapter.Description.Description}"); var createD3dDeviceResult = D3D11.D3D11CreateDevice(adapter, DriverType.Unknown, DeviceCreationFlags.None, null, out dd._d3dDevice, out dd._immediateContext); if (!createD3dDeviceResult.Success) { throw new DesktopDuplicationException("Couldn't create a D3D device from the specified adapter."); } using var device = dd._d3dDevice.QueryInterface <IDXGIDevice>(); var outputResult = adapter.EnumOutputs(outputDeviceIndex, out output); if (outputResult.Failure) { throw new DesktopDuplicationException($"An error occurred attempting to retrieve the output device at the specified index ({outputDeviceIndex}): {outputResult}"); } if (output == null) { throw new DesktopDuplicationException($"An output was not found at the specified index ({outputDeviceIndex})."); } logger.LogInformation($"Using output device on adapter {adapterIndex} at index {outputDeviceIndex}."); var output6 = output.QueryInterface <IDXGIOutput6>(); try { // Copy the values to a new rect. var rectTemp = output6.Description.DesktopCoordinates; dd._desktopRect = new RawRect(rectTemp.Left, rectTemp.Top, rectTemp.Right, rectTemp.Bottom); dd._outputDuplication = output6.DuplicateOutput(device); var stagingTexture = new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = dd._outputDuplication.Description.ModeDescription.Format, Width = Math.Abs(dd._desktopRect.Right - dd._desktopRect.Left), Height = Math.Abs(dd._desktopRect.Bottom - dd._desktopRect.Top), OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = Usage.Staging // << can be read by CPU }; // Initialize the Output Duplication -- If this isn't done occassionally an 'Unsupported' result will occur with DuplicationOutput1 dd._desktopImageTexture = dd._d3dDevice.CreateTexture2D(stagingTexture); } catch (SharpGenException ex) { if (ex.Descriptor.NativeApiCode == "DXGI_ERROR_UNSUPPORTED") { throw new DesktopDuplicationException("Unsupported desktop mode or scenario."); } else if (ex.Descriptor.NativeApiCode == "DXGI_ERROR_NOT_CURRENTLY_AVAILABLE") { throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again."); } else { throw; } } } finally { if (output != null) { output.Dispose(); } if (adapter != null) { adapter.Dispose(); } if (factory != null) { factory.Dispose(); } } return(dd); }
public bool Init(IntPtr WindowHandle) { var factory = DXGI.CreateDXGIFactory1 <IDXGIFactory1>(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); var adapterDescription = adapter.Description; //VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; //VideoCardDescription = adapterDescription.Description.Trim('\0'); monitor.Dispose(); adapter.Dispose(); var swapChainDesc = new SwapChainDescription() { BufferCount = 2, BufferDescription = new ModeDescription(1920, 1080, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputWindow = WindowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; // Create Device and DeviceContext ID3D11Device TempDevice = null; ID3D11DeviceContext TempDeviceContext = null; D3D11.D3D11CreateDevice(adapter, DriverType.Hardware, DeviceCreationFlags.None, null, out TempDevice, out TempDeviceContext); Device = TempDevice.QueryInterface <ID3D11Device1>(); DeviceContext = TempDeviceContext.QueryInterface <ID3D11DeviceContext1>(); TempDevice.Dispose(); TempDeviceContext.Dispose(); // Create SwapChain SwapChain = factory.CreateSwapChain(Device, swapChainDesc); factory.MakeWindowAssociation(WindowHandle, WindowAssociationFlags.IgnoreAltEnter); var backBuffer = SwapChain.GetBuffer <ID3D11Texture2D>(0); m_RenderTargetView = Device.CreateRenderTargetView(backBuffer); backBuffer.Dispose(); // Create blend state BlendDescription bsd = new BlendDescription() { AlphaToCoverageEnable = false,//true, IndependentBlendEnable = false, }; bsd.RenderTarget[0].BlendOperationAlpha = BlendOperation.Add; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].DestinationBlendAlpha = Blend.One; bsd.RenderTarget[0].DestinationBlend = Blend.InverseSourceAlpha; bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteEnable.All; bsd.RenderTarget[0].SourceBlendAlpha = Blend.Zero; bsd.RenderTarget[0].SourceBlend = Blend.SourceAlpha; bsd.AlphaToCoverageEnable = true; ID3D11BlendState bsAlpha = Device.CreateBlendState(bsd); // Set Blend State DeviceContext.OMSetBlendState(bsAlpha); BuildDepthStencilView(1920, 1080); // Create rasterizers m_RSDesc = new RasterizerDescription() { AntialiasedLineEnable = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, DepthClipEnable = false, FillMode = FillMode.Solid, FrontCounterClockwise = true, MultisampleEnable = true, ScissorEnable = false, SlopeScaledDepthBias = .0f }; m_RSCullSolid = Device.CreateRasterizerState(m_RSDesc); m_RSDesc.CullMode = CullMode.None; m_RSSolid = Device.CreateRasterizerState(m_RSDesc); m_RSDesc.FillMode = FillMode.Wireframe; m_RSWireFrame = Device.CreateRasterizerState(m_RSDesc); m_RSDesc.CullMode = CullMode.Back; m_RSCullWireFrame = Device.CreateRasterizerState(m_RSDesc); UpdateRasterizer(); return(true); }