Exemplo n.º 1
0
        void CreateViews(string name, BindFlags flags, SlimDX.Direct3D11.Resource resource)
        {
            if (flags.HasFlag(BindFlags.RenderTarget))
            {
                var view = new RenderTargetView(m_D3dDevice, resource);
                m_RTVList.Add(name, view);
            }

            if (flags.HasFlag(BindFlags.DepthStencil))
            {
                var view = new DepthStencilView(m_D3dDevice, resource);
                m_DSVList.Add(name, view);
            }

            if (flags.HasFlag(BindFlags.ShaderResource))
            {
                var view = new ShaderResourceView(m_D3dDevice, resource);
                m_SRVList.Add(name, view);
            }

            if (flags.HasFlag(BindFlags.UnorderedAccess))
            {
                var view = new UnorderedAccessView(m_D3dDevice, resource);
                m_UAVList.Add(name, view);
            }
        }
Exemplo n.º 2
0
        public void InitializeD3D()
        {
            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = 2, // 2 back buffers (a.k.a. Triple Buffering).
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = FormObject.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            if (Device.CreateWithSwapChain(DriverType.Hardware,
                                           DeviceCreationFlags.Debug,
                                           new FeatureLevel[] { FeatureLevel.Level_11_0 },
                                           swapChainDesc,
                                           out _device,
                                           out _swapChain).IsFailure)
            {
                throw new Exception("Error creating swap chain");
            }

            using (var resource = Resource.FromSwapChain <Texture2D>(_swapChain, 0))
            {
                _renderTargetView = new RenderTargetView(_device, resource);
            };

            _deviceContext = _device.ImmediateContext;

            _viewport = new Viewport(0.0f,
                                     0.0f,
                                     FormObject.Width,
                                     FormObject.Height,
                                     0.0f,
                                     1.0f);

            _rasterizerDescription = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = true,
                IsFrontCounterclockwise  = true,
                IsMultisampleEnabled     = true,
                IsDepthClipEnabled       = true,
                IsScissorEnabled         = false
            };

            _deviceContext.Rasterizer.State = RasterizerState.FromDescription(_device, _rasterizerDescription);

            _deviceContext.Rasterizer.SetViewports(_viewport);
            _deviceContext.OutputMerger.SetTargets(_renderTargetView);

            // Prevent DXGI handling of Alt+Enter since it does not work properly with Winforms
            using (var factory = _swapChain.GetParent <Factory>())
            {
                factory.SetWindowAssociation(FormObject.Handle, WindowAssociationFlags.IgnoreAltEnter);
            };
        }
Exemplo n.º 3
0
        private void CreateRenderTargets(int width, int height)
        {
            var backBuffer = Resource.FromSwapChain <Texture2D>(SwapChain, 0);

            RenderTargetView = new RenderTargetView(Device, backBuffer);

            var depthDescription = new Texture2DDescription {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.D32_Float,
                Height            = backBuffer.Description.Height,
                Width             = backBuffer.Description.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(4, 4),
                Usage             = ResourceUsage.Default
            };

            var depthBuffer = new Texture2D(Device, depthDescription);

            var depthStencilViewDescription = new DepthStencilViewDescription {
                Format    = depthDescription.Format,
                Flags     = DepthStencilViewFlags.None,
                Dimension = depthDescription.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D,
                MipSlice  = 0
            };

            DepthStencilView = new DepthStencilView(Device, depthBuffer, depthStencilViewDescription);

            Device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0f, 1f));

            backBuffer.Dispose();
            depthBuffer.Dispose();
        }
Exemplo n.º 4
0
        public ScreenContext(Control owner, RenderContext context, MatrixManager manager) : base(context)
        {
            Device            device     = context.DeviceManager.Device;
            SampleDescription sampleDesc = new SampleDescription(1, 0);

            this.SwapChain = new SwapChain(context.DeviceManager.Factory, device, getSwapChainDescription(owner, sampleDesc));
            //Set rasterizer
            //Initialization of the depth stencil Buffa
            using (Texture2D depthBuffer = new Texture2D(device, getDepthBufferTexture2DDescription(owner, sampleDesc)))
            {
                this.DepthTargetView = new DepthStencilView(device, depthBuffer);
            }
            //Initializing render targets
            using (Texture2D renderTexture = Resource.FromSwapChain <Texture2D>(this.SwapChain, 0))
            {
                this.RenderTargetView = new RenderTargetView(device, renderTexture);
            }
            this.WorldSpace    = new WorldSpace(context);
            this.BindedControl = owner;
            this.MatrixManager = manager;
            this.PanelObserver = new PanelObserver(owner);
            SetViewport();
            this.HitChekcer = new TexturedBufferHitChecker(this.Context, this);
            this.HitChekcer.Resize(owner.ClientSize);
            owner.MouseMove += owner_MouseMove;
            owner.MouseDown += owner_MouseDown;
            owner.MouseUp   += owner_MouseUp;
        }
Exemplo n.º 5
0
 //============================================================
 // 创建背景缓冲
 private void CreatePrimaryRenderTarget()
 {
     using (Texture2D texture = DxResource.FromSwapChain <Texture2D>(_nativeSwap, 0)) {
         _nativeTarget        = new RenderTargetView(_nativeAdapter, texture);
         _target.NativeTarget = _nativeTarget;
     }
 }
Exemplo n.º 6
0
        public void ShotToFile(int width, int height, string outputFile)
        {
            _width  = width;
            _height = height;

            DxResize();
            DrawFrame();

            var tmpTexture = new Texture2D(CurrentDevice, new Texture2DDescription {
                Width             = _width,
                Height            = _height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            var tmpRenderTarget = new RenderTargetView(CurrentDevice, tmpTexture);

            DrawPreviousFrameTo(tmpRenderTarget);

            Resource.SaveTextureToFile(_context, tmpTexture, outputFile.EndsWith(".jpg") ? ImageFileFormat.Jpg :
                                       outputFile.EndsWith(".bmp") ? ImageFileFormat.Bmp : ImageFileFormat.Png, outputFile);
            tmpRenderTarget.Dispose();
            tmpTexture.Dispose();
        }
Exemplo n.º 7
0
        public ScreenContext(Control owner, RenderContext context, MatrixManager manager) : base(context)
        {
            Device            device     = context.DeviceManager.Device;
            SampleDescription sampleDesc = new SampleDescription(1, 0);

            SwapChain = new SwapChain(context.DeviceManager.Factory, device, getSwapChainDescription(owner, sampleDesc));
            //ラスタライザの設定
            //深度ステンシルバッファの初期化
            using (Texture2D depthBuffer = new Texture2D(device, getDepthBufferTexture2DDescription(owner, sampleDesc)))
            {
                DepthTargetView = new DepthStencilView(device, depthBuffer);
            }
            //レンダーターゲットの初期化
            using (Texture2D renderTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0))
            {
                RenderTargetView = new RenderTargetView(device, renderTexture);
            }
            WorldSpace    = new WorldSpace(context);
            BindedControl = owner;
            MatrixManager = manager;
            PanelObserver = new PanelObserver(owner);
            SetViewport();
            HitChekcer = new TexturedBufferHitChecker(Context, this);
            HitChekcer.Resize(owner.ClientSize);
            owner.MouseMove += owner_MouseMove;
            owner.MouseDown += owner_MouseDown;
            owner.MouseUp   += owner_MouseUp;
        }
Exemplo n.º 8
0
 private void SetupRenderTarget()
 {
     //Render this texture (from swap chain target) into the render target
     using (Texture2D texture = Resource11.FromSwapChain <Texture2D>(swapChain, 0))
     {
         renderTarget = new RenderTargetView(GraphicsDirect3D11.Device, texture);
     }
     GraphicsDirect3D11.Device.ImmediateContext.OutputMerger.SetTargets(renderTarget);
 }
Exemplo n.º 9
0
        protected void Resize()
        {
            var width  = Width;
            var height = Height;

            if (width == 0 || height == 0)
            {
                return;
            }

            DisposeHelper.Dispose(ref _renderBuffer);
            DisposeHelper.Dispose(ref _renderView);
            DisposeHelper.Dispose(ref _depthBuffer);
            DisposeHelper.Dispose(ref _depthView);

            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(_swapChainDescription.BufferCount, ActualWidth, ActualHeight,
                                         Format.Unknown, SwapChainFlags.None);
                _renderBuffer = Resource.FromSwapChain <Texture2D>(_swapChain, 0);
            }
            else
            {
                _renderBuffer = new Texture2D(Device, new Texture2DDescription {
                    Width             = ActualWidth,
                    Height            = ActualHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = WpfMode ? Format.B8G8R8A8_UNorm : Format.R8G8B8A8_UNorm,
                    SampleDescription = SampleDescription,
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = WpfMode ? ResourceOptionFlags.Shared : ResourceOptionFlags.None
                });
            }

            _renderView = new RenderTargetView(Device, _renderBuffer);

            var depth = CreateDepthBuffer(width, height);

            _depthBuffer = depth?.Item1;
            _depthView   = depth?.Item2;

            DeviceContext.Rasterizer.SetViewports(OutputViewport);
            Sprite?.RefreshViewport();

            DeviceContext.Rasterizer.SetViewports(Viewport);

            ResetTargets();
            DeviceContext.OutputMerger.DepthStencilState = null;

            ResizeInner();
            DeviceContextHolder.OnResize(width, height);

            InitiallyResized = true;
        }
Exemplo n.º 10
0
        public void Update(DX11RenderContext context)
        {
            if (this.FTextureOutput.SliceCount == 0 || !FTexIn.IsConnected || !FTexIn[0].Contains(context))
            {
                return;
            }

            if (FTexIn.IsConnected)
            {
                ArrayCount = FTexIn[0][context].ElemCnt;

                for (int i = 0; i < numSlicesOut; i++)
                {
                    int slice = VMath.Zmod(FIndex[i], ArrayCount);

                    Texture2DDescription descIn;
                    Texture2DDescription descOut;

                    if (this.FTextureOutput[i].Contains(context))
                    {
                        descIn  = FTexIn[0][context].Resource.Description;
                        descOut = this.FTextureOutput[i][context].Resource.Description;

                        if (/*FIndex.IsChanged ||*/ descIn.Format != descOut.Format || descIn.Width != descOut.Width || descIn.Height != descOut.Height || descIn.MipLevels != descOut.MipLevels)
                        {
                            //this.logger.Log(LogType.Message, "init slice " + i);
                            InitTexture(context, i, descIn);
                        }
                    }
                    else
                    {
                        //InitTexture(context, i, descIn);
                        this.FTextureOutput[i][context] = new DX11Texture2D();
                    }

                    descIn = this.FTexIn[0][context].Resource.Description;

                    if (this.FTextureOutput[i][context].Resource == null)
                    {
                        //this.logger.Log(LogType.Message, "init slice " + i);
                        InitTexture(context, i, descIn);
                    }

                    SlimDX.Direct3D11.Resource source      = this.FTexIn[0][context].Resource;
                    SlimDX.Direct3D11.Resource destination = this.FTextureOutput[i][context].Resource;

                    for (int mip = 0; mip < descIn.MipLevels; mip++)
                    {
                        int sourceSubres      = SlimDX.Direct3D11.Texture2D.CalculateSubresourceIndex(mip, slice, descIn.MipLevels);
                        int destinationSubres = SlimDX.Direct3D11.Texture2D.CalculateSubresourceIndex(mip, 0, descIn.MipLevels);

                        context.CurrentDeviceContext.CopySubresourceRegion(source, sourceSubres, destination, destinationSubres, 0, 0, 0);
                    }
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initialise les ressources graphiques de base.
        /// </summary>
        void InitializeGraphics()
        {
            var form = new RenderForm("Test SlimDX");

            form.ClientSize = new System.Drawing.Size(Scene.Instance.ResolutionWidth, Scene.Instance.ResolutionHeight);
            m_renderForm    = form;
            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(2, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out m_device, out m_swapChain);

            // Depth stencil buffer
            var depthStencilDesc = new Texture2DDescription()
            {
                Width             = Scene.Instance.ResolutionWidth,
                Height            = Scene.Instance.ResolutionHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D32_Float_S8X24_UInt,
                SampleDescription = new SampleDescription(2, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            m_depthStencilBuffer = new Texture2D(m_device, depthStencilDesc);
            m_depthStencilView   = new DepthStencilView(m_device, m_depthStencilBuffer);

            // Création d'une vue sur le render target.
            using (var resource = Resource.FromSwapChain <Texture2D>(m_swapChain, 0))
                m_mainRenderTarget = new RenderTargetView(m_device, resource);

            // Création du viewport.
            var context  = m_device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, Scene.Instance.ResolutionWidth, Scene.Instance.ResolutionHeight);

            context.OutputMerger.SetTargets(m_depthStencilView, m_mainRenderTarget);
            context.Rasterizer.SetViewports(viewport);

            // Empêche le alt + enter de fonctionner.
            using (var factory = m_swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);
        }
Exemplo n.º 12
0
        void Form_DxResize()
        {
            if (_form_renderTarget != null)
            {
                _form_renderTarget.Dispose();
            }

            _form_swapChain.ResizeBuffers(1, _width, _height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);
            using (var resource = Resource.FromSwapChain <Texture2D>(_form_swapChain, 0))
                _form_renderTarget = new RenderTargetView(CurrentDevice, resource);

            DxResize();
        }
Exemplo n.º 13
0
        private void CreateDeviceSwapChainContext()
        {
            var description = new SwapChainDescription
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = RenderForm.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
            };
            Device dev;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out dev, out swapChain);
            device = dev;

            deviceContext = device.ImmediateContext;

            swapchainresource = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            MainRenderTarget  = new RenderTargetView(device, swapchainresource);

            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R32_Typeless,
                Height            = RenderForm.ClientSize.Height,
                Width             = RenderForm.ClientSize.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            };

            DepthBuffer = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription
            {
                ArraySize       = 1,
                Format          = Format.D32_Float,
                Dimension       = DepthStencilViewDimension.Texture2D,
                MipSlice        = 0,
                Flags           = 0,
                FirstArraySlice = 0
            };

            renderTargetDepthStencil = new DepthStencilView(device, DepthBuffer, dsViewDesc);
        }
Exemplo n.º 14
0
        public void ShotBodyShadow(string outputFile)
        {
            _width  = 512;
            _height = 512;

            foreach (var obj in _objs.Where(obj => obj.Blen != null))
            {
                obj.Blen.Dispose();
                obj.Blen = null;
            }

            ShotBodyShadow_SetCamera();

            DxResize();
            DrawFrame();

            var doubleSided = RasterizerState.FromDescription(CurrentDevice, new RasterizerStateDescription {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None,
                IsFrontCounterclockwise = true,
                IsDepthClipEnabled      = false
            });

            var tmpTexture = new Texture2D(CurrentDevice, new Texture2DDescription {
                Width             = _width,
                Height            = _height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R8G8B8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            _effectShotBodyShadow = new EffectShotBodyShadow(CurrentDevice);

            var tmpRenderTarget = new RenderTargetView(CurrentDevice, tmpTexture);

            DrawPreviousBodyDepthTo(tmpRenderTarget, doubleSided);
            BlurBodyShadow(tmpTexture, 1);
            BlurSomething(tmpTexture, 5, 2f / AmbientBodyShadowSize.X, 2f / AmbientBodyShadowSize.Z);

            Resource.SaveTextureToFile(_context, tmpTexture, ImageFileFormat.Png, outputFile);

            _effectShotBodyShadow.Dispose();
            tmpRenderTarget.Dispose();
            tmpTexture.Dispose();
            doubleSided.Dispose();
        }
        public T readPixel <T>(Resource resource) where T : struct
        {
            context.CopySubresourceRegion(resource, Resource.CalculateSubresourceIndex(0, 0, 1),
                                          new ResourceRegion(0, 0, 0, 1, 1, 1), tempTex,
                                          Resource.CalculateSubresourceIndex(0, 0, 1), 0, 0, 0);
            var data = context.MapSubresource(tempTex,
                                              Resource.CalculateSubresourceIndex(0, 0, 1), 4, MapMode.Read,
                                              global::SlimDX.Direct3D11.MapFlags.None);

            var ret = data.Data.Read <T>();

            context.UnmapSubresource(tempTex, Resource.CalculateSubresourceIndex(0, 0, 1));
            return(ret);
        }
        public void Update(DX11RenderContext context)
        {
            if (this.FTextureOutput.SliceCount == 0 || !FTexIn.IsConnected)
            {
                return;
            }

            if (FTexIn.IsConnected)
            {
                ArrayCount = FTexIn[0][context].ElemCnt;

                for (int i = 0; i < numSlicesOut; i++)
                {
                    int slice = VMath.Zmod(FIndex[i], ArrayCount);

                    Texture2DDescription descIn;
                    Texture2DDescription descOut;

                    if (this.FTextureOutput[i].Contains(context))
                    {
                        descIn  = FTexIn[0][context].Resource.Description;
                        descOut = this.FTextureOutput[i][context].Resource.Description;

                        if (/*FIndex.IsChanged ||*/ descIn.Format != descOut.Format || descIn.Width != descOut.Width || descIn.Height != descOut.Height)
                        {
                            InitTexture(context, i, descIn);
                        }
                    }
                    else
                    {
                        this.FTextureOutput[i][context] = new DX11DepthStencil(context, FTexIn[0][context].Resource.Description.Width, FTexIn[0][context].Resource.Description.Height, FTexIn[0][context].Resource.Description.SampleDescription);
                    }

                    descIn = this.FTexIn[0][context].Resource.Description;

                    if (this.FTextureOutput[i][context].Resource == null)
                    {
                        InitTexture(context, i, descIn);
                    }

                    SlimDX.Direct3D11.Resource source      = this.FTexIn[0][context].Resource;
                    SlimDX.Direct3D11.Resource destination = this.FTextureOutput[i][context].Resource;

                    int sourceSubres      = SlimDX.Direct3D11.Texture2D.CalculateSubresourceIndex(0, slice, descIn.MipLevels);
                    int destinationSubres = SlimDX.Direct3D11.Texture2D.CalculateSubresourceIndex(0, 0, 1);

                    context.CurrentDeviceContext.CopySubresourceRegion(source, sourceSubres, destination, destinationSubres, 0, 0, 0);
                }
            }
        }
Exemplo n.º 17
0
        void CreateSwapChain()
        {
            if ((renderControl.Width > 0) && (renderControl.Height > 0) && renderControl.Visible)
            {
                try
                {
                    if (renderTarget != null)
                    {
                        renderTarget.Dispose();
                        renderTarget = null;
                    }

                    swapChain.ResizeBuffers(1, renderControl.Width, renderControl.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                    using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                        renderTarget = new RenderTargetView(Device, resource);

                    Texture2DDescription depthStencilDesc = new Texture2DDescription
                    {
                        Width             = renderControl.Width,
                        Height            = renderControl.Height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        Format            = Format.D24_UNorm_S8_UInt,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default,
                        BindFlags         = BindFlags.DepthStencil,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        OptionFlags       = ResourceOptionFlags.None
                    };
                    depthStencilBuffer = new Texture2D(Device, depthStencilDesc)
                    {
                        DebugName = "DepthStencilBuffer"
                    };
                    depthStencilView = new DepthStencilView(Device, depthStencilBuffer);

                    Device.ImmediateContext.OutputMerger.SetTargets(depthStencilView, renderTarget);

                    var viewport = new Viewport(0.0f, 0.0f, renderControl.Width, renderControl.Height, 0f, 1f);
                    Device.ImmediateContext.Rasterizer.SetViewports(viewport);
                }
                catch (Exception e)
                {
                    Utility.ReportException(e);
                    deviceLost = true;
                }
                renderRect = new Rectangle(0, 0, renderControl.Width, renderControl.Height);
            }
        }
Exemplo n.º 18
0
        public void Apply(DX11Resource <DX11RenderTextureArray> textureArray, ISpread <int> slices)
        {
            int    w = textureArray[context].Width;
            int    h = textureArray[context].Height;
            int    d = slices.SliceCount;
            Format f = textureArray[context].Format;

            Texture2DDescription descIn = textureArray[context].Resource.Description;

            // check if parameters match - if not, create a new rt array
            if (this.rtarr != null)
            {
                if (this.rtarr.ElemCnt != d ||
                    this.rtarr.Width != w ||
                    this.rtarr.Height != h ||
                    this.rtarr.Description.MipLevels != descIn.MipLevels ||
                    this.rtarr.Format != f)
                {
                    this.rtarr.Dispose(); this.rtarr = null;
                }
            }

            if (this.rtarr == null)
            {
                this.rtarr = new DX11RenderTextureArray(this.context, w, h, d, f, true, descIn.MipLevels);
            }

            // copy the ressources over
            for (int i = 0; i < slices.SliceCount; i++)
            {
                int slice = VMath.Zmod(slices[i], textureArray[context].ElemCnt);

                SlimDX.Direct3D11.Resource source = textureArray[context].Resource;

                for (int mip = 0; mip < descIn.MipLevels; mip++)
                {
                    //int mip = 0;
                    int sourceSubres      = SlimDX.Direct3D11.Texture2D.CalculateSubresourceIndex(mip, slice, descIn.MipLevels);
                    int destinationSubres = SlimDX.Direct3D11.Texture2D.CalculateSubresourceIndex(mip, i, descIn.MipLevels);

                    context.CurrentDeviceContext.CopySubresourceRegion(source, sourceSubres, this.rtarr.Resource, destinationSubres, 0, 0, 0);
                }
            }
        }
Exemplo n.º 19
0
        protected void Setoutput()
        {
            if (Rendertarget != null)
            {
                Rendertarget.Dispose();
            }

            using (var resource = Resource.FromSwapChain <Texture2D>(_swapchain, 0))
            {
                Rendertarget = new RenderTargetView(_device, resource);
            }

            // setting a viewport is required if you want to actually see anything
            Devicecontext = _device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, Width, Height);

            Devicecontext.OutputMerger.SetTargets(Rendertarget);
            Devicecontext.Rasterizer.SetViewports(viewport);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Raises the System.Windows.Forms.Control.Resize event.
        /// </summary>
        /// <param name="e">
        /// An System.EventArgs that contains the event data.
        /// </param>
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            // If the form is minimized, OnResize is triggered with a client-size of (0,0).
            if (ClientSize.IsEmpty)
            {
                return;
            }
            if (swapChain == null)
            {
                return;
            }
            ReleaseCOMObjects(false);
            // Resize the back buffer.
            swapChain.ResizeBuffers(1, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
            // Bind the back buffer to the output merger stage of the pipeline so that Direct3D can
            // render onto it. FromSwapChain increases the reference count of the swapChain object, so
            // wrap it in a using statement to keep the reference count at 1.
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                renderTargetView = new RenderTargetView(device, resource);
            // Create the depth and stencil buffers.
            var depthStencilDesc = new Texture2DDescription {
                Width             = ClientSize.Width,
                Height            = ClientSize.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            depthStencilBuffer = new Texture2D(device, depthStencilDesc);
            depthStencilView   = new DepthStencilView(device, depthStencilBuffer);
            Context.OutputMerger.SetTargets(depthStencilView, renderTargetView);
            // Adjust the viewport
            if (AutoAdjustViewPort)
            {
                ResizeViewport(ClientSize);
            }
        }
Exemplo n.º 21
0
        private void MainForm_Load(object sender, System.EventArgs e)
        {
            // Creating device (we accept dx10 cards or greater)
            FeatureLevel[] levels =
            {
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_10_0
            };

            // Defining our swap chain
            SwapChainDescription desc = new SwapChainDescription();

            desc.BufferCount       = 1;
            desc.Usage             = Usage.BackBuffer | Usage.RenderTargetOutput;
            desc.ModeDescription   = new ModeDescription(0, 0, new Rational(0, 0), Format.R8G8B8A8_UNorm);
            desc.SampleDescription = new SampleDescription(1, 0);
            desc.OutputHandle      = Handle;
            desc.IsWindowed        = true;
            desc.SwapEffect        = SwapEffect.Discard;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, levels, desc, out device11, out swapChain);

            // Getting back buffer
            backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            // Defining render view
            renderTargetView = new RenderTargetView(device11, backBuffer);
            device11.ImmediateContext.OutputMerger.SetTargets(renderTargetView);
            device11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, ClientSize.Width, ClientSize.Height, 0.0f, 1.0f));

            // Preparing shaders
            PrepareShaders();

            // Creating geometry
            CreateGeometry();

            // Setting constants
            AffectConstants();
        }
Exemplo n.º 22
0
        public void Resize()
        {
            if (BindedControl.ClientSize.Width == 0 || BindedControl.ClientSize.Height == 0)
            {
                return;                                                                              //フォームがフロート状態になった時一瞬だけ来て、デバイスが作れなくなるのでこの時はなしにする。
            }
            DisposeTargetViews();
            SwapChainDescription desc = SwapChain.Description;

            SwapChain.ResizeBuffers(desc.BufferCount, BindedControl.ClientSize.Width, BindedControl.ClientSize.Height, desc.ModeDescription.Format,
                                    desc.Flags);
            //深度ステンシルバッファの初期化
            using (Texture2D depthBuffer = new Texture2D(Context.DeviceManager.Device, getDepthBufferTexture2DDescription(BindedControl, desc.SampleDescription)))
            {
                DepthTargetView = new DepthStencilView(Context.DeviceManager.Device, depthBuffer);
            }
            //レンダーターゲットの初期化
            using (Texture2D renderTexture = Resource.FromSwapChain <Texture2D>(SwapChain, 0))
            {
                RenderTargetView = new RenderTargetView(Context.DeviceManager.Device, renderTexture);
            }
            HitChekcer.Resize(BindedControl.ClientSize);
        }
Exemplo n.º 23
0
        public void Resize()
        {
            if (this.BindedControl.ClientSize.Width == 0 || this.BindedControl.ClientSize.Height == 0)
            {
                return;                                                                                        //To none at this time so come just for a moment when form becomes a floating device, make。
            }
            DisposeTargetViews();
            SwapChainDescription desc = this.SwapChain.Description;

            this.SwapChain.ResizeBuffers(desc.BufferCount, this.BindedControl.ClientSize.Width, this.BindedControl.ClientSize.Height, desc.ModeDescription.Format,
                                         desc.Flags);
            //Initialization of the depth stencil Buffa
            using (Texture2D depthBuffer = new Texture2D(this.Context.DeviceManager.Device, getDepthBufferTexture2DDescription(this.BindedControl, desc.SampleDescription)))
            {
                this.DepthTargetView = new DepthStencilView(this.Context.DeviceManager.Device, depthBuffer);
            }
            //Initializing render targets
            using (Texture2D renderTexture = Resource.FromSwapChain <Texture2D>(this.SwapChain, 0))
            {
                this.RenderTargetView = new RenderTargetView(this.Context.DeviceManager.Device, renderTexture);
            }
            this.HitChekcer.Resize(this.BindedControl.ClientSize);
        }
Exemplo n.º 24
0
        public ScreenRenderTargetAspect(DxDeviceContext dxDeviceContext)
        {
            _dxDeviceContext = dxDeviceContext;
            ShowRedDot       = true;

            // Init render target from primary display
            Texture2D backBuffer = Resource.FromSwapChain <Texture2D>(_dxDeviceContext.SwapChain, 0);

            _renderTargetView = new RenderTargetView(_dxDeviceContext.Device, backBuffer);
            _dxDeviceContext.Device.ImmediateContext.ClearRenderTargetView(_renderTargetView, new Color4(System.Drawing.Color.Black));

            // Init depth stencil
            Texture2DDescription sdDesc = new Texture2DDescription();

            sdDesc.Width             = _dxDeviceContext.FrameWidth;
            sdDesc.Height            = _dxDeviceContext.FrameHeight;
            sdDesc.MipLevels         = 1;
            sdDesc.ArraySize         = 1;
            sdDesc.Format            = Format.D24_UNorm_S8_UInt;
            sdDesc.SampleDescription = new SampleDescription(1, 0);
            sdDesc.Usage             = ResourceUsage.Default;
            sdDesc.BindFlags         = BindFlags.DepthStencil;
            sdDesc.CpuAccessFlags    = CpuAccessFlags.None;
            sdDesc.OptionFlags       = ResourceOptionFlags.None;
            _depthStencilTexture     = new Texture2D(_dxDeviceContext.Device, sdDesc);

            DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();

            dsvDesc.Format          = sdDesc.Format;
            dsvDesc.Dimension       = DepthStencilViewDimension.Texture2D;
            dsvDesc.FirstArraySlice = 0;
            dsvDesc.ArraySize       = 1;
            _depthStencilView       = new DepthStencilView(_dxDeviceContext.Device, _depthStencilTexture, dsvDesc);

            // Init viewport
            _viewport = new Viewport(0, 0, _dxDeviceContext.FrameWidth, _dxDeviceContext.FrameHeight, 0, 1);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Method called when the form is resized by the user.
        /// </summary>
        /// <param name="sender">sending form</param>
        /// <param name="eventArgs">event argument</param>
        private static void FormOnResize(object sender, EventArgs eventArgs)
        {
            RenderTarget.Dispose();
            DepthView.Dispose();
            depthBuffer.Dispose();


            DeviceContext = Device.ImmediateContext;

            DeviceContext.Rasterizer.State = RasterizerState.FromDescription(Device, Rasterizer);

            depthBufferDesc.Width  = Form.ClientSize.Width;
            depthBufferDesc.Height = Form.ClientSize.Height;


            depthBuffer = new Texture2D(Device, depthBufferDesc);
            DepthView   = new DepthStencilView(Device, depthBuffer);


            DepthState = DepthStencilState.FromDescription(Device, dsStateDesc);
            DeviceContext.OutputMerger.DepthStencilState = DepthState;



            SwapChain.ResizeBuffers(2, Form.ClientSize.Width, Form.ClientSize.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
            using (var resource = Resource.FromSwapChain <Texture2D>(SwapChain, 0))
                RenderTarget = new RenderTargetView(Device, resource);

            DeviceContext.OutputMerger.SetTargets(DepthView, RenderTarget);


            Viewport = new Viewport(0.0f, 0.0f, Form.ClientSize.Width, Form.ClientSize.Height);
            DeviceContext.Rasterizer.SetViewports(Viewport);
            ProjectionMatrix = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, Viewport.Width / Viewport.Height, .1f, 1000.0f);

            UIManagerSpriteRenderer.SpriteRenderer?.RefreshViewport();
        }
Exemplo n.º 26
0
        public void CreateDeviceAndSwapChain(System.Windows.Forms.Control form)
        {
            this.form = form;

            float aspectRatio = (float)form.ClientSize.Width / (float)form.ClientSize.Height;

            CameraManager.Instance.SetPerspective((float)Math.PI / 4, aspectRatio, 0.1f, 10000.0f);

            var description = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            backBufferTexture = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderTarget      = new RenderTargetView(device, backBufferTexture);

            // setting a viewport is required if you want to actually see anything
            context = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);

            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewports(viewport);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);
        }
Exemplo n.º 27
0
        public HoverForm(Maze maze)
            : base("HoverRenderer")
        {
            this.ClientSize = new System.Drawing.Size(640, 480);

            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = this.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, resource);
            }

            // Create the depth buffer
            var depthBufferDescription = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.D32_Float,
                Height            = this.ClientSize.Height,
                Width             = this.ClientSize.Width,
                MipLevels         = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            };

            using (var depthBuffer = new Texture2D(device, depthBufferDescription))
            {
                depthStencilView  = new DepthStencilView(device, depthBuffer);
                depthStencilState = DepthStencilState.FromDescription(device, new DepthStencilStateDescription {
                    IsDepthEnabled   = true,
                    IsStencilEnabled = false,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.LessEqual
                });
            }

            // Setup wireframe mode
            rasteriserState = RasterizerState.FromDescription(device, new RasterizerStateDescription
            {
                CullMode = SlimDX.Direct3D11.CullMode.None,
                FillMode = SlimDX.Direct3D11.FillMode.Wireframe
            });

            // setting a viewport is required if you want to actually see anything
            context = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, this.ClientSize.Width, this.ClientSize.Height);

            context.OutputMerger.SetTargets(depthStencilView, renderTarget);
            context.OutputMerger.DepthStencilState = depthStencilState;
            context.Rasterizer.State = rasteriserState;
            context.Rasterizer.SetViewports(viewport);

            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "VShader", "vs_4_0", ShaderFlags.Debug, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader   = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "PShader", "ps_4_0", ShaderFlags.Debug, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            // create test vertex data, making sure to rewind the stream afterward
            vertices        = CreateTriangleListFromMaze(maze);
            camera.Position = FindHumanStartPosition(maze);

            // create the vertex layout and buffer
            var elements = new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("COLOR", 0, Format.R32G32B32_Float, 0)
            };

            layout       = new InputLayout(device, inputSignature, elements);
            vertexBuffer = new Buffer(device, vertices, (int)vertices.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 24, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // crate the constant buffer
            constantBuffer = new Buffer(device, new BufferDescription
            {
                Usage       = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(ConstantBuffer)),
                BindFlags   = BindFlags.ConstantBuffer
            });

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // handle alt+enter ourselves
            this.KeyDown += (o, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
                }
            };

            // handle form size changes
            this.UserResized += (o, e) =>
            {
                renderTarget.Dispose();

                swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                    renderTarget = new RenderTargetView(device, resource);

                context.OutputMerger.SetTargets(renderTarget);
            };

            this.KeyDown += new KeyEventHandler(HoverForm_KeyDown);
        }
Exemplo n.º 28
0
        public D3DSlimDXCanvas()
        {
            InitializeComponent();

            // hook the application's idle event
            Application.Idle += new EventHandler(OnApplicationIdle);

            GameConsole.Instance.FrameDone += new EventHandler(GameConsole_FrameDone);

            Size maxSize = new Size(bitmapWidth, bitmapHeight);

            foreach (var screen in Screen.AllScreens)
            {
                maxSize.Width  = Math.Max(maxSize.Width, screen.Bounds.Width);
                maxSize.Height = Math.Max(maxSize.Height, screen.Bounds.Height);
            }

            ModeDescription modeDesc = new ModeDescription();

            modeDesc.Width  = maxSize.Width;
            modeDesc.Height = maxSize.Height;
            modeDesc.Format = Format.R8G8B8A8_UNorm;

            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = this.Handle,
                IsWindowed        = true,
                ModeDescription   = modeDesc,
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);

            // Grab the context.
            context = device.ImmediateContext;

            // Set as output merger render target.
            context.OutputMerger.SetTargets(renderTarget);

            // setting a viewport is required if you want to actually see anything
            var viewport = new Viewport(0.0f, 0.0f, maxSize.Width, maxSize.Height);

            context.Rasterizer.SetViewports(viewport);

            ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile("shader.fx", "Render", "fx_5_0", ShaderFlags.None, EffectFlags.None);

            effect = new Effect(device, effectByteCode);

            // Create sampler
            var samplerDesc = new SamplerDescription();

            samplerDesc.Filter             = Filter.MinMagMipLinear;
            samplerDesc.AddressU           = TextureAddressMode.Wrap;
            samplerDesc.AddressV           = TextureAddressMode.Wrap;
            samplerDesc.AddressW           = TextureAddressMode.Wrap;
            samplerDesc.ComparisonFunction = Comparison.Never;
            samplerDesc.MinimumLod         = 0;
            samplerDesc.MaximumLod         = float.MaxValue;

            SamplerState samplerState = SamplerState.FromDescription(this.device, samplerDesc);

            effect.GetVariableByName("TextureSampler").AsSampler().SetSamplerState(0, samplerState);
            this.context.PixelShader.SetSampler(samplerState, 0);


            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "vs_main", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader   = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("shader.fx", "ps_main", "ps_4_0", ShaderFlags.None, EffectFlags.None))
            {
                pixelShader = new PixelShader(device, bytecode);
            }

            // create test vertex data, making sure to rewind the stream afterward
            vertices = new DataStream(20 * 4, true, true);
            vertices.Write(new Vector3(-1.0f, -1.0f, 0.5f));             // bottom left
            vertices.Write(new Vector2(0.0f, 1.0f));

            vertices.Write(new Vector3(-1.0f, 1.0f, 0.5f));             // top left
            vertices.Write(new Vector2(0.0f, 0.0f));

            vertices.Write(new Vector3(1.0f, -1.0f, 0.5f));             // bottom right
            vertices.Write(new Vector2(1.0f, 1.0f));

            vertices.Write(new Vector3(1.0f, 1.0f, 0.5f));             // top right
            vertices.Write(new Vector2(1.0f, 0.0f));
            vertices.Position = 0;

            vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 20 * 4, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // create the vertex layout and buffer
            var elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("textcoord", 0, Format.R32G32_Float, 12, 0)
            };

            layout = new InputLayout(device, inputSignature, elements);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 20, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAltEnter);


            texes[0] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame1.jpg");
            texes[1] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame2.jpg");
            texes[2] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame3.jpg");
            texes[3] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame4.jpg");
            texes[4] = Texture2D.FromFile(this.device, @"C:\jmk\screens\new\frame5.jpg");


            initialized = true;
        }
Exemplo n.º 29
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form1();

            Device          device;
            SwapChain       swapChain;
            ShaderSignature inputSignature;
            VertexShader    vertexShader;
            GeometryShader  geometryShader;
            PixelShader     pixelShader;

            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTarget;

            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);

            // setting a viewport is required if you want to actually see anything
            var context  = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);

            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewports(viewport);

            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("Voxel.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader   = new VertexShader(device, bytecode);
            }

            using (var bytecode = ShaderBytecode.CompileFromFile("Voxel.fx", "GS", "gs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                geometryShader = new GeometryShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("Voxel.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            // create test vertex data, making sure to rewind the stream afterward
            var vertices = new DataStream(12 * 3, true, true);

            vertices.Write(new Vector3(0.0f, 0.5f, 0.5f));
            vertices.Write(new Vector3(0.5f, -0.5f, 0.5f));
            vertices.Write(new Vector3(-0.5f, -0.5f, 0.5f));
            vertices.Position = 0;

            // create the vertex layout and buffer
            var elements     = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) };
            var layout       = new InputLayout(device, inputSignature, elements);
            var vertexBuffer = new Buffer(device, vertices, 12 * 3, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            // context.GeometryShader.Set(geometryShader);
            context.PixelShader.Set(pixelShader);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // handle alt+enter ourselves
            form.KeyDown += (o, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
                }
            };

            // handle form size changes
            form.Resize += (o, e) =>
            {
                renderTarget.Dispose();

                swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                    renderTarget = new RenderTargetView(device, resource);

                context.OutputMerger.SetTargets(renderTarget);
            };

            MessagePump.Run(form, () =>
            {
                // clear the render target to a soothing blue
                context.ClearRenderTargetView(renderTarget, new Color4(0.5f, 0.5f, 1.0f));

                // draw the triangle
                context.Draw(3, 0);
                swapChain.Present(0, PresentFlags.None);
            });

            // clean up all resources
            // anything we missed will show up in the debug output
            vertices.Close();
            vertexBuffer.Dispose();
            layout.Dispose();
            inputSignature.Dispose();
            vertexShader.Dispose();
            geometryShader.Dispose();
            pixelShader.Dispose();
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }
Exemplo n.º 30
0
 public static void InitRenderTarget()
 {
     using (var resource = Resource.FromSwapChain <Texture2D>(Data.DX11SwapChain, 0))
         Data.DX11RenderTarget = new RenderTargetView(Data.DX11Device, resource);
     Data.DX11Context.OutputMerger.SetTargets(Data.DX11RenderTarget);
 }
        private ShaderResourceView AcquireResourceView(Resource resource)
        {
            // See if it already exists
            ShaderResourceView view;
            if (shaderresourcemap.TryGetValue(resource, out view)) return view;

            // Create it
            view = new ShaderResourceView(Device, resource);
            shaderresourcemap.Add(resource, view);

            // Return it
            return view;
        }