Esempio n. 1
0
// ReSharper restore InconsistentNaming

        static CompositionEngine()
        {
            _wicFactory    = new SharpDX.WIC.ImagingFactory();
            _dWriteFactory = new SharpDX.DirectWrite.Factory();

            var d3DDevice = new SharpDX.Direct3D11.Device(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport
#if DEBUG
                | DeviceCreationFlags.Debug
#endif
                ,
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As <SharpDX.DXGI.Device>(d3DDevice.NativePointer);
            //new SharpDX.DXGI.Device2(d3DDevice.NativePointer);
            var d2DDevice = new SharpDX.Direct2D1.Device(dxgiDevice);

            _d2DFactory                   = d2DDevice.Factory;
            _d2DDeviceContext             = new SharpDX.Direct2D1.DeviceContext(d2DDevice, D2D.DeviceContextOptions.None);
            _d2DDeviceContext.DotsPerInch = new DrawingSizeF(
                Windows.Graphics.Display.DisplayProperties.LogicalDpi,
                Windows.Graphics.Display.DisplayProperties.LogicalDpi);
        }
 internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Esempio n. 3
0
        public void Shutdown()
        {
            if (_deviceContext != null)
            {
                _deviceContext.Dispose();
                _deviceContext = null;
            }

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

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

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

            if (_default3DDevice != null)
            {
                _default3DDevice.Dispose();
                _default3DDevice = null;
            }
        }
// ReSharper restore InconsistentNaming

        static CompositionEngine()
        {
            _wicFactory = new SharpDX.WIC.ImagingFactory();
            _dWriteFactory = new SharpDX.DirectWrite.Factory();

            var d3DDevice = new SharpDX.Direct3D11.Device(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport
#if DEBUG
                | DeviceCreationFlags.Debug
#endif
,
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3,
                FeatureLevel.Level_9_2,
                FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As<SharpDX.DXGI.Device>(d3DDevice.NativePointer);
                //new SharpDX.DXGI.Device2(d3DDevice.NativePointer);
            var d2DDevice = new SharpDX.Direct2D1.Device(dxgiDevice);
            _d2DFactory = d2DDevice.Factory;
            _d2DDeviceContext = new SharpDX.Direct2D1.DeviceContext(d2DDevice, D2D.DeviceContextOptions.None);
            _d2DDeviceContext.DotsPerInch = new Size2F(LogicalDpi, LogicalDpi);
        }
 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);
     }
 }
Esempio n. 6
0
        public WindowedDirect2dRenderEnvironment(string formName, bool debug)
        {
            form = new RenderForm(formName);

            d3dDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | (debug ? DeviceCreationFlags.Debug : DeviceCreationFlags.None));

            dxgiDevice  = d3dDevice.QueryInterface <SharpDX.DXGI.Device>();
            dxgiFactory = new SharpDX.DXGI.Factory1();
            swapChain   = new SwapChain(dxgiFactory, dxgiDevice, new SwapChainDescription {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(Format.B8G8R8A8_UNorm),
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            });
            dxgiSurface = swapChain.GetBackBuffer <Surface>(0);

            d2dFactory        = new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debug ? DebugLevel.Warning : DebugLevel.None);
            d2dDevice         = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice);
            d2dContext        = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None);
            bitmap            = new Bitmap1(d2dContext, dxgiSurface, null);
            d2dContext.Target = bitmap;
        }
Esempio n. 7
0
        public DXD2D1()
        {
            _d3d11Device = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels);
            _dxgiDevice  = _d3d11Device.QueryInterface <D3D11.Device>().QueryInterface <DXGI.Device>();

            _d2dDevice = new D2D1.Device(_dxgiDevice);
        }
Esempio n. 8
0
        /// <summary>
        /// Disposes of object resources.
        /// </summary>
        /// <param name="disposeManagedResources">If true, managed resources should be
        /// disposed of in addition to unmanaged resources.</param>
        protected virtual void Dispose(bool disposeManagedResources)
        {
            if (disposeManagedResources)
            {
                _d3d11Device.Dispose();
                _dxgiDevice.Dispose();
                _backBuffer.Dispose();
                _targetBitmap.Dispose();
                _backBuffer2.Dispose();
                _targetBitmap2.Dispose();
                _d2dDevice.Dispose();
                swapChain.Dispose();
                swapChain2.Dispose();
                d2dContext.Dispose();
                d2dContext2.Dispose();
                dw_Factory.Dispose();
            }

            _d3d11Device   = null;
            _dxgiDevice    = null;
            _backBuffer    = null;
            _targetBitmap  = null;
            _backBuffer2   = null;
            _targetBitmap2 = null;
            _d2dDevice     = null;
            swapChain      = null;
            swapChain2     = null;
            d2dContext     = null;
            d2dContext2    = null;
            dw_Factory     = null;
        }
        public Direct2DFactories()
        {
            WICFactory = new WIC.ImagingFactory();
            DWFactory  = new DW.Factory();

            var d3DDevice = new D3D11.Device(
                D3D.DriverType.Hardware,
                D3D11.DeviceCreationFlags.BgraSupport
#if DEBUG
                | D3D11.DeviceCreationFlags.Debug
#endif
                ,
                D3D.FeatureLevel.Level_11_1,
                D3D.FeatureLevel.Level_11_0,
                D3D.FeatureLevel.Level_10_1,
                D3D.FeatureLevel.Level_10_0,
                D3D.FeatureLevel.Level_9_3,
                D3D.FeatureLevel.Level_9_2,
                D3D.FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As <SharpDX.DXGI.Device> (d3DDevice.NativePointer);
            var d2DDevice  = new D2D1.Device(dxgiDevice);

            D2DFactory = d2DDevice.Factory;
            //_d2DDeviceContext = new D2D1.DeviceContext (d2DDevice, D2D1.DeviceContextOptions.None);
            //var dpi = DisplayDpi;
            //_d2DDeviceContext.DotsPerInch = new Size2F (dpi, dpi);
        }
Esempio n. 10
0
            public Core()
            {
                using (var dxgiDevice =
                           ImageFramework.DirectX.Device.Get().Handle.QueryInterface <SharpDX.DXGI.Device>())
                {
#if DEBUG
                    var debugLevel = DebugLevel.Information;
#else
                    var debugLevel = DebugLevel.None;
#endif
                    var factory = new SharpDX.Direct2D1.Factory1(FactoryType.MultiThreaded, debugLevel);
                    Factory = factory;
                    Handle  = new SharpDX.Direct2D1.Device(factory, dxgiDevice);
                    Context = new SharpDX.Direct2D1.DeviceContext(Handle, DeviceContextOptions.None);
                }

                WriteFactory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);

                RoundStroke = new StrokeStyle(Factory, new StrokeStyleProperties
                {
                    StartCap = CapStyle.Round,
                    EndCap   = CapStyle.Round
                });
                HardStroke = new StrokeStyle(Factory, new StrokeStyleProperties
                {
                    StartCap = CapStyle.Flat,
                    EndCap   = CapStyle.Flat
                });

                ImageFramework.DirectX.Device.Get().DeviceDispose += (sender, args) => Dispose();
            }
Esempio n. 11
0
        public MainWindow()
        {
            _dxgiDevice = AvaloniaLocator.Current.GetService <SharpDX.DXGI.Device>();
            _d3dDevice  = _dxgiDevice.QueryInterface <SharpDX.Direct3D11.Device>();
            _d2dDevice  = AvaloniaLocator.Current.GetService <SharpDX.Direct2D1.Device>();
            DataContext = _model = new MainWindowViewModel();
            _desc       = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription((int)ClientSize.Width, (int)ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = PlatformImpl?.Handle.Handle ?? IntPtr.Zero,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            _swapChain = new SwapChain(new Factory1(), _d3dDevice, _desc);

            _d2dContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None)
            {
                DotsPerInch = new Size2F(96, 96)
            };

            CreateMesh();
            _view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            this.GetObservable(ClientSizeProperty).Subscribe(Resize);
            Resize(ClientSize);
            AvaloniaXamlLoader.Load(this);
            Background = Avalonia.Media.Brushes.Transparent;
        }
        /// <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 D3D11Renderer(ObservableVideoTrack videoTrack, RendererOptions options)
            : base(videoTrack, options)
        {
            // _factoryDWrite = new DWrite.Factory(DWrite.FactoryType.Shared);

            var device2D = new D2D1.Device(DeviceDXGI, new D2D1.CreationProperties
            {
                DebugLevel    = D2D1.DebugLevel.Warning,
                ThreadingMode = D2D1.ThreadingMode.MultiThreaded,
                Options       = D2D1.DeviceContextOptions.None
            });

            _context2D = new D2D1.DeviceContext(device2D, D2D1.DeviceContextOptions.None);

            // Load the background image
            using (var factoryWic = new WIC.ImagingFactory2())
                using (var decoder = new WIC.JpegBitmapDecoder(factoryWic))
                    using (var inputStream = new WIC.WICStream(factoryWic, "background-small.jpg", NativeFileAccess.Read))
                        using (var formatConverter = new WIC.FormatConverter(factoryWic))
                            using (var bitmapScaler = new WIC.BitmapScaler(factoryWic))
                            {
                                decoder.Initialize(inputStream, WIC.DecodeOptions.CacheOnLoad);
                                formatConverter.Initialize(decoder.GetFrame(0), WIC.PixelFormat.Format32bppPBGRA);
                                bitmapScaler.Initialize(formatConverter, VideoFrameWidth, VideoFrameHeight,
                                                        WIC.BitmapInterpolationMode.Fant);
                                _backgroundBitmap = D2D1.Bitmap1.FromWicBitmap(_context2D, bitmapScaler);
                            }

            // Create render target
            _ballEllipse = new D2D1.Ellipse {
                RadiusX = VideoFrameWidth / 20f, RadiusY = VideoFrameWidth / 20f
            };

            _ballBrush = new D2D1.SolidColorBrush(_context2D, new RawColor4(1f, 1f, 0f, 1f));
        }
Esempio n. 14
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);
            }
Esempio n. 15
0
        public CapturePlayback(SharpDX.Direct2D1.Device device, SharpDX.WIC.ImagingFactory factory, CapturePlayer player)
        {
            this.player = player;
            context     = new DeviceContext(device, DeviceContextOptions.EnableMultithreadedOptimizations);

            CurrentFrame = player.CurrentSurface.Select(surface => CreateFrame(surface));
            this.factory = factory;
        }
Esempio n. 16
0
        public StreamPlayback(SharpDX.Direct2D1.Device device, SharpDX.WIC.ImagingFactory factory, StreamPlayer player, TimeSpan?duration)
        {
            this.player = player;
            context     = new DeviceContext(device, DeviceContextOptions.EnableMultithreadedOptimizations);
            Duration    = duration;

            CurrentFrame = player.CurrentTime.Select(time => CreateFrame(player.Surface, time)).DisposeCurrentOnNext();
            this.factory = factory;
        }
Esempio n. 17
0
        public PaintingDevice(Device2D device2D, Device device3D)
        {
            Contract.Requires(device2D != null);
            Contract.Requires(device3D != null);

            _Factory2D = new Factory(FactoryType.SingleThreaded);

            _PainterContext = new Painter(_Factory2D, device2D, device3D);

            Contract.Assert(Factory2D == _Factory2D);
            Contract.Assert(Painter == _PainterContext);
        }
 /// <summary>
 /// 清理所有正在使用的资源,并设置为 <c>null</c>。
 /// </summary>
 private void ClearResources()
 {
     if (this.d3DDevice != null)
     {
         this.d3DDevice.Dispose();
         this.d3DDevice = null;
     }
     if (this.dxgiDevice != null)
     {
         this.dxgiDevice.Dispose();
         this.dxgiDevice = null;
     }
     if (this.swapChain != null)
     {
         this.swapChain.Dispose();
         this.swapChain = null;
     }
     if (this.backBuffer != null)
     {
         this.backBuffer.Dispose();
         this.backBuffer = null;
     }
     if (this.targetBitmap != null)
     {
         this.targetBitmap.Dispose();
         this.swapChain = null;
     }
     if (this.d2DDevice != null)
     {
         this.d2DDevice.Dispose();
         this.d2DDevice = null;
     }
     if (this.d2DContext != null)
     {
         this.d2DContext.Dispose();
         this.d2DContext = null;
     }
     if (this.d2DFactory != null)
     {
         this.d2DFactory.Dispose();
         this.d2DFactory = null;
     }
     if (this.renderTarget != null)
     {
         this.renderTarget.Dispose();
         this.renderTarget = null;
     }
     if (this.wicFactory != null)
     {
         this.wicFactory.Dispose();
         this.wicFactory = null;
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D11" /> class.
        /// </summary>
        /// <param name="core">The core.</param>
        /// <param name="engineDevice">The engine device.</param>
        internal DeviceHandlerD2D(GraphicsCore core, EngineDevice engineDevice)
        {
            try
            {
                bool doFallbackMethod = core.Force2DFallbackMethod || (core.FactoryD2D_2 == null);

                // Simulate exception if requested
                if (GraphicsCore.ThrowD2DInitDeviceError)
                {
                    throw new SeeingSharpGraphicsException("Simulation Direct2D device init exception");
                }

                // Do default method (Windows 8 and newer)
                if (!doFallbackMethod)
                {
                    try
                    {
                        using (DXGI.Device dxgiDevice = engineDevice.DeviceD3D11_1.QueryInterface <DXGI.Device>())
                        {
                            m_deviceD2D        = new D2D.Device1(engineDevice.Core.FactoryD2D_2, dxgiDevice);
                            m_deviceContextD2D = new SharpDX.Direct2D1.DeviceContext(
                                m_deviceD2D,
                                D2D.DeviceContextOptions.None);
                            m_renderTarget = m_deviceContextD2D;
                        }
                    }
                    catch (Exception) { doFallbackMethod = true; }
                }

                // Fallback method (on older windows platforms (< Windows 8))
                if (doFallbackMethod)
                {
                    m_renderTarget     = null;
                    m_deviceD2D        = null;
                    m_deviceContextD2D = null;

                    m_dummyRenderTargetTexture = GraphicsHelper.CreateRenderTargetTextureDummy(
                        engineDevice.DeviceD3D11_1, 32, 32);
                    m_dummyDirect2DOverlay = new Direct2DOverlayRenderer(
                        engineDevice, m_dummyRenderTargetTexture, 32, 32, DpiScaling.Default,
                        forceInit: true);
                }
            }
            catch (Exception)
            {
                GraphicsHelper.SafeDispose(ref m_deviceContextD2D);
                GraphicsHelper.SafeDispose(ref m_deviceD2D);
                GraphicsHelper.SafeDispose(ref m_dummyDirect2DOverlay);
                GraphicsHelper.SafeDispose(ref m_dummyRenderTargetTexture);
                GraphicsHelper.SafeDispose(ref m_renderTarget);
            }
        }
Esempio n. 20
0
        public static Direct2D1.DeviceContext CreateRenderTarget(
            Direct2D1.Factory1 factory2d,
            Direct3D11.Device device3d)
        {
            var dxgiDevice = device3d.QueryInterface <DXGI.Device>();

            using (var device2d = new Direct2D1.Device(factory2d, dxgiDevice))
            {
                return(new Direct2D1.DeviceContext(
                           device2d,
                           Direct2D1.DeviceContextOptions.None));
            }
        }
Esempio n. 21
0
        public RendererUtil()
        {
            var defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport);

            d3dDevice = defaultDevice.QueryInterface<D3D11.Device1>();
            dxgiDevice = d3dDevice.QueryInterface<Device>();

            d2dFactory = new D2D.Factory(D2D.FactoryType.MultiThreaded);

            d2dDevice = new D2D.Device(dxgiDevice);
            d2dDeviceContext = new D2D.DeviceContext(d2dDevice, D2D.DeviceContextOptions.None);

            imagingFactory = new ImagingFactory2();
        }
Esempio n. 22
0
        /// <summary>
        /// Create a batch manager for drawing text and sprite
        /// </summary>
        /// <param name="device">Device pointer</param>
        internal Canvas(Device device)
        {
            Device = device;

            NativeFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, DebugLevel.Information);

            using (var dxgiDevice = device.NativeDevice.QueryInterface <DeviceGI>())
                NativeDevice = new Device2D(NativeFactory, dxgiDevice);

            NativeDeviceContext = new DeviceContext(NativeDevice, DeviceContextOptions.None);

            InitializeFont();
            Brush = new SolidColorBrush(NativeDeviceContext, default(Color4));
        }
Esempio n. 23
0
        public Direct2DDevice(IServiceRegistry services, SharpDX.Direct3D11.Device d3dDevice, DebugLevel debugLevel)
        {
            this.services = services;
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
            {
                factory       = ToDispose(new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debugLevel));
                device        = ToDispose(new Device(factory, dxgiDevice));
                deviceContext = ToDispose(new DeviceContext(device, DeviceContextOptions.None));
            }

            backBuffer = ToDispose(BackBufferSurface.New(this));
            backBuffer.Initialize();

            directWriteFactory = ToDispose(new DWFactory());
        }
        private void InitializeDevices()
        {
            try
            {
                SwapChainDescription                   = new DXGI.SwapChainDescription();
                SwapChainDescription.BufferCount       = 2;
                SwapChainDescription.SampleDescription = new DXGI.SampleDescription(1, 0);
                SwapChainDescription.SwapEffect        = DXGI.SwapEffect.Discard;
                SwapChainDescription.Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput;
                SwapChainDescription.IsWindowed        = true;
                SwapChainDescription.ModeDescription   = new DXGI.ModeDescription(GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm);
                SwapChainDescription.OutputHandle      = GameWindowHandle;

                D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels, SwapChainDescription, out D3DDefaultDevice, out SwapChain);

                DXGI.Factory factory = SwapChain.GetParent <DXGI.Factory>();
                factory.MakeWindowAssociation(GameWindowHandle, DXGI.WindowAssociationFlags.IgnoreAll);

                D3DDevice = D3DDefaultDevice.QueryInterface <D3D11.Device1>();

                Backbuffer       = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(SwapChain, 0);
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, Backbuffer);
                D3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height);
                D3DDevice.ImmediateContext.OutputMerger.SetTargets(RenderTargetView);

                DXGIDevice = D3DDevice.QueryInterface <DXGI.Device>();

                D2DFactory       = new D2D1.Factory1(D2D1.FactoryType.MultiThreaded);
                D2DDevice        = new D2D1.Device(D2DFactory, DXGIDevice);
                D2DDeviceContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);

                RenderTargetSurface        = Backbuffer.QueryInterface <DXGI.Surface>();
                RenderTarget               = new D2D1.RenderTarget(D2DFactory, RenderTargetSurface, new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)));
                RenderTarget.AntialiasMode = D2D1.AntialiasMode.PerPrimitive;

                // Initialize debug drawings brushes
                DrawingBoundsBrush  = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 1f, 0f));
                CollisionBoxesBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 0f, 0f));

                RenderFrame = new RenderFrame(RenderTarget);

                Clock = Stopwatch.StartNew();
            }
            catch (Exception ex)
            {
                throw new DeviceInitializationException("Unable to initialize DirectX device!", ex);
            }
        }
        public RenderController(IntPtr windowHandle)
        {
            writeFactory = new SharpDX.DirectWrite.Factory();

            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device
                                                      (
                DriverType.Hardware,
                DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport
                                                      );

            device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            SwapChainDescription1 description = new SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 2,
                Scaling           = Scaling.None,
                SwapEffect        = SwapEffect.FlipSequential,
            };

            swapChain  = new SwapChain1(dxgiFactory2, device, windowHandle, ref description);
            backBuffer = Surface.FromSwapChain(swapChain, 0);

            d2dDevice  = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
            properties = new BitmapProperties1
                         (
                new SharpDX.Direct2D1.PixelFormat
                (
                    SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied
                ),
                0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw
                         );
            d2dTarget         = new Bitmap1(d2dContext, backBuffer, properties);
            d2dContext.Target = d2dTarget;

            canDraw = true;
        }
Esempio n. 26
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;
        }
Esempio n. 27
0
        public Painter(Factory factory2D, Device2D device2D, Device device3D)
            : base(device2D)
        {
            Contract.Requires(factory2D != null);
            Contract.Requires(device2D != null);
            Contract.Requires(device3D != null);

            _States = new Stack<State>();

            _Drawer = new Drawer(factory2D);

            _Device2D = device2D;
            _Device3D = device3D;
            _Factory2D = factory2D;

            device2D.Diagnostics.Register(_FrameDuration);

            _Watch = new Stopwatch();
        }
Esempio n. 28
0
        private void Initialize()
        {
            _d2dFactory   = new SharpDX.Direct2D1.Factory1();
            DWriteFactory = new SharpDX.DirectWrite.Factory1();
            WicFactory    = new ImagingFactory2();

            DevicePixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied);
            ImagePixelFormat  = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
                using (var d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>())
                    using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    {
                        _d2dDevice    = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                        DeviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
                    }

            WicImageEncoder = new ImageEncoder(WicFactory, _d2dDevice);
            DeviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Esempio n. 29
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));
        }
Esempio n. 30
0
        public DXBitmapExportContext(int width, int height, float displayScale = 1, int dpi = 72, bool disposeBitmap = true)
            : base(width, height, dpi)
        {
            _disposeBitmap = disposeBitmap;

            if (_default3DDevice == null)
            {
                _default3DDevice = new d3d.Device(DriverType.Hardware, d3d.DeviceCreationFlags.VideoSupport | d3d.DeviceCreationFlags.BgraSupport);
                // default3DDevice = new d3d.Device(DriverType.Warp,  d3d.DeviceCreationFlags.BgraSupport);

                _default3DDevice1 = _default3DDevice.QueryInterface <d3d.Device1>();
                _dxgiDevice       = _default3DDevice1.QueryInterface <dxgi.Device>(); // get a reference to DXGI device

                _device2D = new d2.Device(_dxgiDevice);

                // initialize the DeviceContext - it will be the D2D render target
                _deviceContext = new d2.DeviceContext(_device2D, d2.DeviceContextOptions.None);
            }

            // specify a pixel format that is supported by both and WIC
            _pixelFormat = new d2.PixelFormat(dxgi.Format.B8G8R8A8_UNorm, d2.AlphaMode.Premultiplied);

            // create the d2d bitmap description using default flags
            var bitmapProps = new d2.BitmapProperties1(_pixelFormat, Dpi, Dpi,
                                                       d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // create our d2d bitmap where all drawing will happen
            _bitmap = new d2.Bitmap1(_deviceContext, new Size2(width, height), bitmapProps);

            // associate bitmap with the d2d context
            _deviceContext.Target = _bitmap;
            _deviceContext.BeginDraw();
            _deviceContext.Clear(new Color4 {
                Alpha = 0, Blue = 0, Green = 0, Red = 0
            });

            _canvas = new DXCanvas(_deviceContext)
            {
                DisplayScale = displayScale
            };
        }
Esempio n. 31
0
        public DeviceResources(IntPtr handle)
        {
            Factory2D      = new Factory1_2D1();
            ImagingFactory = new ImagingFactory();
            FontFactory    = new FactoryDW();
            PixelFormat    = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied);

            var modeDescription = new ModeDescription(PixelFormat.Format);

            var swapChainDescription = new SwapChainDescription
            {
                BufferCount       = 1,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = false,
                ModeDescription   = modeDescription,
                OutputHandle      = handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(
                DriverType.Hardware,
                DeviceCreationFlags.BgraSupport,
                swapChainDescription,
                out Device device3D,
                out SwapChain swapChain
                );
            SwapChain = swapChain;

            using (var dxgiDevice = device3D.QueryInterface <SharpDX.DXGI.Device>())
            {
                Device2D = new Device2D1(Factory2D, dxgiDevice);
            }

            device3D.Dispose();

            CreateDeviceContext();
        }
Esempio n. 32
0
        /// <summary>
        /// Creates device resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            } catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
Esempio n. 33
0
        private void CleanUpDeviceIndependentResources()
        {
            if (_deviceIndependedResourcesCreated)
            {
                OnCleanUpDeviceIndependentResources();
            }



            if (_surface != null && !_surface.IsDisposed)
            {
                _surface.Dispose();
            }
            _surface = null;

            if (_dc != null && !_dc.IsDisposed)
            {
                _dc.Dispose();
            }
            _dc = null;

            if (_d2dDevice != null && !_d2dDevice.IsDisposed)
            {
                _d2dDevice.Dispose();
            }
            _d2dDevice = null;

            if (_renderTarget != null && !_renderTarget.IsDisposed)
            {
                _renderTarget.Dispose();
            }
            _renderTarget = null;

            if (_d2dFactory != null && !_d2dFactory.IsDisposed)
            {
                _d2dFactory.Dispose();
            }
            _d2dFactory = null;
        }
Esempio n. 34
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;
        }
		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);
			}
		}
Esempio n. 36
0
        public Direct2DFactories()
        {
            WICFactory = new WIC.ImagingFactory ();
            DWFactory = new DW.Factory ();

            var d3DDevice = new D3D11.Device (
                D3D.DriverType.Hardware,
                D3D11.DeviceCreationFlags.BgraSupport
            #if DEBUG
             | D3D11.DeviceCreationFlags.Debug
            #endif
            ,
                D3D.FeatureLevel.Level_11_1,
                D3D.FeatureLevel.Level_11_0,
                D3D.FeatureLevel.Level_10_1,
                D3D.FeatureLevel.Level_10_0,
                D3D.FeatureLevel.Level_9_3,
                D3D.FeatureLevel.Level_9_2,
                D3D.FeatureLevel.Level_9_1
                );

            var dxgiDevice = ComObject.As<SharpDX.DXGI.Device> (d3DDevice.NativePointer);
            var d2DDevice = new D2D1.Device (dxgiDevice);
            D2DFactory = d2DDevice.Factory;
            //_d2DDeviceContext = new D2D1.DeviceContext (d2DDevice, D2D1.DeviceContextOptions.None);
            //var dpi = DisplayDpi;
            //_d2DDeviceContext.DotsPerInch = new Size2F (dpi, dpi);
        }
Esempio n. 37
0
        /// <summary>
        /// Creates the surface-independent resources and loads the content.
        /// </summary>
        private void CreateDeviceAndLoadContent()
        {
            Debug.Assert(_graphicsDevice == null);

            var flags = GetDeviceCreationFlags();
            Debug.Assert(flags.HasFlag(DeviceCreationFlags.BgraSupport)); // mandatory for D2D support

            // initialize Direct3D11 - this is the bridge between Direct2D and control surface
            _graphicsDevice = _disposeCollector.Collect(GraphicsDevice.New(flags));
            
            // get the low-level DXGI device reference
            using (var dxgiDevice = ((Device)_graphicsDevice).QueryInterface<SharpDX.DXGI.Device>())
            {
                // create D2D device sharing same GPU driver instance
                _d2dDevice =_disposeCollector.Collect(new D2D.Device(dxgiDevice, new D2D.CreationProperties { DebugLevel = D2DDebugLevel }));

                // create D2D device context used in drawing and resource creation
                // this allows us to not recreate the resources if render target gets recreated because of size change
                _d2dDeviceContext = _disposeCollector.Collect(new D2D.DeviceContext(_d2dDevice, D2D.DeviceContextOptions.EnableMultithreadedOptimizations));
            }

            // device-independent factory used to create all DirectWrite resources
            _dwFactory = _disposeCollector.Collect(new SharpDX.DirectWrite.Factory1());

            // load scene-specific content:
            LoadContent();
        }
Esempio n. 38
0
        /// <summary>
        /// Unloads content and disposes all unmanaged resources.
        /// </summary>
        private void DisposeAndUnloadContent()
        {
            _disposeCollector.DisposeAndClear();

            _d2dDeviceContext = null;
            _d2dDevice = null;
            _dwFactory = null;
            _presenter = null;
            _graphicsDevice = null;
        }
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public 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 a solid color brush.
            solidBrush = new SolidColorBrush(d2dContext, Color.Coral);

            // Create a linear gradient brush.
            // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to,
            // NOT the geometry we will apply the brush.
            linearGradientBrush = new LinearGradientBrush(d2dContext, new LinearGradientBrushProperties()
                {
                    StartPoint = new Vector2(50, 0),
                    EndPoint = new Vector2(450, 0),
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                    {
                        new GradientStop()
                        {
                            Color = Color.Blue,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Green,
                            Position = 1,
                        }
                    }));

            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties()
                {
                    Center = new Vector2(250, 525),
                    RadiusX = 100,
                    RadiusY = 100,
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                {
                        new GradientStop()
                        {
                            Color = Color.Yellow,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Red,
                            Position = 1,
                        }
                }));
        }
Esempio n. 40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceContext"/> class using an existing <see cref="Device"/>.
 /// </summary>
 /// <param name="device">The device.</param>
 /// <param name="options">The options to be applied to the created device context.</param>
 /// <remarks>
 /// The new device context will not have a  selected target bitmap. The caller must create and select a bitmap as the target surface of the context.
 /// </remarks>
 /// <unmanaged>HRESULT ID2D1Device::CreateDeviceContext([In] D2D1_DEVICE_CONTEXT_OPTIONS options,[Out] ID2D1DeviceContext** deviceContext)</unmanaged>
 public DeviceContext(Device device, DeviceContextOptions options)
     : base(IntPtr.Zero)
 {
     device.CreateDeviceContext(options, this);
 }
Esempio n. 41
0
        private void OnEditViewportDrawSprites(Device device, SpriteBatch spriteBatch, Rectangle cliprectangle)
        {
            UiEncodingWindowSource current = _currentSource;
            if (current == null)
                return;

            try
            {
                spriteBatch.Begin();
                current.Texture.Draw(device, spriteBatch, Vector2.Zero, new Rectangle(0, 0, current.Texture.Descriptor2D.Width, current.Texture.Descriptor2D.Height), 0, cliprectangle);
                spriteBatch.End();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
Esempio n. 42
0
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath = "Input.png";
            var outputPath = "Output.png";

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var decoder = new wic.PngBitmapDecoder(imagingFactory); // we will load a PNG image
            var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading
            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // load the base image into a D2D Bitmap
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;
            var pixelWidth = inputImageSize.Width;
            var pixelHeight = inputImageSize.Height;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);
            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration

            // draw a long text to show the automatic line wrapping
            var textToDraw = "Some long text to show the drawing of preformatted "
                             + "glyphs using DirectWrite on the Direct2D surface."
                             + " Notice the automatic wrapping of line if it exceeds desired width.";

            // create the text layout - this improves the drawing performance for static text
            // as the glyph positions are precalculated
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen);

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect);
            d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush);
            d2dContext.EndDraw();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // delete the output file if it already exists
            if (System.IO.File.Exists(outputPath)) System.IO.File.Delete(outputPath);

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            // select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
Esempio n. 43
0
        public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage)
        {
            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp,
                                                              d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations);

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            var decoder = new wic.BitmapDecoder(imagingFactory,source, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //Calculate size
            var resultSize = MathUtil.ScaleWithin(inputImageSize.Width,inputImageSize.Height,maxwidth,maxheight);
            var newWidth = resultSize.Item1;
            var newHeight = resultSize.Item2;

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(newWidth, newHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            var bitmapSourceEffect = new d2.Effects.BitmapSourceEffect(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            beforeDrawImage();
            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.Transform = Matrix3x2.Scaling(new Vector2((float)(newWidth / (float)inputImageSize.Width), (float)(newHeight / (float)inputImageSize.Height)));
            d2dContext.DrawImage(bitmapSourceEffect, d2.InterpolationMode.HighQualityCubic);
            d2dContext.EndDraw();
            afterDrawImage();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var ms = new MemoryStream();

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory,ms);

            // select the image encoding format HERE
            var encoder = new wic.JpegBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(newWidth, newHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96,  0, 0, newWidth, newHeight));

            bitmapFrameEncode.Commit();
            encoder.Commit();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            formatConverter.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();
            return ms;
        }
        /// <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);
        }
		/// <summary>
		/// 清理所有正在使用的资源,并设置为 <c>null</c>。
		/// </summary>
		private void ClearResources()
		{
			if (this.d3DDevice != null)
			{
				this.d3DDevice.Dispose();
				this.d3DDevice = null;
			}
			if (this.dxgiDevice != null)
			{
				this.dxgiDevice.Dispose();
				this.dxgiDevice = null;
			}
			if (this.swapChain != null)
			{
				this.swapChain.Dispose();
				this.swapChain = null;
			}
			if (this.backBuffer != null)
			{
				this.backBuffer.Dispose();
				this.backBuffer = null;
			}
			if (this.targetBitmap != null)
			{
				this.targetBitmap.Dispose();
				this.swapChain = null;
			}
			if (this.d2DDevice != null)
			{
				this.d2DDevice.Dispose();
				this.d2DDevice = null;
			}
			if (this.d2DContext != null)
			{
				this.d2DContext.Dispose();
				this.d2DContext = null;
			}
			if (this.d2DFactory != null)
			{
				this.d2DFactory.Dispose();
				this.d2DFactory = null;
			}
			if (this.renderTarget != null)
			{
				this.renderTarget.Dispose();
				this.renderTarget = null;
			}
			if (this.wicFactory != null)
			{
				this.wicFactory.Dispose();
				this.wicFactory = null;
			}
		}
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public 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 = new SwapChain1(dxgiFactory2, device, new ComObject(window), ref description);

            // 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 SharpDX.Direct2D1.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);

            // Load bitmap images
            playerBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png");
            terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png");

            // Create hue rotation effect
            hueRotationEffect = new SharpDX.Direct2D1.Effects.HueRotation(d2dContext);

            // Create image shadow effect
            shadowEffect = new SharpDX.Direct2D1.Effects.Shadow(d2dContext);

            // Create image transform effect
            affineTransformEffect = new SharpDX.Direct2D1.Effects.AffineTransform2D(d2dContext);
            affineTransformEffect.SetInputEffect(0, shadowEffect);
            affineTransformEffect.TransformMatrix = Matrix3x2.Translation(terrainBitmap.PixelSize.Width * 0.25f, terrainBitmap.PixelSize.Height * 0.25f);

            // Create composite effect
            compositeEffect = new SharpDX.Direct2D1.Effects.Composite(d2dContext);
            compositeEffect.InputCount = 2;
            compositeEffect.SetInputEffect(0, affineTransformEffect);

            // Create tiling brush for terrain bitmap
            terrainBrush = new ImageBrush(d2dContext, terrainBitmap, new ImageBrushProperties()
            {
                ExtendModeX = ExtendMode.Wrap,
                ExtendModeY = ExtendMode.Wrap,
                SourceRectangle = new RectangleF(0, 0, terrainBitmap.Size.Width, terrainBitmap.Size.Height),
            });

            // Create rendertarget for drawing the tiling brush
            brushTarget = new Bitmap1(d2dContext, new Size2((int)(terrainBitmap.Size.Width * 10), (int)terrainBitmap.Size.Height), new BitmapProperties1()
            {
                PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                BitmapOptions = BitmapOptions.Target
            });
        }
Esempio n. 47
0
        private void OnEditViewportDrawPrimitives(Device device, RenderTarget target2D, Rectangle cliprectangle)
        {
            UiEncodingWindowSource source = _currentSource;

            WflContent info = source?.Info;
            if (info?.Header.TableType != WflHeader.LargeTable)
                return;

            int viewportX = _editViewport.X;
            int viewportY = _editViewport.Y;

            RectangleF rectangle = new RectangleF {Height = info.Header.LineHeight};

            target2D.BeginDraw();

            for (int i = 0; i < 256 * 2; i++)
            {
                if (i % 256 < 0x20)
                    continue;

                int x, y;
                info.GetOffsets(i, out x, out y);
                x -= viewportX;
                y -= viewportY;

                byte before, width, after;
                info.GetSizes(i, out before, out width, out after);

                rectangle.X = x;
                rectangle.Y = y;
                rectangle.Width = width & 0x7F;

                if (_charactersControl.CurrentMainIndices.Contains(i))
                {
                    target2D.FillRectangle(rectangle, _selectedColorBrush);

                    if (before > 0x7F)
                    {
                        rectangle.Width = (0xFF - before) + 1;
                        rectangle.X = x;
                    }
                    else
                    {
                        rectangle.Width = before;
                        rectangle.X = x - before;
                    }
                    target2D.FillRectangle(rectangle, _spacingColorBrush);

                    if (after > 0x7F)
                    {
                        rectangle.Width = (0xFF - after) + 1;
                        rectangle.X = x + (width & 0x7F) - rectangle.Width;
                    }
                    else
                    {
                        rectangle.Width = after;
                        rectangle.X = x + width & 0x7F;
                    }

                    target2D.FillRectangle(rectangle, _spacingColorBrush);
                }
                else if (source.Chars[i % 256] == 0x00)
                {
                    target2D.FillRectangle(rectangle, _notMappedColorBrush);
                }
                else
                {
                    target2D.DrawRectangle(rectangle, _gridColorBrush, 1.0f);
                }
            }

            int squareSize = info.Header.LineSpacing + info.Header.SquareDiff;
            rectangle.Height = squareSize;
            rectangle.Width = squareSize;
            for (int i = 0; i < info.AdditionalTable.Length; i++)
            {
                int value = info.AdditionalTable[i];
                if (value == 0)
                    continue;

                rectangle.Y = (value >> 8) * squareSize - viewportY;
                rectangle.X = (value & 0xFF) * squareSize - viewportX;

                if (_charactersControl.CurrentAdditionalIndices.Contains(i))
                    target2D.FillRectangle(rectangle, _selectedColorBrush);
                else if (source.Chars[i + 256] == 0x00)
                    target2D.FillRectangle(rectangle, _notMappedColorBrush);
                else
                    target2D.DrawRectangle(rectangle, _gridColorBrush, 1.0f);
            }

            target2D.EndDraw();
        }
Esempio n. 48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PrintControl"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 /// <param name="wicFactory">The WIC factory.</param>
 /// <param name="documentTarget">The document target.</param>
 /// <unmanaged>HRESULT ID2D1Device::CreatePrintControl([In] IWICImagingFactory* wicFactory,[In] IPrintDocumentPackageTarget* documentTarget,[In, Optional] const D2D1_PRINT_CONTROL_PROPERTIES* printControlProperties,[Out] ID2D1PrintControl** printControl)</unmanaged>
 public PrintControl(Device device, SharpDX.WIC.ImagingFactory wicFactory, SharpDX.ComObject documentTarget)
 {
     device.CreatePrintControl(wicFactory, documentTarget, null, this);
 }
Esempio n. 49
0
        private void OnPreviewViewportDraw(Device device, SpriteBatch spriteBatch, Rectangle cliprectangle)
        {
            UiEncodingWindowSource source = _currentSource;
            if (source == null)
                return;

            spriteBatch.Begin(SpriteSortMode.Deferred, null, _previewViewport.DxControl.RenderContainer.GraphicsDevice.SamplerStates.PointClamp, null, null, null, SharpDX.Matrix.Scaling(_scale));

            float x = 0, maxX = 0;
            float y = source.Info.Header.LineSpacing;
            int squareSize = source.Info.Header.SquareSize;
            int lineSpacing = source.Info.Header.LineHeight + source.Info.Header.LineSpacing;

            foreach (char ch in _previewText)
            {
                if (ch == '\r')
                    continue;

                if (ch == '\n')
                {
                    x = 0;
                    y += lineSpacing;
                    continue;
                }

                short index;
                if (source.Codes.TryGetValue(ch, out index))
                {
                    int ox, oy;
                    int h, w;
                    if (index < 256)
                    {
                        byte before, width, after;
                        source.Info.GetSizes(index, out before, out width, out after);
                        w = width;
                        h = source.Info.Header.LineHeight;

                        if (before > 0x7F)
                            x = Math.Max(x - (0xFF - before), 0);
                        else
                            x += before;

                        source.Info.GetOffsets(index, out ox, out oy);
                        source.Texture.Draw(device, spriteBatch, new Vector2(x, y), new Rectangle(ox, oy, w, h), 0, cliprectangle);

                        if (after > 0x7F)
                            x = Math.Max(x - (0xFF - after), 0);
                        else
                            x += after;
                    }
                    else
                    {
                        index -= 256;
                        w = h = squareSize;
                        int value = source.Info.AdditionalTable[index];
                        ox = (value & 0xFF) * squareSize;
                        oy = (value >> 8) * squareSize;
                        source.Texture.Draw(device, spriteBatch, new Vector2(x, y), new Rectangle(ox, oy, w, h), 0, cliprectangle);
                    }

                    x += w;
                    maxX = Math.Max(x, maxX);
                }
            }

            spriteBatch.End();

            double desiredWidth, desiredHeight;
            _previewViewport.GetDesiredSize(out desiredWidth, out desiredHeight);

            double newDesiredWidth = x * _scale;
            double newDesiredHeight = (y + lineSpacing) * _scale;

            if (Math.Abs(newDesiredWidth - desiredWidth) > 1 || Math.Abs(newDesiredHeight - newDesiredHeight) > 1)
                _previewViewport.SetDesiredSize(newDesiredWidth, newDesiredHeight);
        }
Esempio n. 50
0
 /// <unmanaged>HRESULT ID2D1Device::CreatePrintControl([In] IWICImagingFactory* wicFactory,[In] IPrintDocumentPackageTarget* documentTarget,[In, Optional] const D2D1_PRINT_CONTROL_PROPERTIES* printControlProperties,[Out] ID2D1PrintControl** printControl)</unmanaged>
 public PrintControl(Device device, SharpDX.WIC.ImagingFactory wicFactory, SharpDX.ComObject documentTarget, SharpDX.Direct2D1.PrintControlProperties rintControlPropertiesRef)
 {
     device.CreatePrintControl(wicFactory, documentTarget, rintControlPropertiesRef, this);
 }
        /// <summary>
        /// Creates device resources. 
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            } catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
Esempio n. 52
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));
        }