Exemple #1
0
        public void Dispose()
        {
            if (_rtv != null)
            {
                _rtv.Dispose();
            }
            _rtv = null;

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

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

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

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

            _width  = 0;
            _height = 0;
        }
 private void SetRenderTargets(DeviceContext context, ref RenderParameter parameter)
 {
     context.OutputMerger.SetTargets(parameter.DepthStencilView, parameter.RenderTargetView);
     context.Rasterizer.SetViewport(parameter.ViewportRegion);
     context.Rasterizer.SetScissorRectangle(parameter.ScissorRegion.Left, parameter.ScissorRegion.Top,
                                            parameter.ScissorRegion.Right, parameter.ScissorRegion.Bottom);
 }
        /// <summary>
        /// Clear the render targets and depth stencil
        /// </summary>
        /// <param name="context"></param>
        /// <param name="background"></param>
        public void Clear(DeviceContext1 context, Color background)
        {
            context.ClearDepthStencilView(DSV, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

            foreach (var rtv in RTVs)
                context.ClearRenderTargetView(rtv, background);
        }
 /// <summary>
 /// Sets the default render-targets
 /// </summary>
 public void SetDefaultRenderTargets(DeviceContextProxy context, bool isColorBuffer = true)
 {
     context.SetRenderTargets(isColorBuffer ? depthStencilBuffer : null, new RenderTargetView[] { isColorBuffer?colorBuffer: backBuffer });
     //context.OutputMerger.SetTargets(depthStencilBuffer, new RenderTargetView[] { isColorBuffer ? colorBuffer : backBuffer });
     context.SetViewport(0, 0, TargetWidth, TargetHeight, 0.0f, 1.0f);
     context.SetScissorRectangle(0, 0, TargetWidth, TargetHeight);
 }
Exemple #5
0
 /// <summary>
 /// Clears the render target.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="clearBackBuffer">if set to <c>true</c> [clear back buffer].</param>
 /// <param name="clearDepthStencilBuffer">if set to <c>true</c> [clear depth stencil buffer].</param>
 public void ClearRenderTarget(DeviceContext context, bool clearBackBuffer, bool clearDepthStencilBuffer)
 {
     if (CurrentRenderHost != null)
     {
         CurrentRenderHost.ClearRenderTarget(context, clearBackBuffer, clearDepthStencilBuffer);
     }
 }
Exemple #6
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);
        }
        /// <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
        }
            /// <summary>
            /// Clears the buffers with the clear-color
            /// </summary>
            /// <param name="context"></param>
            /// <param name="color"></param>
            /// <param name="clearBackBuffer"></param>
            /// <param name="clearDepthStencilBuffer"></param>
            public void ClearRenderTarget(DeviceContextProxy context, Color4 color, bool clearBackBuffer, bool clearDepthStencilBuffer)
            {
                if (clearBackBuffer)
                {
                    context.ClearRenderTargetView(colorBuffer, color);
                }

                if (clearDepthStencilBuffer)
                {
                    context.ClearDepthStencilView(depthStencilBuffer, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                }
            }
 public static void CopyToTexture(DeviceContext1 context, Texture2D source, Texture2D destination, int subResource = 0)
 {
     if (source.Description.SampleDescription.Count > 1 || source.Description.SampleDescription.Quality > 0)
     {
         context.ResolveSubresource(source, subResource, destination, 0, destination.Description.Format);
     }
     else
     {
         // Not multisampled, so just copy to the destination
         context.CopySubresourceRegion(source, subResource, null, destination, 0);
         //context.CopyResource(source, destination);
     }
 }
Exemple #10
0
 /// <summary>
 /// Set default render target to specify context.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="clear"></param>
 /// <returns>Set successful?</returns>
 public bool SetDefaultRenderTargets(DeviceContext context, bool clear = true)
 {
     if (!IsInitialized)
     {
         return(false);
     }
     renderBuffer.SetDefaultRenderTargets(context);
     if (clear)
     {
         renderBuffer.ClearRenderTarget(context, ClearColor);
     }
     return(true);
 }
Exemple #11
0
        public void Initialise(int width, int height, params SharpDX.Direct3D.FeatureLevel[] featureLevels)
        {
            // Create device
            var dev = new D3D11.Device(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.None,
                                       featureLevels);

            _device  = ComObject.As <D3D11.Device1>(dev.NativePointer);
            _context = _device.ImmediateContext1;

            ToolkitDevice = SharpDX.Toolkit.Graphics.GraphicsDevice.New(_device);

            InitSwapChain(width, height);
            RetrieveSetBuffers();
            _ready = true;
        }
        /// <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();
        }
Exemple #13
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,
            });
        }
 /// <summary>
 /// Unbind the render targets
 /// </summary>
 /// <param name="context"></param>
 public void Unbind(DeviceContext1 context)
 {
     context.OutputMerger.ResetTargets();
 }
 /// <summary>
 /// Clears the render target.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="color">The color.</param>
 public void ClearRenderTarget(DeviceContextProxy context, Color4 color)
 {
     ClearRenderTarget(context, color, true, true);
 }
Exemple #16
0
 /// <summary>
 /// Sets the default render-targets
 /// </summary>
 public void SetDefaultRenderTargets(DeviceContext context)
 {
     context.OutputMerger.SetTargets(depthStencilBufferView, colorBufferView);
     context.Rasterizer.SetViewport(0, 0, TargetWidth, TargetHeight, 0.0f, 1.0f);
     context.Rasterizer.SetScissorRectangle(0, 0, TargetWidth, TargetHeight);
 }
Exemple #17
0
 /// <summary>
 /// Initializes a new deferred context
 /// </summary>
 /// <param name="device">The device.</param>
 public DeviceContextProxy(Device device)
 {
     deviceContext = Collect(new DeviceContext(device));
     this.device   = device;
     IsDeferred    = true;
 }
        /// <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
            });
        }
 /// <summary>
 /// Clears the render target binding.
 /// </summary>
 /// <param name="context">The context.</param>
 public void ClearRenderTargetBinding(DeviceContext context)
 {
     context.OutputMerger.SetTargets(null, new RenderTargetView[0]);
 }
Exemple #20
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);
        }
 public void Bind(DeviceContext1 context)
 {
     context.OutputMerger.SetTargets(DSVReadonly, RTV);
 }
Exemple #22
0
 /// <summary>
 /// Creates the render context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 protected virtual RenderContext CreateRenderContext(DeviceContext context)
 {
     return(new RenderContext(this, context));
 }
Exemple #23
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);
        }
        public void Initialize(Device1 d3dDevice, DeviceContext1 d3dContext, int capacity = 1024)
        {

            m_d3dDevice = d3dDevice;

            m_d3dContext = d3dContext;



            m_capacity = capacity;





            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;



            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\Assets\\SpriteBatch.vs.cso");

            m_vertexShader = new VertexShader(m_d3dDevice, vertexShaderByteCode);

            m_pixelShader = new PixelShader(d3dDevice, NativeFile.ReadAllBytes(path + "\\Assets\\SpriteBatch.ps.cso"));



            // Layout from VertexShader input signature
            m_layout = new InputLayout(d3dDevice, vertexShaderByteCode, new[]
                    {

                        new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32A32_Float,0,0), 
                        new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 16, 0),
                        new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 24, 0),

                    });



            SamplerStateDescription samplerDesc = SharpDX.Direct3D11.SamplerStateDescription.Default();
            m_sampler = new SamplerState(d3dDevice, samplerDesc);





            //BlendStateDescription1 blendDesc = new BlendStateDescription1();
            //blendDesc.AlphaToCoverageEnable = true;  //set to true to get nice blending betweent sprites
            //blendDesc.IndependentBlendEnable = false;
            //blendDesc.RenderTarget[0].IsBlendEnabled = true;
            //blendDesc.RenderTarget[0].IsLogicOperationEnabled = false;
            //blendDesc.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            //blendDesc.RenderTarget[0].DestinationBlend = BlendOption.SourceAlphaSaturate;
            //blendDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
            //blendDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            //blendDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One
            //blendDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Maximum; // set to maximum to blend 2 sprites nicely over each other
            //blendDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            //m_blendStateAlpha = new BlendState1(d3dDevice, blendDesc);




            var description = BlendStateDescription1.Default();
            description.RenderTarget[0].IsBlendEnabled = true;
            description.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            description.RenderTarget[0].DestinationBlend = BlendOption.One;
            description.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha;
            description.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            description.RenderTarget[0].BlendOperation = BlendOperation.Add;
            description.RenderTarget[0].IsLogicOperationEnabled = false;
            description.RenderTarget[0].AlphaBlendOperation = BlendOperation.Maximum;
            description.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            description.AlphaToCoverageEnable = true;  //<==RT DOES NOT WORK
            description.IndependentBlendEnable = false;
            m_blendStateAlpha = new BlendState1(d3dDevice, description);




            //[BELOW] Windows RT this does not work
            //var description = BlendStateDescription1.Default();
            //description.RenderTarget[0].IsBlendEnabled = true;
            //description.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            //description.RenderTarget[0].DestinationBlend = BlendOption.SourceAlphaSaturate;
            //description.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            //description.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            //description.RenderTarget[0].BlendOperation = BlendOperation.Add;
            //description.RenderTarget[0].IsLogicOperationEnabled = false;
            //description.RenderTarget[0].AlphaBlendOperation = BlendOperation.Maximum;
            //description.AlphaToCoverageEnable = true; 
            //description.IndependentBlendEnable = false;
            //description.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            //m_blendStateAlpha = new BlendState1(d3dDevice, description);









            m_constantBufferVS = ToDispose(new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            m_constantBufferPS = ToDispose(new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));





            //=======================

            // Setup the pipeline

            //=======================

            m_vertices = ToDispose(BuildVerticesBuffer(d3dDevice, 1.0f, new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1)));

            m_vertexBufferBinding = new VertexBufferBinding(m_vertices, sizeof(float) * 10, 0);

            d3dContext.InputAssembler.SetVertexBuffers(0, m_vertexBufferBinding);



            d3dContext.InputAssembler.InputLayout = m_layout;

            d3dContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;



            d3dContext.VertexShader.SetConstantBuffer(0, m_constantBufferVS);

            d3dContext.VertexShader.Set(m_vertexShader);



            d3dContext.PixelShader.SetConstantBuffer(0, m_constantBufferPS);

            d3dContext.PixelShader.SetSampler(0, m_sampler);

            d3dContext.PixelShader.Set(m_pixelShader);



            d3dContext.OutputMerger.BlendState = m_blendStateAlpha; // m_blendStateAlpha, m_blendStateAdditive;



        }
        private void RenderParticle(Matrix viewProjection, Vector2 pos, Vector2 size, float opacity, DeviceContext1 d3dContext, ShaderResourceView srv, float rotationVelocity, RectangleF textureRegionToDraw)
        {


            // update TextureSprite transform
            Matrix position = Matrix.Translation(pos.X, -pos.Y, 0); // origin
            Matrix scale = Matrix.Scaling(size.X, size.Y, 1); // no scale modifier        
            //Matrix rotation = Matrix.RotationX(rotationVelocity);


            Matrix worldViewProjection = position;
            //if (rotationVelocity != 0) worldViewProjection = rotation * position ;
            //else worldViewProjection = position;
            worldViewProjection = worldViewProjection * scale * viewProjection;
            //worldViewProjection = worldViewProjection * viewProjection;
            worldViewProjection.Transpose();


            // Update VS/GS/PS
            d3dContext.PixelShader.SetShaderResource(0, srv);


            // Update Constant Buffer
            d3dContext.UpdateSubresource(ref worldViewProjection, m_constantBufferVS, 0);
            d3dContext.UpdateSubresource(ref opacity, m_constantBufferPS, 0);

            if (textureRegionToDraw != RectangleF.Empty) d3dContext.UpdateSubresource<float>(BuildVertices(1.0f, new Vector2(textureRegionToDraw.Left, textureRegionToDraw.Bottom), new Vector2(textureRegionToDraw.Left, textureRegionToDraw.Top), new Vector2(textureRegionToDraw.Right, textureRegionToDraw.Top), new Vector2(textureRegionToDraw.Right, textureRegionToDraw.Bottom)), m_vertices);

            // Draw
            d3dContext.Draw(12, 0);
            //d3dContext.DrawInstanced(12, 1, 0, 0);
            //d3dContext.DrawInstanced(12, m_particles.Count, 0, 0);
            //d3dContext.DrawInstanced(12, 200, 0, 0);


        }
Exemple #26
0
 /// <summary>
 /// Clears the render target.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="clearBackBuffer">if set to <c>true</c> [clear back buffer].</param>
 /// <param name="clearDepthStencilBuffer">if set to <c>true</c> [clear depth stencil buffer].</param>
 public void ClearRenderTarget(DeviceContext context, bool clearBackBuffer, bool clearDepthStencilBuffer)
 {
     renderBuffer?.ClearRenderTarget(context, ClearColor, clearBackBuffer, clearDepthStencilBuffer);
 }
        public void Dispose()
        {
            if (_rtv != null)
                _rtv.Dispose();
            _rtv = null;

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

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

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

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

            _width = 0;
            _height = 0;
        }
        protected virtual void CreateDeviceResources()
        {
            var creationFlags = D3D11.DeviceCreationFlags.BgraSupport;
            creationFlags |= D3D11.DeviceCreationFlags.Debug;

            var device = new D3D11.Device(D3D.DriverType.Hardware, creationFlags,
                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);
            _device = device.QueryInterface<D3D11.Device1>();
            _deviceContext = device.ImmediateContext.QueryInterface<D3D11.DeviceContext1>();
        }
 public void Clear(DeviceContext1 context)
 {
     context.ClearRenderTargetView(RTV, new Color(0, 0, 0, 1));
 }
        /// <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,
                        }
                }));
        }
        /// <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);
        }
        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,
                }
            }));
        }
Exemple #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceContextProxy"/> class.
 /// </summary>
 /// <param name="device">The device.</param>
 public DeviceContextProxy(Device device)
 {
     deviceContext = Collect(new DeviceContext(device));
 }
        public void Initialise(int width, int height, params SharpDX.Direct3D.FeatureLevel[] featureLevels)
        {
            // Create device
            var dev = new D3D11.Device(SharpDX.Direct3D.DriverType.Hardware, D3D11.DeviceCreationFlags.None,
                                       featureLevels);
            _device = ComObject.As<D3D11.Device1>(dev.NativePointer);
            _context = _device.ImmediateContext1;

            ToolkitDevice = SharpDX.Toolkit.Graphics.GraphicsDevice.New(_device);

            InitSwapChain(width, height);
            RetrieveSetBuffers();
            _ready = true;
        }
Exemple #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceContextProxy"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public DeviceContextProxy(DeviceContext context)
 {
     this.deviceContext = context;
 }
Exemple #36
0
 /// <summary>
 /// Muse pass immediate context for this constructor
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="device">device</param>
 public DeviceContextProxy(DeviceContext context, Device device)
 {
     deviceContext = context;
     this.device   = device;
     IsDeferred    = false;
 }
        protected void SetContextState(DeviceContext1 context)
        {
            // Tell the IA what the vertices will look like
            context.InputAssembler.InputLayout = vertexLayout;

            // Set the vertex shader constant buffers
            context.VertexShader.SetConstantBuffer(0, perObjectBuffer);
            context.VertexShader.SetConstantBuffer(1, perFrameBuffer);
            context.VertexShader.SetConstantBuffer(2, perMaterialBuffer);
            context.VertexShader.SetConstantBuffer(3, perArmatureBuffer);

            // Set the pixel shader to run
            context.VertexShader.Set(vertexShader);

            // Set the pixel shader constant buffers
            context.PixelShader.SetConstantBuffer(1, perFrameBuffer);
            context.PixelShader.SetConstantBuffer(2, perMaterialBuffer);

            // Set the pixel shader to run
            context.PixelShader.Set(pixelShader);

            context.Rasterizer.State = rsCullBack;

            // Apply the depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;
        }
 /// <summary>
 /// Clears the render target binding.
 /// </summary>
 /// <param name="context">The context.</param>
 public void ClearRenderTargetBinding(DeviceContextProxy context)
 {
     context.ClearRenderTagetBindings();
 }
 /// <summary>
 /// Bind the render targets to the OutputMerger
 /// </summary>
 /// <param name="context"></param>
 public void Bind(DeviceContext1 context)
 {
     // The empty UnorderedAccessView array is necessary, passing null results in an error
     context.OutputMerger.SetTargets(DSV, 0, new UnorderedAccessView [0], RTVs.ToArray());
 }
        /// <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
        }
Exemple #41
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,
                }
            }));
        }