Ejemplo n.º 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;
        }
Ejemplo n.º 2
0
 internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Ejemplo n.º 3
0
        public BackBuffer(Factory2 factory, Device1 device1, RenderForm renderForm)
        {
            swapChainDescription1 = new SwapChainDescription1()
            {
                Width             = renderForm.ClientSize.Width,
                Height            = renderForm.ClientSize.Height,
                Format            = Format.R8G8B8A8_UNorm,
                Stereo            = false,
                SampleDescription = new SampleDescription(4, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                SwapEffect        = SwapEffect.Discard,
                Flags             = SwapChainFlags.AllowModeSwitch,
            };

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

            BackBufferTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0);
        }
Ejemplo n.º 4
0
        public void CreateDevice(object hostControl, DeviceCreationFlags flags)
        {
            OnDeviceChangeBegin(this, EventArgs.Empty);
            // SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription = new ModeDescription(PreferredBackBufferWidth, PreferredBackBufferHeight, new Rational(60, 1),
                                                      PreferredBackBufferFormat),
                IsWindowed        = true,
                OutputHandle      = (IntPtr)hostControl,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            IsDebugMode = flags.HasFlag(DeviceCreationFlags.Debug);
            var device = ToDispose(new Device(DriverType.Hardware, flags, PreferredGraphicsProfile[0]));

            this.device = ToDispose(device.QueryInterface <Device1>());

            var factory = ToDispose(new Factory1());

            swapChain = ToDispose(new SwapChain(factory, device, desc));
            factory.MakeWindowAssociation(swapChain.Description.OutputHandle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            backBuffer       = ToDispose(Resource.FromSwapChain <Texture2D>(swapChain, 0));
            renderTargetView = ToDispose(new RenderTargetView(device, backBuffer));
            context          = ToDispose(this.device.ImmediateContext.QueryInterface <DeviceContext1>());
            OnDeviceCreated(this, EventArgs.Empty);
            OnDeviceChangeEnd(this, EventArgs.Empty);
        }
Ejemplo n.º 5
0
            protected virtual SampleDescription GetMSAASampleDescription()
            {
                var sampleCount   = 1;
                var sampleQuality = 0;

#if MSAA
                if (MSAA != MSAALevel.Disable)
                {
                    do
                    {
                        var newSampleCount   = sampleCount * 2;
                        var newSampleQuality = Device.CheckMultisampleQualityLevels(Format.B8G8R8A8_UNorm, newSampleCount) - 1;

                        if (newSampleQuality < 0)
                        {
                            break;
                        }

                        sampleCount   = newSampleCount;
                        sampleQuality = newSampleQuality;
                        if (sampleCount == (int)MSAA)
                        {
                            break;
                        }
                    } while (sampleCount < 32);
                }
#endif
                return(new SampleDescription(sampleCount, sampleQuality));
            }
Ejemplo n.º 6
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.º 7
0
        public void Shutdown()
        {
            if (_deviceContext != null)
            {
                _deviceContext.Dispose();
                _deviceContext = null;
            }

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

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

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

            if (_default3DDevice != null)
            {
                _default3DDevice.Dispose();
                _default3DDevice = null;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     指定したサイズの、空の描画可能画像を作成する。
        /// </summary>
        public 描画可能画像(SharpDX.Direct3D11.Device1 d3dDevice1, SharpDX.Direct2D1.DeviceContext d2dDeviceContext, Size2F サイズ, BindFlags bindFlags = BindFlags.ShaderResource)
            : base(d3dDevice1, サイズ, bindFlags | BindFlags.RenderTarget)
        {
            //using var _ = new LogBlock( Log.現在のメソッド名 );

            this.Bitmap = this._作成したテクスチャとデータを共有するビットマップターゲットを作成する(d2dDeviceContext);
        }
Ejemplo n.º 9
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.º 10
0
        private SharpDX.Direct3D11.Buffer BuildVerticesBuffer(SharpDX.Direct3D11.Device1 d3dDevice, float opacity, Vector2 uvbl, Vector2 uvtl, Vector2 uvtr, Vector2 uvbr)
        {
            // Instantiate Vertex buffer from vertex data
            var vertices = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, BuildVertices(opacity, uvbl, uvtl, uvtr, uvbr));


            //vertexBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0);
            return(vertices);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Unloads all resources.
        /// </summary>
        public void UnloadResources()
        {
            m_immediateContext  = CommonTools.DisposeObject(m_immediateContext);
            m_immediateContext3 = CommonTools.DisposeObject(m_immediateContext3);
            m_device1           = CommonTools.DisposeObject(m_device1);
            m_device3           = CommonTools.DisposeObject(m_device3);

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

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

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

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

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

            try
            {
                return(new Bitmap(
                           d2dDeviceContext,
                           new Size2(captureTexture.Description.Width, captureTexture.Description.Height),
                           new DataPointer(dataStream.DataPointer, (int)dataStream.Length),
                           dataRect.Pitch,
                           new BitmapProperties(
                               new PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore),
                               d2dDeviceContext.DotsPerInch.Width,
                               d2dDeviceContext.DotsPerInch.Width)));
            }
            finally
            {
                dxgiSurface.Unmap();
            }
        }
Ejemplo n.º 13
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.º 14
0
 //1 Sided VERTEX BUFFER
 internal SharpDX.Direct3D11.Buffer GenerateVertexBuffer1Sided(SharpDX.Direct3D11.Device1 d3dDevice, float thicknessToUse)
 {
     return(SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, new[]
     {
         // 3D coordinates              UV Texture coordinates
         -1.0f, -1.0f, -thicknessToUse, 1.0f, 0.0f, 1.0f,                           // Front
         -1.0f, 1.0f, -thicknessToUse, 1.0f, 0.0f, 0.0f,
         1.0f, 1.0f, -thicknessToUse, 1.0f, 1.0f, 0.0f,
         -1.0f, -1.0f, -thicknessToUse, 1.0f, 0.0f, 1.0f,
         1.0f, 1.0f, -thicknessToUse, 1.0f, 1.0f, 0.0f,
         1.0f, -1.0f, -thicknessToUse, 1.0f, 1.0f, 1.0f,
     }));
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates the renderer instance.
        /// </summary>
        /// <param name="device">DirectX device.</param>
        /// <param name="context">DirectX context.</param>
        public Renderer(SharpDX.Direct3D11.Device1 device, DeviceContext1 context)
        {
            this.device         = device;
            this.context        = context;
            this.cachedTextures = new Dictionary <int, Texture>();
            this.cachedModel    = null;
            this.frustum        = new BoundingFrustum();

            this.World = this.View = this.Projection = Matrix.Identity;

            // TODO: ToDispose
            this.constantBuffer = new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
        }
Ejemplo n.º 16
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.º 17
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.º 18
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="description"></param>
 /// <param name="device"></param>
 /// <param name="manager"></param>
 public Technique(TechniqueDescription description, Device device, IEffectsManager manager)
 {
     Name           = description.Name;
     EffectsManager = manager;
     Layout         = manager.ShaderManager.RegisterInputLayout(description.InputLayoutDescription);
     if (description.PassDescriptions != null)
     {
         foreach (var desc in description.PassDescriptions)
         {
             var pass = new Lazy <ShaderPass>(() => { return(Collect(new ShaderPass(desc, manager))); }, true);
             passDict.Add(desc.Name, pass);
             passList.Add(pass);
         }
     }
 }
Ejemplo n.º 19
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;
        }
Ejemplo n.º 20
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.º 21
0
        public static SharpDX.Direct3D11.Buffer CreateBuffer <T>(SharpDX.Direct3D11.Device1 device, BindFlags bindFlags, params T[] items)
            where T : struct
        {
            var len    = Utilities.SizeOf(items);
            var stream = new DataStream(len, true, true);

            foreach (var item in items)
            {
                stream.Write(item);
            }
            stream.Position = 0;
            var buffer = new SharpDX.Direct3D11.Buffer(device, stream, len, ResourceUsage.Default,
                                                       bindFlags, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            return(buffer);
        }
Ejemplo n.º 22
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.º 23
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();
        }
        /// <summary>
        /// Function to retrieve the video modes for an output.
        /// </summary>
        /// <param name="D3DDevice">D3D device for filtering supported display modes.</param>
        /// <param name="giOutput">Output that contains the video modes.</param>
        /// <returns>A list of display compatible full screen video modes.</returns>
        private static IEnumerable <ModeDescription1> GetVideoModes(D3D11.Device1 D3DDevice, Output1 giOutput)
        {
            Format[] formats = ((Format[])Enum.GetValues(typeof(Format)))
                               .Where(item => (D3DDevice.CheckFormatSupport(item) & D3D11.FormatSupport.Display) == D3D11.FormatSupport.Display)
                               .ToArray();

            IEnumerable <ModeDescription1> result = Enumerable.Empty <ModeDescription1>();

            // Test each format for display compatibility.
            return(formats.Aggregate(result,
                                     (current, format) =>
                                     current.Concat(giOutput.GetDisplayModeList1(format,
                                                                                 DisplayModeEnumerationFlags.Scaling |
                                                                                 DisplayModeEnumerationFlags.Stereo |
                                                                                 DisplayModeEnumerationFlags.DisabledStereo |
                                                                                 DisplayModeEnumerationFlags.Interlaced)
                                                    .Where(item => (D3DDevice.CheckFormatSupport(format) & D3D11.FormatSupport.Display) == D3D11.FormatSupport.Display))));
        }
Ejemplo n.º 25
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.º 26
0
        public NativeDevice()
        {
#if DEBUG
            var flags = DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport;
#else
            var flags = DeviceCreationFlags.BgraSupport;
#endif
            var device11_0 = new Device(DriverType.Hardware, flags, FeatureLevel.Level_11_1);

            device1 = device11_0.QueryInterfaceOrNull <Device1>();

            if (device1 == null)
            {
                throw new NotSupportedException("SharpDX.Direct3D11.Device1 is not supported");
            }


            //Release D3D11.0 Device
            Utilities.Dispose(ref device11_0);
        }
Ejemplo n.º 27
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
            };
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Loads a new Texture from a file on disk.
        /// </summary>
        /// <param name="device">DirectX device.</param>
        /// <param name="filename">Path to the texture file.</param>
        /// <returns></returns>
        public static async Task <Texture> LoadFromFile(SharpDX.Direct3D11.Device1 device, string filename)
        {
            Texture newTexture = new Texture();

            newTexture.texturePath = filename;
            NativeFileStream fileStream = new NativeFileStream(filename, NativeFileMode.Open, NativeFileAccess.Read);

            using (BinaryReader reader = new BinaryReader(fileStream))
            {
                int width  = reader.ReadInt32();
                int height = reader.ReadInt32();

                int    dataLength = reader.ReadInt32();
                byte[] data       = new byte[dataLength];

                data = reader.ReadBytes(dataLength);

                DataStream stream = new DataStream(dataLength, false, true);
                stream.Write(data, 0, dataLength);

                newTexture.texture = new Texture2D(device, new Texture2DDescription()
                {
                    ArraySize         = 1,
                    BindFlags         = BindFlags.ShaderResource,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.BC3_UNorm,
                    Height            = height,
                    MipLevels         = 1,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Immutable,
                    Width             = width,
                }, new DataRectangle(stream.DataPointer, width * 4));

                newTexture.resourceView = new ShaderResourceView(device, newTexture.texture);
            }

            return(newTexture);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="description"></param>
 /// <param name="device"></param>
 /// <param name="manager"></param>
 public Technique(TechniqueDescription description, Device device, IEffectsManager manager)
 {
     Description = description;
     Name = description.Name;
     EffectsManager = manager;
     if (description.InputLayoutDescription != null && description.PassDescriptions != null)
     {
         if (description.PassDescriptions != null)
         {
             foreach (var desc in description.PassDescriptions)
             {
                 if (desc.InputLayoutDescription == null)
                 {
                     desc.InputLayoutDescription = description.InputLayoutDescription;
                 }
                 var pass = new Lazy<ShaderPass>(() => { return new ShaderPass(desc, manager); }, true);
                 passDict.Add(desc.Name, pass);
                 passList.Add(pass);
             }
         }
     }
 }
Ejemplo n.º 30
0
 /// <summary>
 ///   Constructs a new <see cref = "T:SharpDX.Direct3D11.BlendState1" /> based on the specified description.
 /// </summary>
 /// <param name = "device">The device with which to associate the state object.</param>
 /// <param name = "description">The state description.</param>
 /// <returns>The newly created object.</returns>
 public BlendState1(Device1 device, SharpDX.Direct3D11.BlendStateDescription1 description)
     : base(IntPtr.Zero)
 {
     device.CreateBlendState1(ref description, this);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Create resources that depend on the Direct3D device.
        /// </summary>
        /// <param name="deviceManager">The <see cref="DeviceManager"/> associated with this instance.</param>
        private void CreateDeviceResources(Tesseract gameEngine)
        {
            // Release any pre-existing resources
            RemoveAndDispose(ref PerFrameBuffer);
            RemoveAndDispose(ref PerMaterialBuffer);
            RemoveAndDispose(ref PerObjectBuffer);

            // Get & store references to the Direct3D device & device context
            Device3D = gameEngine.DeviceManager.Device3D;
            Context3D = gameEngine.DeviceManager.Context3D;

            // Release any pre-existing swap chain
            if (SwapChain != null) { RemoveAndDispose(ref SwapChain); }

            // Create constant buffers for shader resources
            CreateConstantBuffers(Device3D, Context3D);

            // Set depth-stencil & rasterizer states
            Context3D.OutputMerger.DepthStencilState = ToDispose(new DepthStencilState(Device3D, new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.Less,
                    DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
                    IsStencilEnabled = false,
                    StencilReadMask = 0xff,
                    StencilWriteMask = 0xff,
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment
                    },
                    BackFace = new DepthStencilOperationDescription()
                    {
                        Comparison = Comparison.Always,
                        PassOperation = StencilOperation.Keep,
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement
                    }
                }));
            Context3D.Rasterizer.State = ToDispose(
                new RasterizerState(Device3D, new RasterizerStateDescription()
                    {
                        FillMode = SettingsManager.ShowWireframe ? SharpDX.Direct3D11.FillMode.Wireframe : SharpDX.Direct3D11.FillMode.Solid,
                        CullMode = CullMode.Back,
                        IsFrontCounterClockwise = SettingsManager.VertexWindingCCW,
                    }));
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Creates the swap chain.
 /// </summary>
 /// <param name="factory">The DXGI factory</param>
 /// <param name="device">The D3D11 device</param>
 /// <param name="desc">The swap chain description</param>
 /// <returns>An instance of swap chain</returns>
 protected abstract SharpDX.DXGI.SwapChain1 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc);
Ejemplo n.º 33
0
            /// <inheritdoc/>
            public void SetWindow(CoreWindow window)
            {
                this.window = window;

                // Starts the timer
                clock = Stopwatch.StartNew();

                // Creates Direct3D11 device
                using (var defaultDevice = new Device(DriverType.Hardware, DeviceCreationFlags.None))
                    graphicsDevice = defaultDevice.QueryInterface<Device1>();


                // Setup swapchain, render target, depth stencil buffer.
                SetupScreenBuffers();

                string path = Package.Current.InstalledLocation.Path;

                // Loads vertex shader bytecode
                var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\MiniCube_VS.fxo");
                vertexShader = new VertexShader(graphicsDevice, vertexShaderByteCode);

                // Loads pixel shader bytecode
                pixelShader = new PixelShader(graphicsDevice, NativeFile.ReadAllBytes(path + "\\MiniCube_PS.fxo"));

                // Layout from VertexShader input signature
                layout = new InputLayout(graphicsDevice, vertexShaderByteCode, new[]
                                                                              {
                                                                                  new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                                                                                  new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 16, 0)
                                                                              });

                // Instantiate Vertex buffer from vertex data
                Buffer vertices = Buffer.Create(graphicsDevice, BindFlags.VertexBuffer, new[]
                                                                                       {
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color.Orange), // Front
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, -1.0f, 1.0f),  Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, -1.0f, 1.0f),   Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, -1.0f, 1.0f),   Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, -1.0f, 1.0f),  Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, 1.0f, 1.0f),  Color.Orange), // BACK
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, 1.0f, 1.0f),    Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, 1.0f, 1.0f),   Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, 1.0f, 1.0f),  Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, 1.0f, 1.0f),   Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, 1.0f, 1.0f),    Color.Orange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, -1.0f, 1.0f),  Color.OrangeRed), // Top
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, 1.0f, 1.0f),   Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, 1.0f, 1.0f),    Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, -1.0f, 1.0f),  Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, 1.0f, 1.0f),    Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, -1.0f, 1.0f),   Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color.OrangeRed), // Bottom
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, 1.0f, 1.0f),   Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, 1.0f, 1.0f),  Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, -1.0f, 1.0f),  Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, 1.0f, 1.0f),   Color.OrangeRed),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color.DarkOrange), // Left
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, 1.0f, 1.0f),  Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, 1.0f, 1.0f),   Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, 1.0f, 1.0f),   Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(-1.0f, 1.0f, -1.0f, 1.0f),  Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, -1.0f, 1.0f),  Color.DarkOrange), // Right
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, 1.0f, 1.0f),    Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, 1.0f, 1.0f),   Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, -1.0f, -1.0f, 1.0f),  Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, -1.0f, 1.0f),   Color.DarkOrange),
                                                                                           new VertexPositionColor(new Vector4(1.0f, 1.0f, 1.0f, 1.0f),    Color.DarkOrange),
                                                                                       });

                vertexBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<VertexPositionColor>(), 0);

                // Create Constant Buffer
                constantBuffer = ToDispose(new Buffer(graphicsDevice, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new deferred context instance of <see cref="SharpDX.Direct3D11.DeviceContext1"/> class.
 /// </summary>
 /// <param name="device"></param>
 public DeviceContext1(Device1 device) : base(IntPtr.Zero)
 {
     device.CreateDeferredContext1(0, this);
 }
        /// <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.º 36
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;
        }
Ejemplo n.º 37
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;
        }
        /// <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>
        /// 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
        }
Ejemplo n.º 40
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>();
        }
Ejemplo n.º 41
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);
        }