Пример #1
0
 protected Bitmap(string name, Direct2DDevice device, Size2 size, BitmapProperties1 bitmapProperties)
     : base(name, device)
 {
     Properties = bitmapProperties;
     Resource   = ToDispose(new Bitmap1(device, size, bitmapProperties));
     Size       = size;
 }
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="BackBuffer">Буффер на который будем рисовать, наш холст</param>
        /// <param name="Width">Ширина области в которую будем рисовать</param>
        /// <param name="Height">Высота объласти в которую будем рисовать</param>
        public TextWirter(SharpDX.Direct3D11.Device2 device, SwapChain2 swapChain, Color color, float dpi = 96f, string font = "Calibri", int size = 14)
        {
#if DEBUG
            var debug = SharpDX.Direct2D1.DebugLevel.Error;
#else
            var debug = SharpDX.Direct2D1.DebugLevel.None;
#endif

            _Factory2D = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debug);
            using (var dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device>())
            {
                d2dDevice = new SharpDX.Direct2D1.Device(_Factory2D, dxgiDevice);
            }
            _RenderTarget2D = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            BitmapProperties1 properties = new BitmapProperties1(
                new PixelFormat(
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied),
                dpi,
                dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);
            d2dTarget        = new Bitmap1(_RenderTarget2D, backBuffer, properties);
            this.TextFont    = font;
            this.TextSize    = size;
            _FactoryDWrite   = new SharpDX.DirectWrite.Factory();
            _SceneColorBrush = new SolidColorBrush(_RenderTarget2D, color);
            InitTextFormat();
            _RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;
        }
 public DeviceManager()
 {
     try
     {
         // 创建 Dierect3D 设备。
         this.d3DDevice  = new D3D11Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport);
         this.dxgiDevice = d3DDevice.QueryInterface <D3D11Device1>().QueryInterface <DXGIDevice>();
         // 创建 Direct2D 设备和工厂。
         this.d2DDevice  = new D2D1Device(dxgiDevice);
         this.d2DContext = new DeviceContext(d2DDevice, DeviceContextOptions.None);
         this.d2DFactory = this.d2DContext.Factory;
         this.wicFactory = new ImagingFactory2();
     }
     catch
     {
         this.ClearResources();
         try
         {
             // 创建 D3D 设备异常,则尝试 Direct2D 单线程工厂。
             this.d2DFactory = new Factory(FactoryType.SingleThreaded);
             this.wicFactory = new ImagingFactory();
         }
         catch
         {
             this.ClearResources();
         }
     }
     if (this.d2DFactory != null)
     {
         Dpi          = d2DFactory.DesktopDpi;
         BitmapProps1 = new BitmapProperties1(D2PixelFormat, Dpi.Width, Dpi.Height, BitmapOptions.Target);
     }
 }
Пример #4
0
        public override void Update(D3D11Device device)
        {
            var rt = SetRenderTarget(device);

            if (_bitmap == null)
            {
                var pf = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);
                var bp = new BitmapProperties1(pf, device.Dpi.Height, device.Dpi.Width,
                                               BitmapOptions.CannotDraw | BitmapOptions.Target)
                ;

                using (var surface = rt.Surface)
                {
                    _bitmap = new Bitmap1(device.D2DDeviceContext, surface, bp);
                }
            }

            device.D2DDeviceContext.Target = _bitmap;
            device.D2DDeviceContext.BeginDraw();
            {
                _scene.Draw(device.D2DDeviceContext, new SharpDX.RectangleF(0, 0, _rect.Width, _rect.Height));
            }
            device.D2DDeviceContext.EndDraw();
            device.D2DDeviceContext.Target = null;
        }
Пример #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProxy"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="context">The context.</param>
 /// <param name="surface">The surface.</param>
 /// <param name="properties">The properties.</param>
 public BitmapProxy(string name, DeviceContext context, Surface surface, BitmapProperties1 properties)
 {
     Properties = properties;
     Context    = context;
     bitmap     = new Bitmap1(context, surface, properties);
     Size       = new Size2((int)Bitmap.Size.Width, (int)Bitmap.Size.Height);
     Name       = name;
 }
Пример #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BitmapProxy"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="context">The context.</param>
 /// <param name="size">The size.</param>
 /// <param name="properties">The properties.</param>
 public BitmapProxy(string name, DeviceContext context, Size2 size, BitmapProperties1 properties)
 {
     Properties = properties;
     Context    = context;
     bitmap     = new Bitmap1(context, size, properties);
     Size       = size;
     Name       = name;
 }
Пример #7
0
        public static Bitmap1 LoadBitmap(string filename, DeviceContext context)
        {
            var props = new BitmapProperties1
            {
                PixelFormat =
                    new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)
            };

            return(Bitmap1.FromWicBitmap(context, LoadBitmap(filename), props));
        }
        public static Bitmap1 LoadBitmap(SharpDX.Direct3D11.DeviceContext device, string filename)
        {
            var props = new BitmapProperties1
            {
                PixelFormat =
                    new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)
            };

            return(Bitmap1.FromWicBitmap(device.QueryInterface <SharpDX.Direct2D1.DeviceContext>(), LoadBitmapSource(device, filename), props));
        }
Пример #9
0
        private Bitmap1 _作成したテクスチャとデータを共有するビットマップターゲットを作成する()
        {
            using var dxgiSurface = this.Texture.QueryInterfaceOrNull <SharpDX.DXGI.Surface>();

            var bmpProp = new BitmapProperties1()
            {
                PixelFormat   = new PixelFormat(dxgiSurface.Description.Format, AlphaMode.Premultiplied),
                BitmapOptions = BitmapOptions.Target | BitmapOptions.CannotDraw,
            };

            return(new Bitmap1(Global.既定のD2D1DeviceContext, dxgiSurface, bmpProp));
        }
Пример #10
0
        public static Bitmap1 CreateBitmapRenderTarget(this _d2d.DeviceContext3 d2dDeContext, SwapChain swapChain)
        {
            using var backBuffer = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0);
            using var surface    = backBuffer.QueryInterface <Surface>();

            var bmpProperties = new BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                dpiX: 96,
                dpiY: 96,
                bitmapOptions: BitmapOptions.Target | BitmapOptions.CannotDraw);

            return(new Bitmap1(d2dDeContext, surface, bmpProperties));
        }
Пример #11
0
        void CreateBitmap(D3D11Device device)
        {
            Dispose();

            var pf = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore);
            var bp = new BitmapProperties1(pf, device.Dpi.Height, device.Dpi.Width,
                                           BitmapOptions.CannotDraw | BitmapOptions.Target)
            ;

            using (var surface = _getSurface())
            {
                m_bitmap = new Bitmap1(device.D2DDeviceContext, surface);
            }
        }
Пример #12
0
 public Direct2DText()
 {
     defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                   d3d.DeviceCreationFlags.VideoSupport
                                                   | d3d.DeviceCreationFlags.BgraSupport
                                                   | d3d.DeviceCreationFlags.None); // take out the Debug flag for better performance
     d3dDevice      = defaultDevice.QueryInterface <d3d.Device1>();                 // get a reference to the Direct3D 11.1 device
     dxgiDevice     = d3dDevice.QueryInterface <dxgi.Device>();                     // get a reference to DXGI device
     d2dDevice      = new d2.Device(dxgiDevice);                                    // initialize the D2D device
     imagingFactory = new wic.ImagingFactory2();                                    // initialize the WIC factory
     d2dContext     = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);
     dwFactory      = new dw.Factory();
     d2dBitmapProps = new BitmapProperties1(d2PixelFormat, dpi, dpi, BitmapOptions.Target | BitmapOptions.CannotDraw);
 }
Пример #13
0
        public void InitializeDeviceResources()
        {
            ModeDescription backBufferDesc = new ModeDescription(1600, 900, new Rational(60, 1), Format.B8G8R8A8_UNorm);

            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = this.Handle,
                IsWindowed        = true
            };

            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug;

            //SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0))
            {
                renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            System.Drawing.Graphics g = this.CreateGraphics();

            SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, SharpDX.Direct2D1.DebugLevel.None);

            // Create Direct2D device
            var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>();

            //d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
            d2dDevice  = new SharpDX.Direct2D1.Device(dxgiDevice);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
            //d2dContext.PrimitiveBlend = PrimitiveBlend.SourceOver;

            BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                                                                 g.DpiX, g.DpiY, BitmapOptions.Target | BitmapOptions.CannotDraw);

            Surface backBuffer2D = swapChain.GetBackBuffer <Surface>(0);

            //new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied)
            SharpDX.Direct2D1.RenderTargetProperties rtp = new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore));
            d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, backBuffer2D, rtp);
            d2dTarget       = new Bitmap1(d2dContext, backBuffer2D, properties);

            d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView);
        }
Пример #14
0
        void Resize()
        {
            d2dDeviceContext.Target = null;
            d2dSurface.Dispose();
            swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);
            Surface1 dxgiSurface = swapChain.GetBackBuffer <Surface1>(0);
            var      props       = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore),
                                                         d2dDeviceContext.DotsPerInch.Width,
                                                         d2dDeviceContext.DotsPerInch.Height,
                                                         BitmapOptions.Target | BitmapOptions.CannotDraw);

            d2dSurface = new Bitmap1(d2dDeviceContext, dxgiSurface, props);
            dxgiSurface.Dispose();
            d2dDeviceContext.Target = d2dSurface;
        }
Пример #15
0
        protected override void On活性化()
        {
            // テクスチャを作成する。
            base.On活性化();

            // 作成したテクスチャとデータを共有するビットマップターゲットを作成する。
            using (var dxgiSurface = this.Texture.QueryInterfaceOrNull <SharpDX.DXGI.Surface1>())
            {
                var bmpProp = new BitmapProperties1()
                {
                    PixelFormat   = new PixelFormat(dxgiSurface.Description.Format, AlphaMode.Premultiplied),
                    BitmapOptions = BitmapOptions.Target | BitmapOptions.CannotDraw,
                };
                this._Bitmap = new Bitmap1(グラフィックデバイス.Instance.D2DDeviceContext, dxgiSurface, bmpProp);
            }
        }
Пример #16
0
 public static void CreateDeviceSwapChainBitmap(
     IDXGISwapChain1 swapChain,
     ID2D1DeviceContext target)
 {
     using (IDXGISurface surface = swapChain.GetBuffer <IDXGISurface>(0))
     {
         var props = new BitmapProperties1
         {
             BitmapOptions = BitmapOptions.Target | BitmapOptions.CannotDraw,
             PixelFormat   = new Vortice.DCommon.PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Ignore)
         };
         using (var bitmap = target.CreateBitmapFromDxgiSurface(surface, props))
         {
             target.Target = bitmap;
         }
     }
 }
Пример #17
0
        public static Bitmap1 LoadBitmap2D(BclBitmap bitmap)
        {
            var sourceArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var imageRes   = new Size(bitmap.Width, bitmap.Height);

            var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly,
                                             System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            var stride    = bitmap.Width * sizeof(int);
            var bytesSize = bitmapData.Stride * bitmapData.Height;

            var byteArray = new byte[bytesSize];

            Marshal.Copy(bitmapData.Scan0, byteArray, 0, bytesSize);

            bitmap.UnlockBits(bitmapData);

            var tempStream = new DataStream(bytesSize, true, true);

            for (var y = 0; y < bitmap.Height; y++)
            {
                var offset = stride * y;
                for (var x = 0; x < bitmap.Width; x++)
                {
                    var b    = byteArray[offset++];
                    var g    = byteArray[offset++];
                    var r    = byteArray[offset++];
                    var a    = byteArray[offset++];
                    var rgba = r | (g << 8) | (b << 16) | (a << 24);
                    tempStream.Write(rgba);
                }
            }

            tempStream.Position = 0;

            var bitmapProperties =
                new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm,
                                                                        SharpDX.Direct2D1.AlphaMode.Premultiplied));

            var newBitmap = new Bitmap1(Renderer.Context2D, new Size2(bitmap.Width, bitmap.Height), tempStream,
                                        stride,
                                        bitmapProperties);

            return(newBitmap);
        }
Пример #18
0
        private Bitmap1 DecodeImage(Stream imageStream)
        {
            using (var bitmapDecoder = new BitmapDecoder(WicFactory, imageStream, DecodeOptions.CacheOnDemand))
                using (var converter = new FormatConverter(WicFactory))
                {
                    _formatGuid = bitmapDecoder.ContainerFormat;
                    var frame = bitmapDecoder.GetFrame(0);
                    converter.Initialize(frame, ImagePixelFormat);

                    var props = new BitmapProperties1()
                    {
                        BitmapOptions = BitmapOptions.Target,
                        PixelFormat   = DevicePixelFormat
                    };

                    return(SharpDX.Direct2D1.Bitmap1.FromWicBitmap(DeviceContext, converter, props));
                }
        }
Пример #19
0
        private void InitializeDirectX(GameWindow gameWindow)
        {
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
            {
                _d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }

            var swapChainDesc = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                BufferCount       = 2,
                Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                SwapEffect        = SwapEffect.FlipSequential,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.AspectRatioStretch
            };

            using (var dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                using (var dxgiFactory = dxgiDevice.Adapter.GetParent <SharpDX.DXGI.Factory2>())
                {
                    var window = new ComObject(gameWindow.WindowObject);
                    _swapChain  = new SwapChain1(dxgiFactory, _d3dDevice, window, ref swapChainDesc);
                    _d2dFactory = new SharpDX.Direct2D1.Factory1();
                    _d2dDevice  = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                }

            _deviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
            using (var surface = Surface.FromSwapChain(_swapChain, 0))
            {
                var pixelFormat      = new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied);
                var bitmapProperties = new BitmapProperties1(pixelFormat, 0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw);

                _d2dTargetBitmap      = new SharpDX.Direct2D1.Bitmap1(_deviceContext, surface, bitmapProperties);
                _deviceContext.Target = _d2dTargetBitmap;
            }

            _dwriteFactory   = new SharpDX.DirectWrite.Factory1();
            _wicFactory      = new ImagingFactory();
            _formatConverter = new FormatConverter(_wicFactory);
            _deviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype;
        }
Пример #20
0
        public Stream GenerateBitmapFont(string characters, ImmutableDictionary <int, string> puaCharacters, ImageFormat format,
                                         out byte[] widths, bool drawOutline, string fontFamily, int fontSize, int baselineOriginX, int baselineOriginY)
        {
            _cellWidth  = drawOutline ? OutlineCellWidth : NormalCellWidth;
            _cellHeight = drawOutline ? OutlineCellHeight : NormalCellHeight;
            int rowCount     = (int)Math.Ceiling((double)characters.Length / ColumnCount);
            int bitmapWidth  = _cellWidth * ColumnCount;
            int bitmapHeight = 4 * (int)Math.Ceiling((double)_cellHeight * rowCount / 4);

            var bitmapProperties = new BitmapProperties1(DevicePixelFormat, Dpi, Dpi, BitmapOptions.Target);
            var containerGuid    = format == ImageFormat.Png ? ContainerFormatGuids.Png : ContainerFormatGuids.Dds;

            using (var fontBitmap = new Bitmap1(DeviceContext, new Size2(bitmapWidth, bitmapHeight), bitmapProperties))
            {
                DrawCharacters(fontBitmap, characters, puaCharacters, drawOutline, 0, 0, fontFamily, fontSize, baselineOriginX, baselineOriginY);
                widths = _widths;
                return(EncodeBitmap(fontBitmap, containerGuid));
            }
        }
Пример #21
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));
        }
Пример #22
0
        /// <summary>
        /// Initializes the presentable resources before resize.
        /// </summary>
        /// <param name="device"></param>
        public void InitializePresentable(GraphicsDevice device)
        {
            Device3D12 device3D12 = device.NativeDevice;

            deviceContext2D = new GraphicsDeviceContext2D(DeviceContext);

            Brush = new SolidColorBrush(DeviceContext, SharpDX.Color.White);

            var properties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
                DesktopDpi.Width,
                DesktopDpi.Height,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            FrameResources = new FrameResource[Presenter.BackBufferCount];
            for (int i = 0; i < Presenter.BackBufferCount; i++)
            {
                var frameResource = new FrameResource();
                FrameResources[i]          = frameResource;
                frameResource.RenderTarget = Presenter.BackBuffers[i].Resource;

                Device3D.CreateWrappedResource(
                    Presenter.BackBuffers[i].Resource,
                    new D3D11ResourceFlags()
                {
                    BindFlags = (int)BindFlags.RenderTarget
                },
                    (int)ResourceStates.RenderTarget,
                    (int)ResourceStates.Present,
                    Utilities.GetGuidFromType(typeof(Resource11)),
                    out frameResource.WrappedBackBuffer);

                frameResource.Surface = frameResource.WrappedBackBuffer.QueryInterface <Surface>();
                frameResource.Bitmap  = new Bitmap1(DeviceContext, frameResource.Surface, properties);
            }

            // https://msdn.microsoft.com/en-us/library/windows/desktop/dd370966(v=vs.85).aspx#resizing_a_dxgi_surface_render_target
            // https://msdn.microsoft.com/en-us/library/windows/desktop/bb205075(v=vs.85).aspx#Care_and_Feeding_of_the_Swap_Chain
            // https://msdn.microsoft.com/en-us/library/windows/desktop/bb205075(v=vs.85).aspx#Handling_Window_Resizing
        }
Пример #23
0
        private void CreateDeviceIndependentResources()
        {
            _dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>();
            _d2dDevice  = new SharpDX.Direct2D1.Device(_dxgiDevice);
            _d2dFactory = _d2dDevice.Factory;
            var dpiX = _d2dFactory.DesktopDpi.Width;
            var dpiY = _d2dFactory.DesktopDpi.Height;

            _dc = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None);
            _dc.PrimitiveBlend = PrimitiveBlend.SourceOver;

            var format     = new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied);
            var properties = new BitmapProperties1(format, dpiX, dpiY, BitmapOptions.Target | BitmapOptions.CannotDraw);

            _surface      = _swapChain.GetBackBuffer <Surface>(0);
            _renderTarget = new Bitmap1(_dc, _surface, properties);

            _dc.Target        = _renderTarget;
            _dc.AntialiasMode = AntialiasMode.PerPrimitive;

            OnCreateDeviceIndependentResources();
            this._deviceIndependedResourcesCreated = true;
        }
Пример #24
0
        public void Resize(object sender, WindowEventArgs pE)
        {
            try
            {
                Device.ImmediateContext.ClearState();

                _backBuffer.Dispose();
                _renderTarget.Dispose();
                Context.Dispose();

                _swapChain.ResizeBuffers(BUFFER_COUNT, (int)pE.Size.Width, (int)pE.Size.Height, Format.Unknown, SwapChainFlags.AllowModeSwitch);

                Context = new SharpDX.Direct2D1.DeviceContext(_2dDevice, DeviceContextOptions.None);
                var dpi  = Factory2D.DesktopDpi;
                var prop = new BitmapProperties1(new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), dpi.Height, dpi.Width, BitmapOptions.CannotDraw | BitmapOptions.Target);
                _backBuffer    = _swapChain.GetBackBuffer <Surface>(0);
                _renderTarget  = new Bitmap1(Context, _backBuffer, prop);
                Context.Target = _renderTarget;
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error creating render target: " + e.Message);
            }
        }
Пример #25
0
        protected override void OnInitialize(InitializeDirectXEventArgs e)
        {
            IDirect2DProvider direct2D         = e.DirectX.Direct2D;
            BitmapProperties1 bitmapProperties = new BitmapProperties1()
            {
                DpiX          = e.Settings.Dpi,
                DpiY          = e.Settings.Dpi,
                PixelFormat   = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                BitmapOptions = BitmapOptions.Target,
            };

            uiSurface = ToDispose(new Bitmap1(direct2D.Context,
                                              new Size2(e.Settings.ScreenWidth, e.Settings.ScreenHeight), bitmapProperties));

            Overlay = ToDispose(Overlay.FromDescription(
                                    new OverlayDescription(width: e.Settings.ScreenWidth,
                                                           height: e.Settings.ScreenHeight)));
            Overlay.BeginDesign();

            Panel panel = new Panel()
            {
                Position = new SharpDX.Vector2(512, 192), Width = 320, Height = 92
            };
            Label label = new Label()
            {
                Position = new SharpDX.Vector2(8, 8), Text = "stereo"
            };

            panel.Add(label);
            Overlay.Add(panel);

            Overlay.EndDesign(e.DirectX);

            effectGraph = CreateEffectGraph(direct2D);
            direct2D.Context.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Пример #26
0
        protected void InitialiseResources()
        {
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _surface);
            RemoveAndDispose(ref _target);
            _d2dContext.Target = null;

            var desc = CreateSwapChainDescription();

            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description.BufferCount,
                    WindowSize.Width,
                    WindowSize.Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            else
            {
                using (var dxgiDevice2 = _d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            _swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc));
                            //_swapChain = ToDispose(new SwapChain1(dxgiFactory2, _d3dDevice, _outputHandle, ref desc));
                        }
            }

            _backBuffer = ToDispose(Resource.FromSwapChain <Texture2D>(_swapChain, 0));
            {
                // Create a view interface on the rendertarget to use on bind.
                _renderTargetView = new RenderTargetView(_d3dDevice, _backBuffer);

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = _backBuffer.Description;
                RenderTargetBounds = new Rectangle(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            using (var depthBuffer = new Texture2D(_d3dDevice,
                                                   new Texture2DDescription()
            {
                Format = Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)WindowSize.Width,
                Height = (int)WindowSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.DepthStencil,
            }))
                _depthStencilView = new DepthStencilView(_d3dDevice, depthBuffer, new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D
                });

            var viewport = new ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            _d3dContext.Rasterizer.SetViewport(viewport);

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
                _d2dFactory.DesktopDpi.Width,
                _d2dFactory.DesktopDpi.Height,
                BitmapOptions.Target | BitmapOptions.CannotDraw);


            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
                _target = new Bitmap1(_d2dContext, dxgiBackBuffer, bitmapProperties);

            _d2dContext.Target            = _target;
            _d2dContext.TextAntialiasMode = TextAntialiasMode.Grayscale;

            /*_backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_d3dDevice, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0))
             *  _target = ToDispose(new RenderTarget(_d2dFactory, dxgiBackBuffer, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */
            OnInitialize?.Invoke(this);
        }
Пример #27
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device     = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width  = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                                                                 DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create the DirectWrite factory objet.
            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

            // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);

            // Create two TextLayout objects for rendering the moving text.
            textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f);
            textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f);

            // Vertical offset for the moving text.
            layoutY = 0.0f;

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush       = new SolidColorBrush(d2dContext, Color.Black);
        }
        protected virtual void CreateSizeDependentResources()
        {
            // Ensure dependent objects have been released.
            d2dContext.Target = null;
            if (d2dTargetBitmap != null)
            {
                RemoveAndDispose(ref d2dTargetBitmap);
            }
            d3dContext.OutputMerger.SetRenderTargets((RenderTargetView)null);
            d3dContext.Flush();

            /*d3dContext.FinishCommandList(false);
             * d3dContext.li*/

            // Set render target size to the rendered size of the panel including the composition scale,
            // defaulting to the minimum of 1px if no size was specified.
            var scale              = Dpi / 96;
            var renderTargetWidth  = (int)(panel.ActualWidth * scale);
            var renderTargetHeight = (int)(panel.ActualHeight * scale);

            if (renderTargetWidth == 0 || renderTargetHeight == 0)
            {
                return;
            }

            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, renderTargetWidth, renderTargetHeight, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
            }
            else
            {
                var swapChainDesc = new SwapChainDescription1();
                swapChainDesc.Width  = renderTargetWidth;
                swapChainDesc.Height = renderTargetHeight;
                swapChainDesc.Format = Format.B8G8R8A8_UNorm;
                swapChainDesc.Stereo = new RawBool(false);
                swapChainDesc.SampleDescription.Count   = 1;
                swapChainDesc.SampleDescription.Quality = 0;
                swapChainDesc.Usage       = Usage.RenderTargetOutput;
                swapChainDesc.BufferCount = 2;
                swapChainDesc.SwapEffect  = SwapEffect.FlipSequential;
                swapChainDesc.Flags       = SwapChainFlags.None;
                swapChainDesc.AlphaMode   = AlphaMode.Unspecified; // Todo... May need to change
                //swapChainDesc.Scaling = Scaling.None;

                using (var dxgiDevice = d3dDevice.QueryInterface <global::SharpDX.DXGI.Device1>())
                {
                    var dxgiAdapter = dxgiDevice.Adapter;
                    var dxgiFactory = dxgiAdapter.GetParent <global::SharpDX.DXGI.Factory2>();

                    swapChain = Collect(new SwapChain1(dxgiFactory, d3dDevice, ref swapChainDesc, null));

                    // Counter act the composition scale of the render target as
                    // we already handle this in the platform window code.
                    using (var swapChain2 = swapChain.QueryInterface <SwapChain2>())
                    {
                        var inverseScale = new RawMatrix3x2();
                        inverseScale.M11           = 1.0f / scale;
                        inverseScale.M22           = 1.0f / scale;
                        swapChain2.MatrixTransform = inverseScale;
                    }

                    dxgiDevice.MaximumFrameLatency = 1;
                }

                // Associate the SwapChainBackgroundPanel with the swap chain
                using (var panelNative = ComObject.As <ISwapChainPanelNative>(panel))
                {
                    panelNative.SwapChain = swapChain;
                }
            }

            var bitmapProperties = new BitmapProperties1(
                new PixelFormat(Format.B8G8R8A8_UNorm, global::SharpDX.Direct2D1.AlphaMode.Premultiplied),
                Dpi,
                Dpi,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            using (var dxgiBackBuffer = swapChain.GetBackBuffer <Surface>(0))
            {
                d2dTargetBitmap   = Collect(new Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));
                d2dContext.Target = d2dTargetBitmap;
            }
        }
Пример #29
0
 protected BitmapTarget(string name, Direct2DDevice device, Surface surface, BitmapProperties1 description)
     : base(name, device, surface, description)
 {
     Initialize(Resource);
 }
Пример #30
0
        protected void _Bitmapを生成する(BitmapProperties1 bitmapProperties1 = null)
        {
            var decoder     = (BitmapDecoder)null;
            var sourceFrame = (BitmapFrameDecode)null;
            var converter   = (FormatConverter)null;

            try
            {
                // 生成に失敗しても例外は発生しない。ただ描画メソッドで表示されなくなるだけ。

                #region " 画像ファイルパスの有効性を確認する。"
                //-----------------
                if (this._画像ファイルパス.数なしパス.Nullまたは空である())
                {
                    Log.ERROR($"画像ファイルパスが null または空文字列です。[{this._画像ファイルパス.変数付きパス}]");
                    return;
                }
                if (false == System.IO.File.Exists(this._画像ファイルパス.数なしパス))
                {
                    Log.ERROR($"画像ファイルが存在しません。[{this._画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " 画像ファイルに対応できるデコーダを見つける。"
                //-----------------
                try
                {
                    decoder = new BitmapDecoder(
                        グラフィックデバイス.Instance.WicImagingFactory,
                        this._画像ファイルパス.数なしパス,
                        SharpDX.IO.NativeFileAccess.Read,
                        DecodeOptions.CacheOnLoad);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"画像ファイルに対応するコーデックが見つかりません。(0x{e.HResult:x8})[{this._画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " 最初のフレームをデコードし、取得する。"
                //-----------------
                try
                {
                    sourceFrame = decoder.GetFrame(0);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"画像ファイルの最初のフレームのデコードに失敗しました。(0x{e.HResult:x8})[{this._画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " 32bitPBGRA へのフォーマットコンバータを生成する。"
                //-----------------
                try
                {
                    // WICイメージングファクトリから新しいコンバータを生成。
                    converter = new FormatConverter(グラフィックデバイス.Instance.WicImagingFactory);

                    // コンバータに変換元フレームや変換後フォーマットなどを設定。
                    converter.Initialize(
                        sourceRef: sourceFrame,
                        dstFormat: SharpDX.WIC.PixelFormat.Format32bppPBGRA,    // Premultiplied BGRA
                        dither: BitmapDitherType.None,
                        paletteRef: null,
                        alphaThresholdPercent: 0.0,
                        paletteTranslate: BitmapPaletteType.MedianCut);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"32bitPBGRA へのフォーマットコンバータの生成または初期化に失敗しました。(0x{e.HResult:x8})[{this._画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                #region " コンバータを使って、フレームを WICビットマップ経由で D2D ビットマップに変換する。"
                //-----------------
                try
                {
                    // WIC ビットマップを D2D ビットマップに変換する。
                    this._Bitmap?.Dispose();
                    this._Bitmap = Bitmap1.FromWicBitmap(
                        グラフィックデバイス.Instance.D2DDeviceContext,
                        converter,
                        bitmapProperties1);
                }
                catch (SharpDXException e)
                {
                    Log.ERROR($"Direct2D1.Bitmap1 への変換に失敗しました。(0x{e.HResult:x8})[{this._画像ファイルパス.変数付きパス}]");
                    return;
                }
                //-----------------
                #endregion

                //Log.Info( $"{FDKUtilities.現在のメソッド名}: 画像を生成しました。[{変数付きファイルパス}]" );
            }
            finally
            {
                converter?.Dispose();
                sourceFrame?.Dispose();
                decoder?.Dispose();
            }
        }