Ejemplo n.º 1
0
        public override void Init(IntPtr display, IntPtr window, uint samples, bool vsync, bool sRGB)
        {
            _display = display;
            _window  = window;
            _vsync   = vsync;

            FeatureLevel[] features =
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0
            };

            SharpDX.Direct3D11.Device dev11 = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.None, features);
            _dev = dev11.QueryInterfaceOrNull <SharpDX.Direct3D11.Device1>();

            SampleDescription sampleDesc = new SampleDescription();

            do
            {
                if (_dev.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, (int)samples) > 0)
                {
                    sampleDesc.Count   = (int)samples;
                    sampleDesc.Quality = 0;
                    break;
                }
                else
                {
                    samples >>= 1;
                }
            } while (samples > 0);

            SwapChainDescription1 desc = new SwapChainDescription1();

            desc.Width             = 0;
            desc.Height            = 0;
            desc.Format            = sRGB ? Format.R8G8B8A8_UNorm_SRgb : Format.R8G8B8A8_UNorm;
            desc.Scaling           = Scaling.None;
            desc.SampleDescription = sampleDesc;
            desc.Usage             = Usage.RenderTargetOutput;
            desc.BufferCount       = 2;
            desc.SwapEffect        = SwapEffect.FlipSequential;
            desc.Flags             = SwapChainFlags.None;

            SharpDX.DXGI.Device2 dev = _dev.QueryInterface <SharpDX.DXGI.Device2>();
            Adapter  adapter         = dev.Adapter;
            Factory2 factory         = adapter.GetParent <Factory2>();

            if (display == IntPtr.Zero)
            {
                GCHandle          handle     = (GCHandle)window;
                SharpDX.ComObject coreWindow = new SharpDX.ComObject(handle.Target as object);
                _swapChain = new SwapChain1(factory, _dev, coreWindow, ref desc);
            }
            else
            {
                _swapChain = new SwapChain1(factory, _dev, window, ref desc);
            }

            _device = new RenderDeviceD3D11(_dev.ImmediateContext.NativePointer, sRGB);
        }
Ejemplo n.º 2
0
        private void CreateCaptureItemDependendStuff()
        {
            _framePool = Direct3D11CaptureFramePool.Create(_device, PixelFormat, 2, _item.Size);
            _framePool.FrameArrived += OnFrameArrived;
            _session = _framePool.CreateCaptureSession(_item);
            _session.IsCursorCaptureEnabled = !PresentationToNDIAddIn.Properties.Settings.Default.HideMouse;

            var description = new SwapChainDescription1
            {
                Width             = _item.Size.Width,
                Height            = _item.Size.Height,
                Format            = SharpDxFormat,
                Stereo            = false,
                SampleDescription = new SampleDescription {
                    Count = 1, Quality = 0
                },
                Usage       = Usage.RenderTargetOutput,
                BufferCount = 2,
                Scaling     = Scaling.Stretch,
                SwapEffect  = SwapEffect.FlipSequential,
                AlphaMode   = AlphaMode.Premultiplied,
                Flags       = SwapChainFlags.None
            };

            _swapChain = new SwapChain1(_factory, _d3dDevice, ref description);
            _session.StartCapture();
        }
Ejemplo n.º 3
0
            public void Initialize(Device2 device, IntPtr hwnd, CompositionType compositionType, Size2 size)
            {
                if (Device != null)
                {
                    Dispose();
                }

                Device  = device;
                Adapter = Device.GetParent <Adapter>();
                Factory = Adapter.GetParent <Factory2>();

                var swapChainDescription = new SwapChainDescription1
                {
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = Usage.RenderTargetOutput,
                    BufferCount       = 2,
                    SwapEffect        = GetBestSwapEffectForPlatform(),
                    Scaling           = Scaling.Stretch,
                    Format            = Format.B8G8R8A8_UNorm,
                    AlphaMode         = compositionType.HasFlag(CompositionType.Composited)
                        ? AlphaMode.Premultiplied
                        : AlphaMode.Ignore,
                    Width  = size.Width,
                    Height = size.Height
                };

                SwapChain = compositionType.HasFlag(CompositionType.Composited)
                    ? new SwapChain1(Factory, Device, ref swapChainDescription)
                    : new SwapChain1(Factory, Device, hwnd, ref swapChainDescription);
            }
Ejemplo n.º 4
0
        public void Dispose()
        {
            if (_rtv != null)
            {
                _rtv.Dispose();
            }
            _rtv = null;

            if (_swap != null)
            {
                _swap.Dispose();
            }
            _swap = null;

            if (ToolkitDevice != null)
            {
                ToolkitDevice.Dispose();
            }
            ToolkitDevice = null;

            if (_context != null)
            {
                _context.Dispose();
            }
            _context = null;

            if (_device != null)
            {
                _device.Dispose();
            }
            _device = null;

            _width  = 0;
            _height = 0;
        }
Ejemplo n.º 5
0
        private void InitSwapChain(int width, int height)
        {
            if (width <= 0 || height <= 0)
            {
                throw new ArgumentException("panel must have a valid width or height");
            }

            // Create swap chain for composition and bind to panel
            var desc = new SwapChainDescription1
            {
                Width             = width,
                Height            = height,
                Format            = Format.B8G8R8A8_UNorm,
                Flags             = SwapChainFlags.None,
                BufferCount       = 2,
                AlphaMode         = AlphaMode.Unspecified,
                Stereo            = false,
                Scaling           = Scaling.Stretch,
                SampleDescription = { Count = 1, Quality = 0 },
                SwapEffect        = SwapEffect.FlipSequential,
                Usage             = Usage.RenderTargetOutput
            };

            _width  = width;
            _height = height;

            var dxgiDev = ComObject.As <SharpDX.DXGI.Device1>(_device.NativePointer);
            var adapter = dxgiDev.Adapter;
            var fact    = adapter.GetParent <SharpDX.DXGI.Factory2>();

            _swap = fact.CreateSwapChainForComposition(_device, ref desc, null);

            dxgiDev.MaximumFrameLatency = 1;
        }
        void CreateSwapChain()
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                SwapEffect        = SwapEffect.FlipSequential,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.Stretch,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = 1080,
                Width             = 1920,
            };

            // 建立SwapChain
            using (SharpDX.DXGI.Device3 dxgiDevice3 = D3D11Device.QueryInterface <SharpDX.DXGI.Device3>()) {
                using (Factory2 dxgiFactory2 = dxgiDevice3.Adapter.GetParent <Factory2>()) {
                    swapChain1 = new SwapChain1(dxgiFactory2, D3D11Device, ref swapChainDescription);
                    swapChain1.QueryInterface <SwapChain>();
                }
            }

            // 把Xaml的SwapChainPanel與DirectX的SwapChain連結起來
            using (ISwapChainPanelNative swapChainPanelNative = ComObject.As <ISwapChainPanelNative>(this)) {
                swapChainPanelNative.SwapChain = swapChain1;
                SetViewport();
            }
        }
Ejemplo n.º 7
0
 protected override SharpDX.DXGI.SwapChain2 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Creates a SwapChain from a CoreWindow pointer
     using (var comWindow = new ComObject(window))
         using (var swapChain1 = new SwapChain1(factory, device, comWindow, ref desc))
             return(swapChain1.QueryInterface <SwapChain2>());
 }
Ejemplo n.º 8
0
        public BackBuffer(Factory2 factory, Device1 device1, RenderForm renderForm)
        {
            swapChainDescription1 = new SwapChainDescription1()
            {
                Width             = renderForm.ClientSize.Width,
                Height            = renderForm.ClientSize.Height,
                Format            = Format.R8G8B8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(4, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.AllowModeSwitch,
            };

            SwapChain = new SwapChain1(factory,
                                       device1,
                                       renderForm.Handle,
                                       ref swapChainDescription1,
                                       new SwapChainFullScreenDescription()
            {
                RefreshRate = new Rational(60, 1),
                Scaling     = DisplayModeScaling.Centered,
                Windowed    = true
            }, null);

            BackBufferTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
        }
Ejemplo n.º 9
0
        private static SwapChain3 CreateSwapChain(
            IntPtr windowHandle,
            D3D12.CommandQueue commandQueue,
            PixelFormat backBufferFormat,
            int backBufferCount,
            int width,
            int height)
        {
            var swapChainDescription = new SwapChainDescription1
            {
                Width             = width,
                Height            = height,
                Format            = backBufferFormat.ToDxgiFormat(),
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                Scaling           = Scaling.Stretch,
                BufferCount       = backBufferCount,
                SwapEffect        = SwapEffect.FlipSequential,
                Flags             = SwapChainFlags.None
            };

#if DEBUG
            const bool debug = true;
#else
            const bool debug = false;
#endif
            using (var dxgiFactory = new Factory2(debug))
                using (var tempSwapChain = new SwapChain1(dxgiFactory, commandQueue, windowHandle, ref swapChainDescription))
                {
                    return(tempSwapChain.QueryInterface <SwapChain3>());
                }
        }
Ejemplo n.º 10
0
            void CreateDeviceResources()
            {
                var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

                var device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();

                var dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>();

                var dxgiAdapter = dxgiDevice2.Adapter;

                SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

                var desc = new SwapChainDescription1();

                desc.Width             = 480;
                desc.Height            = 640;
                desc.Format            = Format.B8G8R8A8_UNorm;
                desc.Stereo            = false;
                desc.SampleDescription = new SampleDescription(1, 0);
                desc.Usage             = Usage.RenderTargetOutput;
                desc.BufferCount       = 2;
                desc.Scaling           = Scaling.AspectRatioStretch;
                desc.SwapEffect        = SwapEffect.FlipSequential;
                desc.Flags             = SwapChainFlags.AllowModeSwitch;

                this.swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(mWindow), ref desc);

                var d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);

                this.d2dDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None);

                var backBuffer = this.swapChain.GetBackBuffer <Surface>(0);

                var displayInfo = DisplayInformation.GetForCurrentView();

                this.d2dTarget = new Bitmap1(this.d2dDeviceContext, backBuffer, new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), displayInfo.LogicalDpi, displayInfo.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw));

                this.updateList = new List <IUpdatable>();

                // 10.5改変
                this.playerShotManager = new PlayerShotManager(this.d2dDeviceContext);

                this.updateList.Add(this.playerShotManager);

                this.fighterDisplay = new Fighter(this.d2dDeviceContext, playerShotManager);
                this.fighterDisplay.SetPosition(540, 240);

                this.displayList = new List <IDrawable>();
                this.displayList.Add(this.fighterDisplay);
                this.displayList.Add(this.playerShotManager);

                this.targetManager = new RectTargetManager(this.d2dDeviceContext, this.playerShotManager);
                this.displayList.Add(this.targetManager);
                this.updateList.Add(this.targetManager);

                this.enemyShotManager = new EnemyShotManager(this.d2dDeviceContext, this.targetManager, this.fighterDisplay);
                this.displayList.Add(this.enemyShotManager);
                this.updateList.Add(this.enemyShotManager);
            }
Ejemplo n.º 11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="swapChain"></param>
 /// <param name="deviceContext"></param>
 public void Initialize(SwapChain1 swapChain, DeviceContext2D deviceContext)
 {
     RemoveAndDispose(ref d2DTarget);
     using (var surf = swapChain.GetBackBuffer <Surface>(0))
     {
         d2DTarget = Collect(BitmapProxy.Create("SwapChainTarget", deviceContext, surf));
     }
 }
Ejemplo n.º 12
0
 public void Dispose()
 {
     if (m_swapChain != null)
     {
         m_swapChain.Dispose();
         m_swapChain = null;
     }
 }
Ejemplo n.º 13
0
        private bool CheckRender(IntPtr hwnd)
        {
            //window did not change
            if (hwnd == window)
            {
                return(window != IntPtr.Zero); //is not no window
            }
            //window changed do some cleanup of resource attached to old window
            fpsColor?.Dispose();
            fpsFont?.Dispose();
            renderOverlay?.Dispose();
            renderTarget?.Dispose();
            renderTexture?.Dispose();
            renderWindow?.Dispose();
            fpsCounter?.Dispose();
            window = hwnd;

            //window changed to no window
            if (window == IntPtr.Zero)
            {
                return(false);
            }

            //window render init
            using (var factory = adapter.GetParent <Factory2>()) {
                renderWindow = new SwapChain1(factory, device, window, ref renderDescription,
                                              new SwapChainFullScreenDescription()
                {
                    RefreshRate = new Rational(15, 1),
                    Scaling     = DisplayModeScaling.Stretched,
                    Windowed    = true
                }, null);

                factory.MakeWindowAssociation(window, WindowAssociationFlags.IgnoreAll);
            }

            renderTexture = Texture2D.FromSwapChain <Texture2D>(renderWindow, 0);
            renderTarget  = new RenderTargetView(device, renderTexture);

            //overlay init
            using (var surface = renderWindow.GetBackBuffer <Surface>(0))
                using (var factory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded))
                    renderOverlay = new RenderTarget(factory, surface, new RenderTargetProperties()
                    {
                        Type        = RenderTargetType.Default,
                        PixelFormat = new D2DPixelFormat(Format.B8G8R8A8_UNorm, D2DAlphaMode.Premultiplied)
                    })
                    {
                        TextAntialiasMode = TextAntialiasMode.Cleartype
                    };

            using (var factory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared))
                fpsFont = new TextFormat(factory, "Calibri", FontWeight.Bold, FontStyle.Normal, 18);

            fpsColor   = new SolidColorBrush(renderOverlay, new Color4(1f, 0f, 1f, 0.7f));
            fpsCounter = new AvgFPSCounter();
            return(true);
        }
Ejemplo n.º 14
0
        public Form1()
        {
            InitializeComponent();

            VerticalSyncEnabled = false;

            using (var device11 = new SharpDX.Direct3D11.Device(
                       SharpDX.Direct3D.DriverType.Hardware,
                       DeviceCreationFlags.None,
                       new[] {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
                SharpDX.Direct3D.FeatureLevel.Level_11_0,
            }))
            {
                // Query device for the Device1 interface (ID3D11Device1)
                device = device11.QueryInterfaceOrNull <SharpDX.Direct3D11.Device1>();
                if (device == null)
                {
                    throw new NotSupportedException(
                              "SharpDX.Direct3D11.Device1 is not supported");
                }
            }// Rather than create a new DXGI Factory we reuse the
             // one that has been used internally to create the device

            int sameple = device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 100);

            using (var dxgi = device.QueryInterface <SharpDX.DXGI.Device2>())
                using (var adapter = dxgi.Adapter)
                    using (var factory = adapter.GetParent <Factory2>())
                    {
                        var desc1 = new SwapChainDescription1()
                        {
                            Width             = this.ClientSize.Width,
                            Height            = this.ClientSize.Height,
                            Format            = Format.R8G8B8A8_UNorm,
                            Stereo            = false,
                            SampleDescription = new SampleDescription(1, 0),
                            Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                            BufferCount       = 1,
                            Scaling           = Scaling.Stretch,
                            SwapEffect        = SwapEffect.Discard,
                        };

                        SwapChain = new SwapChain1(factory,
                                                   device,
                                                   this.Handle,
                                                   ref desc1,
                                                   new SwapChainFullScreenDescription()
                        {
                            RefreshRate = new Rational(60, 1),
                            Scaling     = DisplayModeScaling.Centered,
                            Windowed    = true
                        },
                                                   // Restrict output to specific Output (monitor)
                                                   adapter.Outputs[0]);
                    }
        }
Ejemplo n.º 15
0
        protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Create the swap chain for XAML composition
            var swapChain = new SwapChain1(factory, device, ref desc);

            // Attach swap chain to SwapChainPanel
            nativePanel.SwapChain = swapChain;
            return(swapChain);
        }
Ejemplo n.º 16
0
        public void CreateDirectXSwapChain()
        {
            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                // Want Transparency.
                AlphaMode = SharpDX.DXGI.AlphaMode.Premultiplied,
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = (int)(ActualHeight),
                Width  = (int)(ActualWidth),
                // Default multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
            };

            using (SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport))
            {
                this.device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device2>();
            }

            // Save the context instance
            //this.d3d11DC = this.device.ImmediateContext2;

            using (SharpDX.DXGI.Device3 dxgiDevice3 = device.QueryInterface <SharpDX.DXGI.Device3>())
            {
                using (SharpDX.DXGI.Factory3 dxgiFactory3 = dxgiDevice3.Adapter.GetParent <SharpDX.DXGI.Factory3>())
                {
                    using (SwapChain1 swapChain1 = new SwapChain1(dxgiFactory3, device, ref swapChainDescription))
                    {
                        swapChain = swapChain1.QueryInterface <SwapChain2>();
                    }
                }
            }

            using (ISwapChainPanelNative nativeObject = ComObject.As <ISwapChainPanelNative>(this))
            {
                nativeObject.SwapChain = swapChain;
            }

            backBufferTexture = SharpDX.Direct3D11.Resource.FromSwapChain <SharpDX.Direct3D11.Texture2D>(swapChain, 0);

            using (var surface = backBufferTexture.QueryInterface <Surface2>())
            {
                d2d1DC = new DeviceContext(surface);
            }
        }
Ejemplo n.º 17
0
        protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Creates the swap chain for XAML composition
            var swapChain = new SwapChain1(factory, device, ref desc);

            // Associate the SwapChainBackgroundPanel with the swap chain
            nativeBackgrounPanel.SwapChain = swapChain;

            return(swapChain);
        }
Ejemplo n.º 18
0
        public ScreenGrabberWindowsCapture(MonitorInfo screen) : base(screen)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var device = WindowsCaptureHelper.CreateDirect3DDeviceFromSharpDXDevice(new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport));
                _d3dDevice = WindowsCaptureHelper.CreateSharpDXDevice(device);
                var item   = WindowsCaptureHelper.CreateItemForMonitor(Screen.HMon);

                var factory = new Factory2();

                var description = new SwapChainDescription1
                {
                    Width             = item.Size.Width,
                    Height            = item.Size.Height,
                    Format            = Format.B8G8R8A8_UNorm,
                    Stereo            = false,
                    SampleDescription = new SampleDescription
                    {
                        Count   = 1,
                        Quality = 0
                    },
                    Usage       = Usage.RenderTargetOutput,
                    BufferCount = 2,
                    Scaling     = Scaling.Stretch,
                    SwapEffect  = SwapEffect.FlipSequential,
                    AlphaMode   = AlphaMode.Premultiplied,
                    Flags       = SwapChainFlags.None
                };

                _swapChain = new SwapChain1(factory, _d3dDevice, ref description);
                _framePool = Direct3D11CaptureFramePool.Create(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size);
                _session   = _framePool.CreateCaptureSession(item);
                _session.IsCursorCaptureEnabled = false;

                _swapChain.ResizeBuffers(2, item.Size.Width, item.Size.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);

                _screenTexture = new Texture2D(_d3dDevice, new Texture2DDescription
                {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = item.Size.Width,
                    Height            = item.Size.Height,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                });

                _framePool.FrameArrived += OnFrameArrived;

                _session.StartCapture();
            });
        }
Ejemplo n.º 19
0
        private SwapChain CreateSwapChainForWinRT()
        {
            var coreWindow = Description.DeviceWindowHandle as CoreWindow;
            var swapChainBackgroundPanel = Description.DeviceWindowHandle as SwapChainBackgroundPanel;

            bufferCount = 2;
            var description = new SwapChainDescription1
            {
                // Automatic sizing
                Width             = Description.BackBufferWidth,
                Height            = Description.BackBufferHeight,
                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // TODO: Check if we can use the Description.BackBufferFormat
                Stereo            = false,
                SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultiSampleCount, 0),
                Usage             = Description.RenderTargetUsage,
                // Use two buffers to enable flip effect.
                BufferCount = bufferCount,
                Scaling     = SharpDX.DXGI.Scaling.Stretch,
                SwapEffect  = SharpDX.DXGI.SwapEffect.FlipSequential,
            };

            if (coreWindow != null)
            {
                // Creates a SwapChain from a CoreWindow pointer
                using (var comWindow = new ComObject(coreWindow))
                    return(new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, comWindow, ref description));
            }
            else if (swapChainBackgroundPanel != null)
            {
                var nativePanel = ComObject.As <ISwapChainBackgroundPanelNative>(swapChainBackgroundPanel);
                // Creates the swap chain for XAML composition
                var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);

                // Associate the SwapChainBackgroundPanel with the swap chain
                nativePanel.SwapChain = swapChain;
                return(swapChain);
            }
            else
            {
#if DIRECTX11_2
                using (var comObject = new ComObject(Description.DeviceWindowHandle))
                {
                    var swapChainPanel = comObject.QueryInterfaceOrNull <ISwapChainPanelNative>();
                    if (swapChainPanel != null)
                    {
                        var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);
                        swapChainPanel.SwapChain = swapChain;
                        return(swapChain);
                    }
                }
#endif
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 20
0
        protected override SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Creates the swap chain for XAML composition
            var swapChain = new SwapChain1(factory, device, ref desc);  //factory.CreateSwapChainForComposition(device, ref desc, null);

            // Associate the SwapChainPanel with the swap chain
            nativePanel.SwapChain = swapChain;

            // Returns the new swap chain
            return(swapChain);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///		現在のバックバッファの内容を Bitmap に複写して返す。
        ///		すべての描画が終わったあと、Present() する前に呼び出すこと。
        /// </summary>
        /// <returns>Bitmap。使用後は解放すること。</returns>
        public static Bitmap 取得する(
            SharpDX.Direct3D11.Device1 d3dDevice1,
            SwapChain1 swapchain1,
            RenderTargetView renderTargetView,
            SharpDX.Direct2D1.DeviceContext d2dDeviceContext)
        {
            // バックバッファの情報を取得する。
            Texture2DDescription backBufferDesc;

            using (var backBuffer = swapchain1.GetBackBuffer <Texture2D>(0))
                backBufferDesc = backBuffer.Description;

            // CPUがアクセス可能な Texture2D バッファをGPU上に作成する。
            using var captureTexture = new Texture2D(
                      d3dDevice1,
                      new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,    // CPUからアクセスできる。
                Format            = backBufferDesc.Format,
                Height            = backBufferDesc.Height,
                Width             = backBufferDesc.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Staging, // GPU から CPU への copy ができる。
            });

            // RenderTarget から Texture2D バッファに、GPU上で画像データをコピーする。
            using (var resource = renderTargetView.Resource)
                d3dDevice1.ImmediateContext.CopyResource(resource, captureTexture);

            // Texture2D の本体(DXGIサーフェス)から Bitmap を生成する。
            using var dxgiSurface = captureTexture.QueryInterface <Surface>();
            var dataRect = dxgiSurface.Map(SharpDX.DXGI.MapFlags.Read, out DataStream dataStream);

            try
            {
                return(new Bitmap(
                           d2dDeviceContext,
                           new Size2(captureTexture.Description.Width, captureTexture.Description.Height),
                           new DataPointer(dataStream.DataPointer, (int)dataStream.Length),
                           dataRect.Pitch,
                           new BitmapProperties(
                               new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                               d2dDeviceContext.DotsPerInch.Width,
                               d2dDeviceContext.DotsPerInch.Width)));
            }
            finally
            {
                dxgiSurface.Unmap();
            }
        }
Ejemplo n.º 22
0
        private void CreateSwapChain()
        {
            using (var dxgiAdaptor = DxgiDevice.Adapter)
                using (var dxgiFactory = dxgiAdaptor.GetParent <Factory2>())
                {
                    _deviceContext?.Dispose();
                    _deviceContext = new DeviceContext(D2DDevice, DeviceContextOptions.None)
                    {
                        DotsPerInch = _savedDpi
                    };


                    var swapChainDesc = new SwapChainDescription1
                    {
                        Width             = _savedSize.Width,
                        Height            = _savedSize.Height,
                        Format            = Format.B8G8R8A8_UNorm,
                        Stereo            = false,
                        SampleDescription = new SampleDescription
                        {
                            Count   = 1,
                            Quality = 0,
                        },
                        Usage       = Usage.RenderTargetOutput,
                        BufferCount = 2,
                        Scaling     = Scaling.None,
                        SwapEffect  = SwapEffect.FlipSequential,
                        Flags       = 0,
                    };

                    _swapChain?.Dispose();
                    _swapChain = CreateSwapChain(dxgiFactory, swapChainDesc);

                    using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
                        using (var d2dBackBuffer = new Bitmap1(
                                   _deviceContext,
                                   dxgiBackBuffer,
                                   new BitmapProperties1(
                                       new PixelFormat
                        {
                            AlphaMode = AlphaMode.Ignore,
                            Format = Format.B8G8R8A8_UNorm
                        },
                                       _savedDpi.Width,
                                       _savedDpi.Height,
                                       BitmapOptions.Target | BitmapOptions.CannotDraw)))
                        {
                            _deviceContext.Target = d2dBackBuffer;
                        }
                }
        }
Ejemplo n.º 23
0
        protected override SharpDX.DXGI.SwapChain2 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
        {
            // Creates the swap chain for XAML composition
            using (var swapChain1 = new SwapChain1(factory, device, ref desc))
            {
                var swapChain2 = swapChain1.QueryInterface<SwapChain2>();

                // Associate the SwapChainPanel with the swap chain
                nativePanel.SwapChain = swapChain2;

                // Returns the new swap chain
                return swapChain2;
            }
        }
            public void InitializeRenderThread(DeviceContext renderContext, SwapChain1 swapChain)
            {
                DestoryRenderThread();
                Exception          = null;
                this.renderContext = renderContext;
                this.swapChain     = swapChain;
                tsc = new CancellationTokenSource();
                var token = tsc.Token;

                RenderThread = new Thread(new ThreadStart(() =>
                {
                    while (!token.IsCancellationRequested)
                    {
                        try
                        {
                            renderThreadEvent.Wait();
                            if (token.IsCancellationRequested)
                            {
                                break;
                            }
                            lock (mlock)
                            {
                                if (!paused)
                                {
                                    renderContext.ExecuteCommandList(commandList, true);
                                    renderContext.Flush();
                                    swapChain.Present(0, 0);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Exception = ex;
                            Pause();
                            break;
                        }
                        finally
                        {
                            Disposer.RemoveAndDispose(ref commandList);
                            renderThreadEvent.Reset();
                            IsBusy = false;
                        }
                    }
                }));
                RenderThread.SetApartmentState(ApartmentState.STA);
                RenderThread.IsBackground = true;
                RenderThread.Start();
            }
Ejemplo n.º 25
0
 /// <summary>
 /// Called when [create render target and depth buffers].
 /// </summary>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <returns></returns>
 protected override ShaderResourceViewProxy OnCreateBackBuffer(int width, int height)
 {
     if (swapChain == null || swapChain.IsDisposed)
     {
         swapChain = CreateSwapChain(surfacePtr);
     }
     else
     {
         RemoveAndDispose(ref d2dTarget);
         RemoveAndDispose(ref backBuffer);
         swapChain.ResizeBuffers(swapChain.Description1.BufferCount, TargetWidth, TargetHeight, swapChain.Description.ModeDescription.Format, swapChain.Description.Flags);
     }
     backBuffer = new ShaderResourceViewProxy(Device, Texture2D.FromSwapChain <Texture2D>(swapChain, 0));
     d2dTarget  = new D2DTargetProxy();
     d2dTarget.Initialize(swapChain, DeviceContext2D);
     return(backBuffer);
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Destroys the SwapChain and all related instances.
        /// </summary>
        void DestroySwapChain()
        {
            _swapChain2?.Dispose();
            _swapChain2 = null;

            _device3?.Dispose();
            _device3 = null;

            _swapChain?.Dispose();
            _swapChain = null;

            _device?.Dispose();
            _device = null;

            _d3D11Device?.Dispose();
            _d3D11Device = null;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Called when [create render target and depth buffers].
        /// </summary>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns></returns>
        protected override ShaderResourceViewProxy OnCreateBackBuffer(int width, int height)
        {
            if (swapChain == null || swapChain.IsDisposed)
            {
                swapChain = CreateSwapChain(surfacePtr);
            }
            else
            {
                swapChain.ResizeBuffers(swapChain.Description1.BufferCount, TargetWidth, TargetHeight, swapChain.Description.ModeDescription.Format, swapChain.Description.Flags);
            }
            var backBuffer = Collect(new ShaderResourceViewProxy(Device, Texture2D.FromSwapChain <Texture2D>(swapChain, 0)));
            var sampleDesc = swapChain.Description1.SampleDescription;

            ColorBuffer.CreateRenderTargetView();
            d2dTarget = Collect(new D2DTargetProxy());
            d2dTarget.Initialize(swapChain, DeviceContext2D);
            return(backBuffer);
        }
Ejemplo n.º 28
0
        public void Initialize()
        {
            if (!_deviceManager.IsInitialized)
            {
                throw new InvalidOperationException("Device manager is not initialized");
            }

            if (Initialized)
            {
                Uninitialize();
            }

            var swapChainDescription = new SwapChainDescription1
            {
                Width             = Width,
                Height            = Height,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(SampleCount, SampleQuality),
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                BufferCount       = 1,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.AllowModeSwitch
            };
            var fullScreenDescription = new SwapChainFullScreenDescription
            {
                RefreshRate = new Rational(60, 1),
                Scaling     = DisplayModeScaling.Centered,
                Windowed    = true
            };

            using (var dxgiDevice2 = _deviceManager.Device.QueryInterface <Device2>())
                using (var dxgiFactory2 = dxgiDevice2.Adapter.GetParent <Factory2>())
                {
                    SwapChain = new SwapChain1(dxgiFactory2, _deviceManager.Device, _windowHandle, ref swapChainDescription, fullScreenDescription);
                    dxgiFactory2.MakeWindowAssociation(_windowHandle, WindowAssociationFlags.IgnoreAll);
                }

            Texture          = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
            RenderTargetView = new RenderTargetView(_deviceManager.Device, Texture);

            Initialized = true;
        }
Ejemplo n.º 29
0
        public ScreenCapture(GraphicsCaptureItem i)
        {
            item = i;

            device    = Direct3D11Helper.CreateDevice();
            d3dDevice = Direct3D11Helper.CreateSharpDXDevice(device);

            SizeInt32 correctedSize = item.Size;

            correctedSize.Width  = correctedSize.Width / 8 * 8;
            correctedSize.Height = correctedSize.Height / 8 * 8;

            var dxgiFactory = new Factory2();
            var description = new SwapChainDescription1()
            {
                Width             = correctedSize.Width,
                Height            = correctedSize.Height,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage       = Usage.RenderTargetOutput,
                BufferCount = 2,
                Scaling     = Scaling.Stretch,
                SwapEffect  = SwapEffect.FlipSequential,
                AlphaMode   = AlphaMode.Premultiplied,
                Flags       = SwapChainFlags.None
            };

            swapChain = new SwapChain1(dxgiFactory, d3dDevice, ref description);

            framePool = Direct3D11CaptureFramePool.Create(
                device,
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                2,
                correctedSize);
            session  = framePool.CreateCaptureSession(i);
            lastSize = correctedSize;

            framePool.FrameArrived += OnFrameArrived;
        }
Ejemplo n.º 30
0
        void InitializeDirect2D()
        {
            d3dDevice  = new D3D.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
            dxgiDevice = d3dDevice.QueryInterface <DXGI.Device1>();
            var desc = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 3,
                Scaling           = Scaling.None,
                SwapEffect        = SwapEffect.FlipSequential,
                Flags             = SwapChainFlags.None
            };

            DXGI.Factory2 dxgiFactory = dxgiDevice.Adapter.GetParent <DXGI.Factory2>();
            swapChain = new SwapChain1(dxgiFactory, d3dDevice, Child.Handle, ref desc);
            swapChain.BackgroundColor = Color4.White;
            dxgiFactory.Dispose();

            d2dFactory       = new D2D.Factory1(FactoryType.SingleThreaded);
            d2dDevice        = new D2D.Device(d2dFactory, dxgiDevice);
            d2dDeviceContext = new D2D.DeviceContext(d2dDevice, DeviceContextOptions.None);
            d2dDeviceContext.TextAntialiasMode = TextAntialiasMode.Cleartype;
            //d2dDeviceContext.DotsPerInch = new Size2F(96, 96);
            var props = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
                                              d2dDeviceContext.DotsPerInch.Width,
                                              d2dDeviceContext.DotsPerInch.Height,
                                              BitmapOptions.Target | BitmapOptions.CannotDraw);
            Surface1 dxgiSurface = swapChain.GetBackBuffer <Surface1>(0);

            d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
            dxgiSurface.Dispose();
            d2dDeviceContext.Target = d2dSurface;

            VertexFillBrush = new SolidColorBrush(d2dDeviceContext, new Color4(1, 0.5f, 0, 1));
            VertexDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.2f, 0.2f, 0.2f, 1));
            EdgeDrawBrush   = new SolidColorBrush(d2dDeviceContext, Color4.Black);
            RasterDrawBrush = new SolidColorBrush(d2dDeviceContext, new Color4(0.5f, 0.5f, 0.5f, 1));
        }