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

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

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

            SampleDescription sampleDesc = new SampleDescription();

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

            SwapChainDescription1 desc = new SwapChainDescription1();

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

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

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

            _device = new RenderDeviceD3D11(_dev.ImmediateContext.NativePointer, sRGB);
        }
Ejemplo n.º 2
0
        internal void Initialise()
        {
            RemoveAndDispose(ref _d2dFactory);
            RemoveAndDispose(ref _dwFactory);

            _d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded));
            _dwFactory  = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));

            RemoveAndDispose(ref _d3dDevice);
            RemoveAndDispose(ref _d3dContext);
            RemoveAndDispose(ref _d2dDevice);
            RemoveAndDispose(ref _d2dContext);


            //var desc = CreateSwapChainDescription();

            using (var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport)) // | DeviceCreationFlags.Debug,
            {
                _d3dDevice = ToDispose(device.QueryInterface <SharpDX.Direct3D11.Device1>());
            }

            _d3dContext = ToDispose(_d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>());



            using (var dxgiDevice = _d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
            {
                _d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice));
            }
            _d2dContext = ToDispose(new DeviceContext(_d2dDevice, DeviceContextOptions.None));

            /*
             * D2Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new [] { FeatureLevel.Level_10_0 }, desc, out _device, out _swapChain);
             *
             * ToDispose(_device);
             * ToDispose(_swapChain);
             *
             * var d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory());
             *
             * Factory factory = ToDispose(_swapChain.GetParent<Factory>());
             * factory.MakeWindowAssociation(_outputHandle, WindowAssociationFlags.IgnoreAll);
             *
             * _backBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_device, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * _target = ToDispose(new RenderTarget(d2dFactory, _surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */

            InitialiseResources();

            RemoveAndDispose(ref _fpsCounter);

            _fpsCounter = new FpsCounter();
            _fpsCounter.InitialiseGraphics(this);

            OnInitialize?.Invoke(this);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create device manager objects
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateInstance()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);


            #region Create Direct3D 11.1 device and retrieve device context

            // BGRA performs better especially with Direct2D software render targets
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
#if DEBUG
            // Enble D3D device debug layer
            creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
#endif
            // Retrieve the Direct3D 11.1 device and device context
            using (var device = new SharpDX.Direct3D11.Device(DriverType.Hardware,
                                                              creationFlags,
                                                              D3DFeatureLevel))
            {
                d3dDevice = ToDispose(device.QueryInterface <Device1>());
            }

            // Get Direct3D 11.1 immediate context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <DeviceContext1>());
            #endregion

            #region Create Direct2D device and context

#if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
#endif
            // Allocate new references
            d2dFactory    = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory    = ToDispose(new SharpDX.WIC.ImagingFactory2());

            // 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));

            #endregion
        }
Ejemplo n.º 4
0
 public Direct2DText()
 {
     defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                   d3d.DeviceCreationFlags.VideoSupport
                                                   | d3d.DeviceCreationFlags.BgraSupport
                                                   | d3d.DeviceCreationFlags.None); // take out the Debug flag for better performance
     d3dDevice      = defaultDevice.QueryInterface <d3d.Device1>();                 // get a reference to the Direct3D 11.1 device
     dxgiDevice     = d3dDevice.QueryInterface <dxgi.Device>();                     // get a reference to DXGI device
     d2dDevice      = new d2.Device(dxgiDevice);                                    // initialize the D2D device
     imagingFactory = new wic.ImagingFactory2();                                    // initialize the WIC factory
     d2dContext     = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);
     dwFactory      = new dw.Factory();
     d2dBitmapProps = new BitmapProperties1(d2PixelFormat, dpi, dpi, BitmapOptions.Target | BitmapOptions.CannotDraw);
 }
Ejemplo n.º 5
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();
        }
Ejemplo n.º 6
0
        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);
            }
        }
Ejemplo n.º 7
0
        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;
        }
Ejemplo n.º 8
0
        /// <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.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            context = device.ImmediateContext.QueryInterface<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);

            // Create the texture and render target that will hold our backbuffer.
            Texture2D backBufferTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            backBuffer = new RenderTargetView(device, backBufferTexture);

            backBufferTexture.Dispose();
        }
Ejemplo n.º 9
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;
        }
Ejemplo n.º 10
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
            };
        }
        /// <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
            });
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

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

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

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

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

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush = new SolidColorBrush(d2dContext, Color.Black);
        }
Ejemplo n.º 13
0
        protected void InitialiseResources()
        {
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _surface);
            RemoveAndDispose(ref _target);
            _d2dContext.Target = null;

            var desc = CreateSwapChainDescription();

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

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

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

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

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

            _d3dContext.Rasterizer.SetViewport(viewport);

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


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

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

            /*_backBuffer = ToDispose(Resource.FromSwapChain<Texture2D>(_swapChain, 0));
             * _renderTargetView = ToDispose(new RenderTargetView(_d3dDevice, _backBuffer));
             * _surface = ToDispose(_backBuffer.QueryInterface<Surface>());
             *
             * using (var dxgiBackBuffer = _swapChain.GetBackBuffer<Surface>(0))
             *  _target = ToDispose(new RenderTarget(_d2dFactory, dxgiBackBuffer, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))));
             */
            OnInitialize?.Invoke(this);
        }
Ejemplo n.º 14
0
        public SharpRender(RenderForm form)
        {
            this.form = form;
            var adapters = new DXGI.Factory1().Adapters;

            DXGI.Adapter myadapter = null;
            for (int i = 0; i < adapters.Length; ++i)
            {
                Logger.Log(string.Format("Adapter Found: [{0}] " +
                                         "{1}\tDeviceId={5}" +
                                         "{1}\tLuid={6}" +
                                         "{1}\tVendorId={10}" +
                                         "{1}\tSubsystemId={9}" +
                                         "{1}\tDescription={4}" +
                                         "{1}\tRevision={7}" +
                                         "{1}\tDedicatedSystemMemory={2}" +
                                         "{1}\tDedicatedVideoMemory={3}" +
                                         "{1}\tSharedSystemMemory={8}" +
                                         "",
                                         i, Environment.NewLine,
                                         adapters[i].Description.DedicatedSystemMemory,
                                         adapters[i].Description.DedicatedVideoMemory, adapters[i].Description.Description,
                                         adapters[i].Description.DeviceId, adapters[i].Description.Luid,
                                         adapters[i].Description.Revision, adapters[i].Description.SharedSystemMemory,
                                         adapters[i].Description.SubsystemId, adapters[i].Description.VendorId));
                var outputs = adapters[i].Outputs;
                for (int j = 0; j < outputs.Length; ++j)
                {
                    Logger.Log(string.Format("Output Found: [{0},{1}]" +
                                             "{2}\tDeviceName={4}" +
                                             "{2}\tIsAttachedToDesktop={5}" +
                                             "{2}\tMonitorHandle={6}" +
                                             "{2}\tDesktopBounds={3}" +
                                             "{2}\tRotation={7}" +
                                             "",
                                             i, j, Environment.NewLine,
                                             (Rectangle)outputs[j].Description.DesktopBounds,
                                             outputs[j].Description.DeviceName,
                                             outputs[j].Description.IsAttachedToDesktop,
                                             outputs[j].Description.MonitorHandle,
                                             outputs[j].Description.Rotation));
                }
                if (outputs.Length > 0 && myadapter == null)
                {
                    myadapter = adapters[i];
                }
            }
            d3device = new Direct3D11.Device(
                myadapter,
                Direct3D11.DeviceCreationFlags.BgraSupport);
            //SharpDX.Direct3D.DriverType.Hardware,
            //Direct3D11.DeviceCreationFlags.BgraSupport |
            //Direct3D11.DeviceCreationFlags.Debug);
            defDevice    = d3device.QueryInterface <Direct3D11.Device1>();
            dxgiDevice2  = defDevice.QueryInterface <DXGI.Device2>();
            dxgiAdapter  = dxgiDevice2.Adapter;
            dxgiFactory2 = dxgiAdapter.GetParent <DXGI.Factory2>();
            var scDescription = new DXGI.SwapChainDescription1()
            {
                Width             = 0,
                Height            = 0,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Stereo            = false,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = DXGI.Usage.RenderTargetOutput,
                BufferCount       = 2,
                Scaling           = DXGI.Scaling.None,
                SwapEffect        = DXGI.SwapEffect.FlipSequential
            };

            swapChain = new DXGI.SwapChain1(dxgiFactory2, defDevice, form.Handle,
                                            ref scDescription, null, null);
            d2dDevice  = new Direct2D1.Device(dxgiDevice2);
            d2dContext = new Direct2D1.DeviceContext(d2dDevice,
                                                     Direct2D1.DeviceContextOptions.None);
            fac = new Direct2D1.Factory(Direct2D1.FactoryType.SingleThreaded);
            var dpi          = fac.DesktopDpi;
            var bMProperties = new Direct2D1.BitmapProperties1(
                new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm,
                                          Direct2D1.AlphaMode.Premultiplied),
                dpi.Width, dpi.Height,
                Direct2D1.BitmapOptions.CannotDraw | Direct2D1.BitmapOptions.Target);

            bb                = swapChain.GetBackBuffer <DXGI.Surface>(0);
            target            = new Direct2D1.Bitmap1(d2dContext, bb, bMProperties);
            d2dContext.Target = target;
            wrFactory         = new DirectWrite.Factory();

            brush = new Direct2D1.SolidColorBrush(d2dContext, c(Color.White));
        }
Ejemplo n.º 15
0
            private void SetupScreenBuffers()
            {
                width  = (int)window.Bounds.Width;
                height = (int)window.Bounds.Height;

                // If the swap chain already exists, resize it.
                if (swapChain != null)
                {
                    swapChain.ResizeBuffers(2, width, height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);
                }
                // Otherwise, create a new one.
                else
                {
                    // SwapChain description
                    var desc = new SwapChainDescription1
                    {
                        // Automatic sizing
                        Width             = width,
                        Height            = height,
                        Format            = Format.B8G8R8A8_UNorm,
                        Stereo            = false,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = Usage.BackBuffer | Usage.RenderTargetOutput,
                        // Use two buffers to enable flip effect.
                        BufferCount = 2,
                        Scaling     = Scaling.None,
                        SwapEffect  = SwapEffect.FlipSequential,
                    };

                    // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                    // First, retrieve the underlying DXGI Device from the D3D Device.
                    // Creates the swap chain
                    using (var dxgiDevice2 = graphicsDevice.QueryInterface <Device2>())
                        using (Adapter dxgiAdapter = dxgiDevice2.Adapter)
                            using (var dxgiFactory2 = dxgiAdapter.GetParent <Factory2>())
                            {
                                // Creates a SwapChain from a CoreWindow pointer
                                using (var comWindow = new ComObject(window))
                                    swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(graphicsDevice, comWindow, ref desc, null);

                                // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                                // latency and ensures that the application will only render after each VSync, minimizing
                                // power consumption.
                                dxgiDevice2.MaximumFrameLatency = 1;
                            }
                }

                // Obtain the backbuffer for this window which will be the final 3D rendertarget.
                backBuffer = ToDispose(Resource.FromSwapChain <Texture2D>(swapChain, 0));
                {
                    // Create a view interface on the rendertarget to use on bind.
                    renderTargetView = ToDispose(new RenderTargetView(graphicsDevice, backBuffer));
                }

                // Create a viewport descriptor of the full window size.
                var viewport = new Viewport(0, 0, width, height, 0.0f, 1.0f);

                // Set the current viewport using the descriptor.
                graphicsDevice.ImmediateContext.Rasterizer.SetViewport(viewport);
            }
Ejemplo n.º 16
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

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

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

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

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

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

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush       = new SolidColorBrush(d2dContext, Color.Black);
        }
Ejemplo n.º 17
0
        void InitText(SwapChain3 tempSwapChain)
        {
            init       = true;
            device     = tempSwapChain.GetDevice <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();
            var texture2d = tempSwapChain.GetBackBuffer <Texture2D>(0);

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

            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            SharpDX.Direct2D1.BitmapProperties1 properties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                  SharpDX.Direct2D1.AlphaMode.Premultiplied),
                96, 96, SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            Surface backBuffer = tempSwapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, new Size2(800, 600), properties);

            solidBrush = new SharpDX.Direct2D1.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 SharpDX.Direct2D1.LinearGradientBrush(d2dContext, new SharpDX.Direct2D1.LinearGradientBrushProperties()
            {
                StartPoint = new Vector2(50, 0),
                EndPoint   = new Vector2(450, 0),
            },
                                                                            new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Blue,
                    Position = 0,
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Green,
                    Position = 1,
                }
            }));

            SharpDX.Direct2D1.RadialGradientBrushProperties rgb = new SharpDX.Direct2D1.RadialGradientBrushProperties()
            {
                Center  = new Vector2(250, 525),
                RadiusX = 100,
                RadiusY = 100,
            };
            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new SharpDX.Direct2D1.RadialGradientBrush(d2dContext, ref rgb
                                                                            ,
                                                                            new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Yellow,
                    Position = 0,
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Red,
                    Position = 1,
                }
            }));
        }
Ejemplo n.º 18
0
        /// <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);

            playerBitmap  = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png");
            terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png");
            terrainBrush  = new BitmapBrush1(d2dContext, terrainBitmap, new BitmapBrushProperties1()
            {
                ExtendModeX = ExtendMode.Wrap,
                ExtendModeY = ExtendMode.Wrap,
            });
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates the size dependent drawing resources.
        /// </summary>
        private void CreateSizeDependentResources()
        {
            _d2dContext.Target = null;

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

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

            // Generate a swap chain for our window based on the specified description.
            if (_swapChain == null)
            {
                // Query for the adapter and more advanced DXGI objects.
                using (var dxgiDevice2 = _device.QueryInterface <SharpDX.DXGI.Device2>())
                {
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                    {
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            // Description for our swap chain settings.
                            SwapChainDescription1 description = new SwapChainDescription1()
                            {
                                Width             = _width * (int)_scale,
                                Height            = _height * (int)_scale,
                                Format            = Format.B8G8R8A8_UNorm,
                                Stereo            = false,
                                SampleDescription = new SampleDescription(1, 0),
                                Usage             = Usage.RenderTargetOutput,
                                BufferCount       = 2,
                                Scaling           = Scaling.Stretch,
                                SwapEffect        = SwapEffect.FlipSequential,
                                Flags             = SwapChainFlags.AllowModeSwitch
                            };

                            _swapChain = new SwapChain1(dxgiFactory2, _device, _form.Handle, ref description);
                        }
                    }
                }
            }
            else
            {
                _swapChain.ResizeBuffers(0, _width * (int)_scale, _height * (int)_scale, Format.B8G8R8A8_UNorm, SwapChainFlags.AllowModeSwitch);
            }

            Size2F dpi = _d2dFactory.DesktopDpi;

            // 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),
                dpi.Height,
                dpi.Width,
                BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            _backBuffer = Surface.FromSwapChain(_swapChain, 0);
            _d2dTarget  = new Bitmap1(_d2dContext, _backBuffer, properties);

            _d2dContext.Target = _d2dTarget;
        }
Ejemplo n.º 20
0
        /// <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,
                }
            }));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Renderer" /> class.
        /// </summary>
        /// <param name="gameEngine">The game engine.</param>
        /// <param name="form">The form.</param>
        /// <param name="width">The primary width of the view in pixels.</param>
        /// <param name="height">The primary height of the view in pixels.</param>
        public Renderer(IGameEngine gameEngine, GameForm form, int width, int height)
        {
            if (gameEngine == null)
            {
                throw new ArgumentNullException(nameof(gameEngine));
            }

            if (form == null)
            {
                throw new ArgumentNullException(nameof(form));
            }

            _form   = form;
            _resize = false;
            _scale  = 1.0f;
            _width  = width;
            _height = height;

            _dwFactory = new SharpDX.DirectWrite.Factory();
            InitFonts();

            // 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.
            using (var dxgiDevice2 = _device.QueryInterface <SharpDX.DXGI.Device2>())
            {
                _d2dFactory = new SharpDX.Direct2D1.Factory2(SharpDX.Direct2D1.FactoryType.SingleThreaded);

                // Get the default Direct2D device and create a context.
                using (var d2dDevice = new SharpDX.Direct2D1.Device1(_d2dFactory, dxgiDevice2))
                {
                    _d2dContext = new SharpDX.Direct2D1.DeviceContext1(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);
                }
            }

            CreateSizeDependentResources();

            _d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Aliased;
            _d2dContext.AntialiasMode     = AntialiasMode.Aliased;
            _d2dContext.UnitMode          = UnitMode.Pixels;

            _hudYellow     = new SolidColorBrush(_d2dContext, new Color4(1.0f, 1.0f, 0.0f, 1.0f));
            _hudWhite      = new SolidColorBrush(_d2dContext, new Color4(1.0f, 1.0f, 1.0f, 1.0f));
            _hudTextFormat = new TextFormat(_dwFactory, "Sonic Genesis/Mega Drive Font", _fontCollection, FontWeight.Normal, FontStyle.Normal, FontStretch.Normal, 14);

            // init game stuff
            _game = gameEngine;

            _texResMan    = new TextureResourceManager(gameEngine, _d2dContext);
            _spriteResMan = new SpriteResourceManager(gameEngine, _d2dContext);

            // get the services
            _mapService       = _game.GetService <IMapService>();
            _varService       = _game.GetService <IVariableService>();
            _entityService    = _game.GetService <IEntityService>();
            _renderService    = _game.GetService <IRenderService>();
            _collisionService = _game.GetService <ICollisionService>();

            _varShowCollisionMaps  = _varService.GetVar <bool>("r_showcollisionmaps");
            _varShowTileFrames     = _varService.GetVar <bool>("r_showtileframes");
            _varShowEntityOrigins  = _varService.GetVar <bool>("r_showentityorigins");
            _varShowTraceLines     = _varService.GetVar <bool>("r_showtracelines");
            _varShowCollisionBoxes = _varService.GetVar <bool>("r_showcollisionboxes");

            _rc = new RenderContext();

            _spriteRenderList = new List <Animatable>(25);
        }
Ejemplo n.º 22
0
        private static void CreateDevices(int graphicsAdapter)
        {
            var deviceCreationFlags = DeviceCreationFlags.BgraSupport;

#if DEBUG
            deviceCreationFlags |= DeviceCreationFlags.Debug;
#endif

            Logger.Info("Attempting to create device.");

            var adapter = Factory.GetAdapter(graphicsAdapter);

            var levels = new[]
            {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_9_3
            };

            var device = new SharpDX.Direct3D11.Device(adapter, deviceCreationFlags, levels)
            {
                DebugName = adapter.Description.Description
            };

            Logger.Info(
                $"GPU{graphicsAdapter}: {device.DebugName} ({((long)adapter.Description.DedicatedVideoMemory).ToPrettySize()} VRAM)");

            Device           = device.QueryInterface <DeviceD3D>();
            Device.DebugName = device.DebugName;
            Logger.Info("D3D Device created.");
            if (deviceCreationFlags.HasFlag(DeviceCreationFlags.Debug))
            {
                DeviceDebug = new DeviceDebug(Device);
                Logger.Info("Debug device created.");
            }

            DxgiDevice = Device.QueryInterface <Device>();
            Context    = Device.ImmediateContext;

            Device2D = new DeviceD2D(Factory2D, DxgiDevice);

            Context2D = new ContextD2D(Device2D,
                                       DeviceContextOptions.EnableMultithreadedOptimizations)
            {
                TextAntialiasMode =
                    RenderSettings.UseClearTypeRendering
                        ? TextAntialiasMode.Cleartype
                        : (RenderSettings.GuiAntiAliasing ? TextAntialiasMode.Grayscale : TextAntialiasMode.Aliased),
                AntialiasMode = RenderSettings.GuiAntiAliasing ? AntialiasMode.PerPrimitive : AntialiasMode.Aliased,
                UnitMode      = UnitMode.Pixels
            };
            Logger.Info("D2D Device created.");

            Logger.Info("Filling out DebugSettings GPU info.");
            DebugSettings.FillGpuInfo(adapter);

#if DEBUG
            try
            {
                DeviceDebug = new DeviceDebug(Device);
                Logger.Info("Debug device created.");
            }
            catch (SharpDXException)
            {
                Logger.Warn("DeviceDebug not supported.");
            }
#endif

            Logger.Info("Renderer initialized.");
        }
        /// <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,
                        }
                }));
        }
Ejemplo n.º 24
0
 public Factory2 GetFactory2()
 {
     using (var dxgi = device1.QueryInterface <SharpDX.DXGI.Device2>())
         using (var adapter = dxgi.Adapter)
             return(adapter.GetParent <Factory2>());
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D11"/> class.
        /// </summary>
        /// <param name="dxgiAdapter">The tasrget adapter.</param>
        /// <param name="debugEnabled">Is debug mode enabled?</param>
        internal DeviceHandlerD3D11(DXGI.Adapter1 dxgiAdapter, bool debugEnabled)
        {
            m_dxgiAdapter = dxgiAdapter;

            // Define possible create flags
            D3D11.DeviceCreationFlags createFlagsBgra = D3D11.DeviceCreationFlags.BgraSupport;
            D3D11.DeviceCreationFlags createFlags     = D3D11.DeviceCreationFlags.None;
            if (debugEnabled)
            {
                createFlagsBgra |= D3D11.DeviceCreationFlags.Debug;
                createFlags     |= D3D11.DeviceCreationFlags.Debug;
            }

            // Define all steps on which we try to initialize Direct3D
            List <Tuple <D3D.FeatureLevel, D3D11.DeviceCreationFlags, HardwareDriverLevel> > initParameterQueue =
                new List <Tuple <D3D.FeatureLevel, D3D11.DeviceCreationFlags, HardwareDriverLevel> >();

            // Define all trys for hardware initialization
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_11_1, createFlagsBgra, HardwareDriverLevel.Direct3D11));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_11_0, createFlagsBgra, HardwareDriverLevel.Direct3D11));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_10_0, createFlagsBgra, HardwareDriverLevel.Direct3D10));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_3, createFlagsBgra, HardwareDriverLevel.Direct3D9_3));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_2, createFlagsBgra, HardwareDriverLevel.Direct3D9_2));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_1, createFlagsBgra, HardwareDriverLevel.Direct3D9_1));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_10_0, createFlags, HardwareDriverLevel.Direct3D10));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_3, createFlags, HardwareDriverLevel.Direct3D9_3));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_2, createFlags, HardwareDriverLevel.Direct3D9_2));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_1, createFlags, HardwareDriverLevel.Direct3D9_1));

            // Try to create the device, each defined configuration step by step
            foreach (Tuple <D3D.FeatureLevel, D3D11.DeviceCreationFlags, HardwareDriverLevel> actInitParameters in initParameterQueue)
            {
                D3D.FeatureLevel          featureLevel    = actInitParameters.Item1;
                D3D11.DeviceCreationFlags direct3D11Flags = actInitParameters.Item2;
                HardwareDriverLevel       actDriverLevel  = actInitParameters.Item3;

                try
                {
                    // Try to create the device using current parameters
                    using (D3D11.Device device = new D3D11.Device(dxgiAdapter, direct3D11Flags, featureLevel))
                    {
                        m_device1 = device.QueryInterface <D3D11.Device1>();
                        m_device3 = CommonTools.TryExecute(() => m_device1.QueryInterface <D3D11.Device3>());
                        if (m_device3 != null)
                        {
                            m_immediateContext3 = m_device3.ImmediateContext3;
                        }
                    }

                    // Device successfully created, save all parameters and break this loop
                    m_featureLevel  = featureLevel;
                    m_creationFlags = direct3D11Flags;
                    m_driverLevel   = actDriverLevel;
                    break;
                }
                catch (Exception) { }
            }

            // Throw exception on failure
            if (m_device1 == null)
            {
                throw new SeeingSharpGraphicsException("Unable to initialize d3d11 device!");
            }

            // Get immediate context from the device
            m_immediateContext = m_device1.ImmediateContext;
        }
        /// <summary>
        /// Creates device manager objects
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateInstances()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);
            RemoveAndDispose(ref d2dFactory);
            RemoveAndDispose(ref dwriteFactory);
            RemoveAndDispose(ref wicFactory);

            #region Create Direct3D 11.1 device and retrieve device context

            // Bgra performs better especially with Direct2D software
            // render targets
            var creationFlags = DeviceCreationFlags.BgraSupport;
            #if DEBUG
            // Enable D3D device debug layer
            creationFlags |= DeviceCreationFlags.Debug;
            #endif

            // Retrieve the Direct3D 11.1 device and device context
            using (var device = new Device(DriverType.Hardware, creationFlags, Direct3DFeatureLevels))
            {
                d3dDevice = ToDispose(device.QueryInterface<Device1>());
            }

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

            #region Create Direct2D device and context

            #if DEBUG
            var debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
            #else
            var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
            #endif

            // Allocate new references
            d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel));
            dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared));
            wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2());

            // 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));
            #endregion
        }