Beispiel #1
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);
            };
        }
Beispiel #2
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();
        }
Beispiel #3
0
 //============================================================
 // 创建背景缓冲
 private void CreatePrimaryRenderTarget()
 {
     using (Texture2D texture = DxResource.FromSwapChain <Texture2D>(_nativeSwap, 0)) {
         _nativeTarget        = new RenderTargetView(_nativeAdapter, texture);
         _target.NativeTarget = _nativeTarget;
     }
 }
Beispiel #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;
        }
Beispiel #5
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;
        }
 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);
 }
Beispiel #7
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;
        }
Beispiel #8
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);
        }
Beispiel #9
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();
        }
Beispiel #10
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);
        }
Beispiel #11
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);
            }
        }
Beispiel #12
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);
        }
Beispiel #13
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);
            }
        }
Beispiel #14
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();
        }
Beispiel #15
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);
        }
Beispiel #16
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);
        }
        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);
        }
Beispiel #18
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);
        }
Beispiel #19
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();
        }
Beispiel #20
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();
        }
Beispiel #21
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);
 }
Beispiel #22
0
        /// <summary>
        /// ターゲットがリサイズされたときに呼ぶ必要がある
        /// </summary>
        static public void ResizeTargetPanel(int width, int height)
        {
            if (width == 0 || height == 0)
            {
                return;
            }

            // 現状原因がわかってないけれどもdockしている状態で閉じると例外が発生するので…
            try {
                D3D11ImmediateContext.OutputMerger.SetTargets(new RenderTargetView[] { });

                // バックバッファを作り替える
                if (swapChain_ != null)
                {
                    defaultRenderTarget_.Dispose();
                    swapChain_.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                    using (var resource = DxResource.FromSwapChain <Texture2D>(swapChain_, 0))
                        defaultRenderTarget_ = new RenderTargetView(D3D11Device, resource);
                }
                else
                {
                    // TODO:新たにnewしてるのでこれだとテクスチャとしてこれを参照してた場合リンクが切れる…。
                    defaultColorBuffer_.Dispose();
                    //defaultColorBuffer_ = new Texture(new Texture.InitDesc {
                    defaultColorBuffer_.Initialize(new Texture.InitDesc {
                        width  = width,
                        height = height,
                        //format = Format.R8G8B8A8_UNorm,
                        format      = Format.B8G8R8A8_UNorm,
                        bindFlag    = TextureBuffer.BindFlag.IsRenderTarget,
                        optionFlags = ResourceOptionFlags.Shared,
                    });
                    defaultRenderTarget_ = defaultColorBuffer_.RenderTargetView;
                }

                // デプスステンシル
                defaultDepthStencil_.Dispose();
                //defaultDepthStencil_ = new Texture(new Texture.InitDesc {
                defaultDepthStencil_.Initialize(new Texture.InitDesc {
                    width  = width,
                    height = height,
                    //format = Format.R24G8_Typeless,
                    format   = Format.R32_Typeless,
                    bindFlag = TextureBuffer.BindFlag.IsDepthStencil,
                });

                // プロクシイメージ
                if (proxyImage_ != null)
                {
                    proxyImage_.SetBackBufferSlimDX((Texture2D)GraphicsCore.DefaultColorBuffer.TextureResource);
                }

                D3D11ImmediateContext.OutputMerger.SetTargets(defaultDepthStencil_.DepthStencilView, defaultRenderTarget_);

                // ビューポートを再セット(フルスクリーンビューポート)
                var new_viewport = new Viewport(0.0f, 0.0f, width, height);
                D3D11ImmediateContext.Rasterizer.SetViewports(new_viewport);
                TargetWidth  = width;
                TargetHeight = height;

                // カメラ再セット(仮)
                Camera3D.SetAspect((float)width / height);
                Camera3D.Update();
            } catch {
            }
        }
        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;
        }
Beispiel #24
0
        /// <summary>
        /// Initialize graphics properties and create the main window.
        /// </summary>
        public static void Init()
        {
            //Make the Form
            Form = new RenderForm("LeafMeAlone");

            Device = new Device(DriverType.Hardware, DeviceCreationFlags.None);
            var msaa = Device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 4);

            SwapChainDescription 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 = /*msaa != 0 ? new SampleDescription(4,msaa) : */ new SampleDescription(1, 0),
                Flags             = SwapChainFlags.None,
                SwapEffect        = SwapEffect.Discard
            };


            SwapChain = new SwapChain(Device.Factory, Device, description);

            //create new device (with directx) which can be used throughout the project.
            // 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);

            //get device context so we can render to it.
            DeviceContext = Device.ImmediateContext;

            InitializeRasterizer();
            InitializeDepthBuffer();
            InitializeBlending();

            Viewport = new Viewport(0.0f, 0.0f, Form.ClientSize.Width, Form.ClientSize.Height);
            //DeviceContext.OutputMerger.SetTargets(RenderTarget);
            DeviceContext.OutputMerger.SetTargets(DepthView, RenderTarget);
            DeviceContext.Rasterizer.SetViewports(Viewport);

            Form.Resize += FormOnResize;

            ProjectionMatrix = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, Viewport.Width / Viewport.Height, .1f, 1000.0f);

            // dont use default alt enter because it doesn't work.
            using (var factory = SwapChain.GetParent <Factory>())
                factory.SetWindowAssociation(Form.Handle, WindowAssociationFlags.IgnoreAltEnter);

#if DEBUG
            TextBox debugTextbox = new TextBox {
                Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical
            };
            DebugForm = new Form();
            DebugForm.Controls.Add(debugTextbox);
            DebugForm.Closing += (sender, args) =>
            {
                args.Cancel = true;
                DebugForm.Hide();
            };
            Debug.Init(debugTextbox);
#endif

            // handle alt+enter ourselves
            Form.KeyDown += (o, e) =>
            {
                if (e.Shift && e.KeyCode == Keys.Enter)
                {
                    Form.Size = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
                    SwapChain.IsFullScreen = !SwapChain.IsFullScreen;
                }

                if (e.KeyCode == Keys.Escape)
                {
                    Application.Exit();
                }
#if DEBUG
                if (e.Control && e.KeyCode == Keys.Enter)
                {
                    DebugForm.Show();
                }
#endif
            };
            InitializeComponent(Form);
        }
Beispiel #25
0
        public Renderer(MainForm form, Control target)
        {
            t             = new Stopwatch();
            mainForm      = form;
            targetControl = target;
            form.Renderer = this;
            description   = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = target.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);

            // setting a viewport is required if you want to actually see anything
            context  = device.ImmediateContext;
            viewport = new Viewport(0.0f, 0.0f, target.ClientSize.Width, target.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewports(viewport);

            CreateShaders(File.ReadAllText("vteffect.fx"));

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(target.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();

                viewport = new Viewport(0.0f, 0.0f, target.ClientSize.Width, target.ClientSize.Height);
                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);
                context.Rasterizer.SetViewports(viewport);
                SetTexture(currentEntry);
            };

            MessagePump.Run(form, Render);

            // clean up all resources
            // anything we missed will show up in the debug output
            vertices.Close();
            vertexBuffer.Dispose();
            layout.Dispose();
            inputSignature.Dispose();
            vertexShader.Dispose();
            pixelShader.Dispose();
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
            UpdateRenderer = true;
        }
Beispiel #26
0
        /// <summary>
        /// TODO doc
        /// </summary>
        public void Init(string windowName, int top = 10, int left = 10, int width = 1280, int height = 1024)
        {
            InitAwesomium();

            _form = new RenderForm
            {
                Text            = windowName,
                Icon            = new System.Drawing.Icon("res/x.ico"),
                FormBorderStyle = FormBorderStyle.Sizable, // set to NONE for pseudo full screen
                StartPosition   = FormStartPosition.Manual,

                Top    = top,
                Left   = left,
                Width  = width,
                Height = height
            };


            // The characteristics of our swap chain
            var swapChainDescription = new SwapChainDescription
            {
                BufferCount       = 2, // front & back buffer
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = _form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1 /*samples per pixel*/, 0 /*anti-aliasing level*/),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };


            Device.CreateWithSwapChain(DriverType.Hardware,
                                       DeviceCreationFlags.None,
                                       swapChainDescription,
                                       out _device,
                                       out _swapChain);



            // create a view of our render target, which is the backbuffer of the swap chain
            using (var res = Resource.FromSwapChain <Texture2D>(_swapChain, 0))
                _renderTarget = new RenderTargetView(_device, res);



            // create a viewport
            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 & get its input signature
            using (var bytecode = ShaderBytecode.CompileFromFile("res/simple.fx", "vertex_shader", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                _vsInputSignature = ShaderSignature.GetInputSignature(bytecode);
                _vertexShader     = new VertexShader(_device, bytecode);
            }



            // enable alpha blending
            var blendStateDescription = new BlendStateDescription
            {
                AlphaToCoverageEnable  = false,
                IndependentBlendEnable = false,
            };

            blendStateDescription.RenderTargets[0].BlendEnable           = true;
            blendStateDescription.RenderTargets[0].SourceBlend           = BlendOption.SourceAlpha;
            blendStateDescription.RenderTargets[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blendStateDescription.RenderTargets[0].BlendOperation        = BlendOperation.Add;
            blendStateDescription.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
            blendStateDescription.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
            blendStateDescription.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
            blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;


            BlendState TransparentBS = BlendState.FromDescription(_device, blendStateDescription);

            context.OutputMerger.BlendState = TransparentBS;


            // initialize all pixel shaders
            InitPixelShaders();


            #region Input Handling

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


            // add input handler
            _form.KeyDown += HandleInput;


            // handle form size changes

            /* TODO do as u wish
             * _form.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);
             * };
             */

            #endregion
        }
Beispiel #27
0
        static void Main()
        {
            m_FrameNumber = 0;
            m_Time        = 0.0f;

            Device    device;
            SwapChain swapChain;

            //var form = new RenderForm("CSharpRenderer");
            var form  = new CSharpRendererMainForm();
            var panel = form.GetRenderingPanel();

            form.ClientSize = new System.Drawing.Size(ResolutionX, ResolutionY);

            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = panel.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(ResolutionX, ResolutionY, 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);
            var swapChainResource = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            SamplerStates.Initialize(device);
            ShaderManager.Initialize(device);
            GPUProfiler.Initialize(device);
            ContextHelper.Initialize(device);
            RenderTargetManager.Initialize(device);
            PostEffectHelper.Initialize(device, ResolutionX, ResolutionY);
            CubemapRenderHelper.Initialize(device);
            PerlinNoiseRenderHelper.Initialize(device, device.ImmediateContext);
            LightingLUTHelper.Initialize(device, device.ImmediateContext);
            DebugManager.Initialize(device, ResolutionX, ResolutionY);

            InitializeControls(form);

            Scene scene = new Scene();

            scene.Initialize(device, form, panel, ResolutionX, ResolutionY);

            var resolvedRenderTarget = RenderTargetSet.CreateRenderTargetSet(device, ResolutionX, ResolutionY, Format.R8G8B8A8_UNorm, 1, false);

            RenderTargetSet.BindNull(device.ImmediateContext);

            // setting a viewport is required if you want to actually see anything
            var context = device.ImmediateContext;

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

            int counter = 0;

            Dictionary <string, double> profilers;

            profilers = new Dictionary <String, double>();

            DateTime now = DateTime.Now;

            CustomConstantBufferInstance globalFrameConstantBuffer = ShaderManager.CreateConstantBufferInstance("GlobalFrameBuffer", device);

            MessagePump.Run(form, () =>
            {
                TemporalSurfaceManager.UpdateTemporalSurfaces();
                if (ShaderManager.UpdateShaderManager(device))
                {
                    InitializeControls(form);
                }

                GPUProfiler.BeginFrameProfiling(context);

                double timeDelta = (DateTime.Now - now).TotalMilliseconds;

                if (!form.GetFreezeTime())
                {
                    m_Time += timeDelta / 1000.0;
                    m_FrameNumber++;
                }

                UpdateGlobalConstantBuffer(context, globalFrameConstantBuffer, form);

                scene.RenderFrame(context, timeDelta, resolvedRenderTarget);
                now = DateTime.Now;
                DebugManager.PresentDebug(context, resolvedRenderTarget);
                context.CopyResource(resolvedRenderTarget.m_RenderTargets[0].m_TextureObject2D, swapChainResource);
                GPUProfiler.EndFrameProfiling(context);
                swapChain.Present(0, PresentFlags.None);
                context.PixelShader.SetShaderResource(null, 0);

                if (GPUProfiler.m_CurrentFrameProfilerTree != null)
                {
                    Action <GPUProfiler.ProfilerTreeMember, String> processLevel = null;

                    processLevel = (GPUProfiler.ProfilerTreeMember treeMember, String level) =>
                    {
                        string finalName = level + treeMember.m_Name;

                        if (profilers.ContainsKey(finalName))
                        {
                            profilers[finalName] += treeMember.m_Time;
                        }
                        else
                        {
                            profilers.Add(finalName, treeMember.m_Time);
                        }

                        foreach (var v in treeMember.m_ChildMembers)
                        {
                            processLevel(v, level + "_");
                        }
                    };

                    processLevel(GPUProfiler.m_CurrentFrameProfilerTree, "");
                }

                CheckAndUpdateDebugUI(context, form);

                if (++counter == 10)
                {
                    UpdateControls();
                    DataGridView dataGridView = form.GetDataGridView();
                    dataGridView.Rows.Clear();

                    foreach (var profilerEntry in profilers)
                    {
                        DataGridViewRow row = new DataGridViewRow();
                        row.CreateCells(dataGridView);
                        row.Cells[0].Value = profilerEntry.Key;
                        row.Cells[1].Value = String.Format("{0}", Math.Round(profilerEntry.Value * 100.0 / 10.0) / 100.0);
                        dataGridView.Rows.Add(row);
                    }

                    profilers.Clear();

                    counter = 0;
                }
                else
                {
                    // avoid 2ms frame times...
                    System.Threading.Thread.Sleep(10);
                }
            });
        }
Beispiel #28
0
        static void Main()
        {
            var form = new RenderForm("DotRocket/SlimDX example");

            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
            };

            // Setup rendering
            Device    device;
            SwapChain swapChain;

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

            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);
            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);

            // Prevent alt+enter (broken on WinForms)
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // Setup audio-streaming
            XAudio2 xaudio2 = new XAudio2();

            stream = new XWMAStream("tune.xwma");
            MasteringVoice masteringVoice = new MasteringVoice(xaudio2);

            sourceVoice            = new SourceVoice(xaudio2, stream.Format);
            audioBuffer            = new AudioBuffer();
            audioBuffer.AudioData  = stream;
            audioBuffer.AudioBytes = (int)stream.Length;
            audioBuffer.Flags      = BufferFlags.EndOfStream;
            sourceVoice.SubmitSourceBuffer(audioBuffer, stream.DecodedPacketsInfo);
            sourceVoice.Start();

            // Setup DotRocket
#if DEBUG
            DotRocket.Device rocket = new DotRocket.ClientDevice("sync");
            rocket.OnPause     += Pause;
            rocket.OnSetRow    += SetRow;
            rocket.OnIsPlaying += IsPlaying;
            rocket.Connect("localhost", 1338);
#else
            DotRocket.Device rocket = new DotRocket.PlayerDevice("sync");
#endif

            // Get our belowed tracks!
            DotRocket.Track clear_r = rocket.GetTrack("clear.r");
            DotRocket.Track clear_g = rocket.GetTrack("clear.g");
            DotRocket.Track clear_b = rocket.GetTrack("clear.b");

            MessagePump.Run(form, () =>
            {
                // Hammertime.
                double row = ((double)(sourceVoice.State.SamplesPlayed - samplesBias) / stream.Format.SamplesPerSecond) * rowRate;

                // Paint some stuff.
                rocket.Update((int)System.Math.Floor(row));
                context.ClearRenderTargetView(renderTarget, new Color4(
                                                  clear_r.GetValue(row),
                                                  clear_g.GetValue(row),
                                                  clear_b.GetValue(row)));
                swapChain.Present(0, PresentFlags.None);
            });

            // clean up all resources
            // anything we missed will show up in the debug output
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }
Beispiel #29
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);
        }
Beispiel #30
0
        private void InitializeResources()
        {
            var backBuffer = Resource.FromSwapChain <Texture2D>(swapChain, 0);

            // Defining render view
            var renderTargetView = new RenderTargetView(device11, backBuffer);

            backBuffer.Dispose();

            device11.ImmediateContext.OutputMerger.SetTargets(renderTargetView);
            renderTargetView.Dispose();

            device11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, ClientSize.Width, ClientSize.Height, 0.0f, 1.0f));

            using (var byteCode = ShaderBytecode.CompileFromFile("Effet.fx", "bidon", "fx_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None))
            {
                effect = new Effect(device11, byteCode);
            }

            var technique = effect.GetTechniqueByIndex(0);
            var pass      = technique.GetPassByIndex(0);

            layout = new InputLayout(device11, pass.Description.Signature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0)
            });

            device11.ImmediateContext.InputAssembler.InputLayout = layout;

            // Texture
            var rasterizerStateDescription = new RasterizerStateDescription {
                CullMode = CullMode.None, FillMode = FillMode.Solid
            };

            var rstate = RasterizerState.FromDescription(device11, rasterizerStateDescription);

            device11.ImmediateContext.Rasterizer.State = rstate;
            rstate.Dispose();

            var rnd = new Random();

            // Creating vertex buffer
            var vertices2 = new float[featureCount * 4 * 2];

            for (var i = 0; i < vertices2.Length;)
            {
                var x = (float)rnd.NextDouble() * 250000;
                var y = (float)rnd.NextDouble() * (float)Math.PI * 2;
                var w = (float)rnd.NextDouble() * 3;
                var h = (float)rnd.NextDouble() * (float)Math.PI * 2 / 20.0f;

                vertices2[i++] = x;
                vertices2[i++] = y;

                vertices2[i++] = x + w;
                vertices2[i++] = y;

                vertices2[i++] = x;
                vertices2[i++] = y + h;

                vertices2[i++] = x + w;
                vertices2[i++] = y + h;
            }

            var stream = new DataStream(featureCount * 4 * vertexSize, true, true);

            stream.WriteRange(vertices2);
            stream.Position = 0;

            var vertexBuffer = new Buffer(device11, stream, new BufferDescription
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = (int)stream.Length,
                Usage          = ResourceUsage.Default
            });

            stream.Dispose();

            device11.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, vertexSize, 0));
            vertexBuffer.Dispose();

            // for quads, 6 indices per feature
            var indices1 = new int[featureCount * 6];

            for (int j = 0; j < featureCount; j++)
            {
                indices1[j * 6 + 0] = j * 4 + 0;
                indices1[j * 6 + 1] = j * 4 + 1;
                indices1[j * 6 + 2] = j * 4 + 2;

                indices1[j * 6 + 3] = j * 4 + 1;
                indices1[j * 6 + 4] = j * 4 + 2;
                indices1[j * 6 + 5] = j * 4 + 3;
            }

            stream = new DataStream(featureCount * 6 * sizeof(int), true, true);
            stream.WriteRange(indices1);
            stream.Position = 0;

            indicesb1 = new Buffer(device11, stream, new BufferDescription
            {
                BindFlags      = BindFlags.IndexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = (int)stream.Length,
                Usage          = ResourceUsage.Default
            });
            stream.Dispose();

            // for lines, 8 indices per feature
            var indices2 = new int[featureCount * 8];

            for (int j = 0; j < featureCount; j++)
            {
                indices2[j * 8 + 0] = j * 4 + 0;
                indices2[j * 8 + 1] = j * 4 + 1;

                indices2[j * 8 + 2] = j * 4 + 1;
                indices2[j * 8 + 3] = j * 4 + 3;

                indices2[j * 8 + 4] = j * 4 + 3;
                indices2[j * 8 + 5] = j * 4 + 2;

                indices2[j * 8 + 6] = j * 4 + 2;
                indices2[j * 8 + 7] = j * 4 + 0;
            }

            stream = new DataStream(featureCount * 8 * sizeof(int), true, true);
            stream.WriteRange(indices2);
            stream.Position = 0;

            indicesb2 = new Buffer(device11, stream, new BufferDescription
            {
                BindFlags      = BindFlags.IndexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = (int)stream.Length,
                Usage          = ResourceUsage.Default
            });
            stream.Dispose();
        }