Exemple #1
0
        /// <summary>
        /// Initialize for on-screen rendering
        /// </summary>
        public void Initialize(IntPtr outputHandle)
        {
            Debug.Assert(Initialized == false);

            if (UseMsaa)
            {
                InitializeDevice().Dispose();
            }

            _swapChainDescription = new SwapChainDescription {
                BufferCount       = 2,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = outputHandle,
                SampleDescription = SampleDescription,
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device device;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, _swapChainDescription, out device, out _swapChain);
            SetDeviceContextHolder(new DeviceContextHolder(device));

            using (var factory = _swapChain.GetParent <Factory>()) {
                factory.SetWindowAssociation(outputHandle, WindowAssociationFlags.IgnoreAll);
            }

            InitializeInner();
            Initialized = true;
        }
Exemple #2
0
        public D3DManager(Form renderForm)
        {
            if (renderForm == null)
            {
                throw new ArgumentNullException("renderForm");
            }

            var swapChainDescription = new SwapChainDescription {
                BufferCount       = 1,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(renderForm.ClientSize.Width, renderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = renderForm.Handle,
                SampleDescription = new SampleDescription(4, 4),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

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

            SwapChain.GetParent <Factory>().SetWindowAssociation(renderForm.Handle, WindowAssociationFlags.IgnoreAll);

            CreateRenderTargets(renderForm.ClientSize.Width, renderForm.ClientSize.Height);

            Device.ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            Device.ImmediateContext.Rasterizer.State = RasterizerState.FromDescription(Device,
                                                                                       new RasterizerStateDescription {
                CullMode             = CullMode.Back,
                FillMode             = FillMode.Solid,
                IsMultisampleEnabled = true
            });
        }
Exemple #3
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);
            };
        }
Exemple #4
0
        public void InitDirectX()
        {
            if (IsDirectXInitialized)
            {
                throw new InvalidOperationException();
            }
            form             = new RenderForm("The Wizards - DirectX 11");
            form.Activated  += new EventHandler(form_Activated);
            form.Deactivate += new EventHandler(form_Deactivate);
            form.Size        = FormSize;
            //form.Width = (int)FormSize.X;
            //form.Height = (int)FormSize.Y;
            //form.TopMost = true;
            //WARNING: THERE IS ONLY ONE BUFFER ATM. (no backbuffer?)
            var desc = new SwapChainDescription
            {
                BufferCount = 3,                // Set to 3 here for triple buffering?
                //ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(0, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),                // No multisampling!
                //SampleDescription = ne w SampleDescription(4, 0),
                SwapEffect = SwapEffect.Discard,
                Usage      = Usage.RenderTargetOutput | Usage.BackBuffer,           // backbuffer added, no clue wat it does
            };



            try
            {
                //Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to initialize device in Debug Mode. Running in normal mode instead!");
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            }



            //var result = device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 2);


            var factory = swapChain.GetParent <Factory>();

            factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);

            renderTargetView = new RenderTargetView(device, BackBuffer);



            device.ImmediateContext.OutputMerger.SetTargets(renderTargetView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
        }
        public void Initialize(Device3dInit initStruct)
        {
            // store info from initStruct
            m_hWindow = initStruct.hWindow;

            // device state
            m_CurrRenderTargets = new RenderTargetView[4];
            m_CurrViewports     = new Viewport[4];

            {
                // swap chain
                var desc = new SwapChainDescription()
                {
                    BufferCount       = 1,
                    ModeDescription   = new ModeDescription(initStruct.iScreenWidth, initStruct.iScreenHeight, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    IsWindowed        = true,
                    OutputHandle      = m_hWindow.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect        = SwapEffect.Discard,
                    Usage             = Usage.RenderTargetOutput
                };
                // create device and swap chain
                DeviceCreationFlags flags = DeviceCreationFlags.Debug;
                SlimDXDevice11.CreateWithSwapChain(DriverType.Hardware, flags, desc, out m_D3dDevice, out m_SwapChain);

                // [Q] what SetWindowAssociation() is about?
#warning "[Q] what SetWindowAssociation() is about?"
                m_D3dDevice.Factory.SetWindowAssociation(initStruct.hWindow.Handle, WindowAssociationFlags.IgnoreAll);
            }

            // create back buffers
            Texture2D backBuffer       = Texture2D.FromSwapChain <Texture2D>(m_SwapChain, 0);
            var       renderTargetView = new RenderTargetView(m_D3dDevice, backBuffer);
            m_RTVList.Add("BackBuffer", renderTargetView);
            // create depth buffer
            CreateDepthStencilBuffer(new CreateDepthStencilBufferCmd()
            {
                Name   = "BackBuffer",
                Width  = m_hWindow.ClientSize.Width,
                Height = m_hWindow.ClientSize.Height
            });

            // create viewport
            var viewport = new Viewport(0.0f, 0.0f, m_hWindow.ClientSize.Width, m_hWindow.ClientSize.Height, 0.0f, 1.0f);
            m_ViewportList.Add("Default", viewport);
            SetViewport("Default");

            // set our render pipeline to the default state
            m_D3dDevice.ImmediateContext.Rasterizer.SetViewports(m_CurrViewports);
            m_D3dDevice.ImmediateContext.OutputMerger.SetTargets(m_CurrDepthStencil, m_CurrRenderTargets);

            // success
            Debug.Helper.Log("Device3d D3d11 is successfully initialized");
        }
Exemple #6
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);
        }
Exemple #7
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);
        }
        protected override void OnInitialization(Graphics3DConfiguration config)
        {
            if (GraphicsDirect3D11.Device != null)
            {
                throw new Graphics3DStateException("Cannot do device initialization: Device already initialized!");
            }

            Device11 device = null;

            Device11.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, Direct3DConverter11.ConvertToSwapChainDescription(config), out device, out swapChain);
            //Setup device to main device
            GraphicsDirect3D11.Device = device;

            SetupRenderTarget();
        }
Exemple #9
0
            //// RESOURCE MANAGEMENT
            //// maybe some of this can be moved to util class too?

            public static void InitDevice()
            {
                var description = new SwapChainDescription()
                {
                    BufferCount       = 1,
                    Usage             = Usage.RenderTargetOutput,
                    OutputHandle      = Data.Window.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 Data.DX11Device, out Data.DX11SwapChain);
                Data.DX11Device.Factory.SetWindowAssociation(Data.Window.Handle, WindowAssociationFlags.IgnoreAll);
            }
Exemple #10
0
        public DxDeviceContext(IntPtr formHandle, Control renderAreaObject, bool fullscreen)
        {
            _isFullscreen = fullscreen;

            SwapChainDescription desc = new SwapChainDescription();

            if (fullscreen)
            {
                throw new ApplicationException("Not implemented yet");
            }
            else
            {
                FrameWidth  = renderAreaObject.Width;
                FrameHeight = renderAreaObject.Height;

                desc.BufferCount     = 1;
                desc.ModeDescription = new ModeDescription(FrameWidth,
                                                           FrameHeight,
                                                           new SlimDX.Rational(60, 1),
                                                           Format.R8G8B8A8_UNorm);
                desc.IsWindowed = true;
                desc.SwapEffect = SwapEffect.Discard;
            }

            desc.OutputHandle      = renderAreaObject.Handle;
            desc.SampleDescription = new SampleDescription(1, 0);
            desc.Usage             = Usage.RenderTargetOutput;

            Device    dev;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out dev, out swapChain);
            Device    = dev;
            SwapChain = swapChain;
            Device.Factory.SetWindowAssociation(renderAreaObject.Handle, WindowAssociationFlags.IgnoreAll);

            _dInput = new DirectInput();
            CooperativeLevel cooLevel = CooperativeLevel.Foreground;

            cooLevel |= CooperativeLevel.Nonexclusive;
            _mouse    = new Mouse(_dInput);
            _mouse.SetCooperativeLevel(formHandle, cooLevel);

            _shaderByteCode = ShaderBytecode.CompileFromFile(GetFxFile(), "fx_5_0", ShaderFlags.None, EffectFlags.None);
            Effect          = new SlimDX.Direct3D11.Effect(Device, _shaderByteCode);
        }
Exemple #11
0
        // RESOURCE MANAGEMENT
        // maybe some of this can be moved to util class too?

        private void InitDevice()
        {
            if (overlay == null)
            {
                throw new Exception("Overlay not set.");
            }
            var description = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = overlay.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);
            device.Factory.SetWindowAssociation(overlay.Handle, WindowAssociationFlags.IgnoreAll);
        }
Exemple #12
0
        public override void Initialize()
        {
            Device    tmpDevice;
            SwapChain sc;

            using (var rf = new RenderForm())
            {
                var desc = new SwapChainDescription
                {
                    BufferCount     = 1,
                    Flags           = SwapChainFlags.None,
                    IsWindowed      = true,
                    ModeDescription =
                        new ModeDescription(100, 100, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    OutputHandle      = rf.Handle,
                    SampleDescription = new SampleDescription(1, 0),
                    SwapEffect        = SwapEffect.Discard,
                    Usage             = Usage.RenderTargetOutput
                };

                Result res = Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc,
                                                        out tmpDevice, out sc);
                if (res.IsSuccess)
                {
                    using (tmpDevice)
                    {
                        using (sc)
                        {
                            PresentPointer     = GeneralHelper.Memory.GetVFTableEntry(sc.ComPointer, VMT_PRESENT);
                            ResetTargetPointer = GeneralHelper.Memory.GetVFTableEntry(sc.ComPointer,
                                                                                      VMT_RESIZETARGET);
                        }
                    }
                }
            }

            _presentDelegate = GeneralHelper.Memory.CreateFunction <Direct3D11Present>(PresentPointer);
            _presentHook     = GeneralHelper.Memory.Detours.CreateAndApply(_presentDelegate, new Direct3D11Present(Callback),
                                                                           "D11Present");
        }
Exemple #13
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();
        }
Exemple #14
0
        //============================================================
        public void Setup(int width, int height)
        {
            // 创建设备
            SwapChainDescription description = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = false,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput,
            };

#if DEBUG
            DxDevice.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out _nativeAdapter, out _nativeSwap);
#else
            DxDevice.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out _nativeAdapter, out _nativeSwap);
#endif
            _nativeDevice = _nativeAdapter.ImmediateContext;
            // 设置缓冲大小
            ConfigureBackBuffer(width, height);
        }
Exemple #15
0
        protected void Createdevice()
        {
            if (_device != null)
            {
                _device.Dispose();
            }

            var description = new SwapChainDescription
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = OutputhandlePtr,
                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);
        }
Exemple #16
0
        private void CreateDeviceAndSwapChain()
        {
            // 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
            var 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);
        }
Exemple #17
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);
        }
Exemple #18
0
        private void FormMain_Shown(object sender, System.EventArgs e)
        {
            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = this.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            screenPixelRateX = 2f / (float)this.Width;
            screenPixelRateY = 2f / (float)this.Height;
            Device11.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out mainD11, out mainSC);
            mainD11.Factory.SetWindowAssociation(this.Handle, WindowAssociationFlags.IgnoreAll);

            WaitCallback wcb = new WaitCallback(this.DoRenderLoop);

            ThreadPool.QueueUserWorkItem(wcb, null);

            running = true;
        }
Exemple #19
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;
        }
Exemple #20
0
        public static void Initialize3D(IntPtr handle, int viewPortWidth, int viewPortHeight)
        {
            #region Set Swapchain and Viewport
            var swapDiscription = new SwapChainDescription()
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = handle,
                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, swapDiscription, out device, out swapChain);
            swapChain.IsFullScreen = false;
            context = device.ImmediateContext;
            using (var factory = swapChain.GetParent <FactoryDXGI>())
                factory.SetWindowAssociation(handle, WindowAssociationFlags.IgnoreAltEnter);
            viewport = new Viewport(0, 0, viewPortWidth, viewPortHeight);
            context.Rasterizer.SetViewports(viewport);
            #endregion
            #region Set RenderTarget and DepthStencil
            SetTargetAndDepthSView(viewPortWidth, viewPortHeight);
            #endregion
            #region Set Blend&RasterizerStates
            RasterizerStateDescription backCull = new RasterizerStateDescription()
            {
                FillMode = SlimDX.Direct3D11.FillMode.Solid,
                CullMode = CullMode.Back,
                IsFrontCounterclockwise = true,
                IsDepthClipEnabled      = true
            };

            backCullState = RasterizerState.FromDescription(device, backCull);

            BlendStateDescription transDesc = new BlendStateDescription()
            {
                AlphaToCoverageEnable  = false,
                IndependentBlendEnable = false
            };
            transDesc.RenderTargets[0].BlendEnable           = true;
            transDesc.RenderTargets[0].SourceBlend           = BlendOption.SourceAlpha;
            transDesc.RenderTargets[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            transDesc.RenderTargets[0].BlendOperation        = BlendOperation.Add;
            transDesc.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
            transDesc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
            transDesc.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
            transDesc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            transBlendState = BlendState.FromDescription(device, transDesc);

            context.Rasterizer.State        = backCullState;
            context.OutputMerger.BlendState = transBlendState;
            #endregion

            LoadShaders();
            LoadInputLayouts();

            worldMatrix = Matrix.Translation(-8, 0, -8);
            projMatrix  = Matrix.PerspectiveFovRH(FOV, (float)viewPortWidth / viewPortHeight, 0.01f, 1000.0f);
            SetupCamera();
            grid = new CoordinateGrid(new Color4(0.95f, 0.95f, 0.95f));
        }
Exemple #21
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            SwapChainDescription desc = new SwapChainDescription()
            {
                BufferCount     = 2,
                Flags           = SwapChainFlags.AllowModeSwitch,
                IsWindowed      = true,
                ModeDescription = new ModeDescription()
                {
                    Format           = Format.R8G8B8A8_UNorm,
                    Height           = Height,
                    Width            = Width,
                    RefreshRate      = new Rational(1, 60),
                    Scaling          = DisplayModeScaling.Centered,
                    ScanlineOrdering = DisplayModeScanlineOrdering.Progressive
                },
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None,
                                       new FeatureLevel[1] {
                FeatureLevel.Level_11_0
            }, desc, out device, out swapChain);
            using (Texture2D tex = Texture2D.FromSwapChain <Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, tex);
            }
            using (Texture2D depthTex = new Texture2D(device, new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                Width = Width,
                Height = Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                Format = Format.D32_Float,
                CpuAccessFlags = CpuAccessFlags.None,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            }))
            {
                depthTarget = new DepthStencilView(device, depthTex);
            }
            //四角形の頂点を表すリスト
            Vector4[] verticies = new Vector4[]
            {
                new Vector4(-0.5f, 0.75f, 5f, 1f),//左上手前の三角形
                new Vector4(0f, 0f, 5f, 1f),
                new Vector4(-1f, 0f, 5f, 1f),


                new Vector4(0f, 1f, 10f, 1f),//中央奥の大きい三角形
                new Vector4(1f, -0.5f, 10f, 1f),
                new Vector4(-1f, -0.5f, 10f, 1f),
            };
            using (DataStream ds = new DataStream(verticies, true, true))
            {
                vertexBuffer = new Buffer(device, ds, new BufferDescription()
                {
                    BindFlags   = BindFlags.VertexBuffer,
                    SizeInBytes = (int)ds.Length,
                });
            }
            using (ShaderBytecode compiledCode = ShaderBytecode.CompileFromFile("shader.fx", "fx_5_0", ShaderFlags.Debug, EffectFlags.None))
            {
                effect = new Effect(device, compiledCode);
            }
            inputLayout = new InputLayout(device, effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new InputElement[]
            {
                new InputElement()
                {
                    SemanticName = "POSITION",
                    Format       = Format.R32G32B32A32_Float
                },
            });
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport[] { new Viewport(0, 0, Width, Height, 0, 1), });
            projection = Matrix.PerspectiveFovLH((float)Math.PI / 4f, Width / Height, 0.1f, 15);
        }
Exemple #22
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - MiniTri Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device    device;
            SwapChain swapChain;

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

            Factory factory = swapChain.GetParent <Factory>();

            factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);
            var       bytecode   = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var       effect     = new Effect(device, bytecode);
            var       technique  = effect.GetTechniqueByIndex(0);
            var       pass       = technique.GetPassByIndex(0);
            var       layout     = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            var stream = new DataStream(3 * 32, true, true);

            stream.WriteRange(new[] {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
            });
            stream.Position = 0;

            var vertices = new SlimDX.Direct3D11.Buffer(device, stream, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = 3 * 32,
                Usage          = ResourceUsage.Default
            });

            stream.Dispose();

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));

            MessagePump.Run(form, () =>
            {
                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                device.ImmediateContext.InputAssembler.InputLayout       = layout;
                device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0));

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    device.ImmediateContext.Draw(3, 0);
                }

                swapChain.Present(0, PresentFlags.None);
            });

            bytecode.Dispose();
            vertices.Dispose();
            layout.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
Exemple #23
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();
        }
Exemple #24
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - Conway's game of life Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device    device;
            SwapChain swapChain;

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

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);
            var       bytecode   = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var       effect     = new Effect(device, bytecode);
            var       technique  = effect.GetTechniqueByIndex(0);
            var       pass       = technique.GetPassByIndex(0);
            String    errors;
            var       computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
            var       compute         = new ComputeShader(device, computeByteCode);

            // shader variable handles
            var conwayResourceH = effect.GetVariableByName("tex").AsResource();
            var resolutionInvH  = effect.GetVariableByName("resolutionInv").AsVector();

            resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
            EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();

            // create texture, fill it with random data
            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                Width             = form.ClientSize.Width,
                Height            = form.ClientSize.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                CpuAccessFlags    = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                BindFlags         = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
                Format            = Format.R32_Float
            };

            var random = new Random();
            var data   = new float[form.ClientSize.Width * form.ClientSize.Height];

            for (int i = 0; i < form.ClientSize.Width; ++i)
            {
                for (int j = 0; j < form.ClientSize.Height; ++j)
                {
                    data[i * form.ClientSize.Height + j] = (float)random.Next(2);
                }
            }

            DataStream    ds       = new DataStream(data, true, false);
            DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);

            Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);

            // Create SRV and UAV over the same texture
            UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
            ShaderResourceView  conwaySRV = new ShaderResourceView(device, conwayTex);

            // On the more typical setup where you switch shaders,
            // you will have to set the texture after every
            conwayResourceH.SetResource(conwaySRV);

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            Vector2 lightPosSS;
            float   angle = 0;

            MessagePump.Run(form, () =>
            {
                // this does the light rotation
                angle     += 0.002f;
                lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
                lightPosSSH.Set(lightPosSS);

                device.ImmediateContext.ComputeShader.Set(compute);
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
                device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);

                // After running the CS you have to unset UAV from the shader, so you can use it as SRV
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);

                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    // No vertices are send as they are created in the vertex shader on the fly.
                    device.ImmediateContext.Draw(4, 0);
                }

                swapChain.Present(0, PresentFlags.None);
            });

            computeByteCode.Dispose();
            conwayUAV.Dispose();
            conwaySRV.Dispose();
            conwayTex.Dispose();
            ds.Dispose();
            bytecode.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
        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;
        }
Exemple #26
0
        public void Init()
        {
            #region init_gfx
            Form = new RenderForm("Kazedan");
            var   factory = new FactoryD2D();
            SizeF dpi     = factory.DesktopDpi;

            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = Form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription((int)(GFXResources.Bounds.Width * (dpi.Width / 96f)), (int)(GFXResources.Bounds.Height * (dpi.Height / 96f)), new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
            };

            Device    device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapChainDesc, out device, out swapChain);

            Surface backBuffer = Surface.FromSwapChain(swapChain, 0);

            renderTarget = RenderTarget.FromDXGI(factory, backBuffer, new RenderTargetProperties()
            {
                HorizontalDpi       = dpi.Width,
                VerticalDpi         = dpi.Height,
                MinimumFeatureLevel = SlimDX.Direct2D.FeatureLevel.Default,
                PixelFormat         = new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Ignore),
                Type  = RenderTargetType.Default,
                Usage = RenderTargetUsage.None
            });
            factory.Dispose();

            // Freaking antialiasing lagging up my programs
            renderTarget.AntialiasMode     = AntialiasMode.Aliased;
            renderTarget.TextAntialiasMode = TextAntialiasMode.Grayscale;

            using (var DXGIFactory = swapChain.GetParent <FactoryDXGI>())
                DXGIFactory.SetWindowAssociation(Form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            Form.ClientSize   = GFXResources.Bounds;
            Form.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            Form.Icon         = Properties.Resources.KazedanIcon;
            #endregion

            GFXResources.Init(renderTarget);

            Form.KeyDown += (o, e) =>
            {
                Keys key = e.KeyCode;
                switch (key)
                {
                case Keys.F11:
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
                    break;

                case Keys.F:
                    Sequencer.NoteManager.UserEnabledFancy = !Sequencer.NoteManager.UserEnabledFancy;
                    Sequencer.NoteManager.RenderFancy      = Sequencer.NoteManager.UserEnabledFancy;
                    break;

                case Keys.Up:
                    Sequencer.Delay += 100;
                    Sequencer.Reset();
                    break;

                case Keys.Down:
                    if (Sequencer.Delay >= 100)
                    {
                        Sequencer.Delay -= 100;
                        Sequencer.Reset();
                    }
                    break;

                case Keys.Left:
                    if (GFXResources.NoteOffset > 0)
                    {
                        GFXResources.NoteOffset--;
                    }
                    break;

                case Keys.Right:
                    if (GFXResources.NoteOffset < 128 - GFXResources.NoteCount)
                    {
                        GFXResources.NoteOffset++;
                    }
                    break;

                case Keys.D:
                    Sequencer.ShowDebug = !Sequencer.ShowDebug;
                    break;

                case Keys.Space:
                    if (Sequencer.Stopped)
                    {
                        Sequencer.Start();
                    }
                    else
                    {
                        Sequencer.Stop();
                    }
                    break;
                }
            };

            // Start loading thread
            Thread loadThread = new Thread(Load);
            loadThread.Start();

            // Show controller window
            Thread controlThread = new Thread(() =>
            {
                loadThread.Join();
                Application.EnableVisualStyles();
                ControlForm = new KZControl(Sequencer);
                Application.Run(ControlForm);
            });
            controlThread.SetApartmentState(ApartmentState.STA);
            controlThread.Start();

            // Make sure the control form closes when the main form does
            Form.Disposed += (o, e) =>
            {
                ControlForm?.BeginInvoke((MethodInvoker) delegate
                {
                    ControlForm.Close();
                });
            };

            MessagePump.Run(Form, () =>
            {
                // Do sequencer tick
                if (!Sequencer.Stopped)
                {
                    Sequencer.UpdateNotePositions();
                    Sequencer.UpdateRenderer();
                }
                Paint(renderTarget);

                // Calculate profiling information
                long tick = Environment.TickCount;
                if (tick - LastSample >= SampleRate)
                {
                    Elapsed    = tick - LastTick;
                    LastSample = tick;
                }
                LastTick = tick;
                swapChain.Present(1, PresentFlags.None);
            });

            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
            Sequencer.Dispose();
        }
Exemple #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);
        }
Exemple #28
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
        }
        public Renderer3d(String title)
        {
            m_scenes = new List <Scene>();

            cameras_ = new List <Camera>();

            samplerStates_ = new Dictionary <string, SamplerState>();

            lastTime_ = DateTime.Now;

            form_        = new RenderForm(title);
            form_.Width  = 1024;
            form_.Height = 768;

            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(form_.ClientSize.Width, form_.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form_.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device_, out swapChain_);

            Factory factory = swapChain_.GetParent <Factory>();

            factory.SetWindowAssociation(form_.Handle, WindowAssociationFlags.IgnoreAll);

            backBuffer_ = Texture2D.FromSwapChain <Texture2D>(swapChain_, 0);
            renderView_ = new RenderTargetView(device_, backBuffer_);


            var depthDesc = new Texture2DDescription()
            {
                Width             = form_.Width,
                Height            = form_.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                Usage          = ResourceUsage.Default,
                BindFlags      = BindFlags.DepthStencil,
                CpuAccessFlags = 0,
                OptionFlags    = 0
            };

            m_depthBuffer = new Texture2D(device_, depthDesc);

            device_.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form_.ClientSize.Width, form_.ClientSize.Height, 0.1f, 1.0f));

            RasterizerStateDescription descRast = new RasterizerStateDescription()
            {
                FillMode           = FillMode.Solid,
                CullMode           = CullMode.None,
                IsDepthClipEnabled = true
            };

            m_rasterizerState = RasterizerState.FromDescription(device_, descRast);

            DepthStencilStateDescription dsStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled  = true,
                DepthWriteMask  = DepthWriteMask.All,
                DepthComparison = Comparison.Less,

                IsStencilEnabled = true,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    DepthFailOperation = StencilOperation.Increment,
                    FailOperation      = StencilOperation.Keep,
                    PassOperation      = StencilOperation.Keep
                },

                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    DepthFailOperation = StencilOperation.Increment,
                    FailOperation      = StencilOperation.Keep,
                    PassOperation      = StencilOperation.Keep
                },
            };

            DepthStencilState dsState = DepthStencilState.FromDescription(device_, dsStateDesc);

            device_.ImmediateContext.OutputMerger.DepthStencilState = dsState;
            device_.ImmediateContext.Rasterizer.State = m_rasterizerState;

            DepthStencilViewDescription DSVDesc = new DepthStencilViewDescription()
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice  = 0
            };

            m_depthView = new DepthStencilView(device_, m_depthBuffer, DSVDesc);

            dsState.Dispose();

            device_.ImmediateContext.OutputMerger.SetTargets(m_depthView, renderView_);

            CreateSamplers();
        }
Exemple #30
0
        /// <summary>
        /// Initializes SlimDX and input devices.
        /// </summary>
        /// <param name="caption">Window caption string.</param>
        public FrameworkForm(string caption)
            : base(caption)
        {
            SwapChainDescription description = new SwapChainDescription()
            {
                BufferCount       = 1,
                Flags             = SwapChainFlags.None,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(ClientSize.Width, ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            try
            {
#if DEBUG
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out graphicsDevice, out swapChain);
#else
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out graphicsDevice, out swapChain);
#endif
            }
            catch
            {
                MessageBox.Show("An error has occurred during initialization process.");
                Environment.Exit(0);
            }
            finally
            {
                if (graphicsDevice.FeatureLevel != FeatureLevel.Level_11_0)
                {
                    MessageBox.Show("This program requires DirectX 11. Your version is " + graphicsDevice.FeatureLevel.ToString() + ".");
                    Environment.Exit(0);
                }
            }

            Factory factory = swapChain.GetParent <Factory>();
            factory.SetWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter);
            KeyDown += (o, e) =>
            {
                // Fixes Alt-Enter keyboard input bug in SlimDX.
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
                }

                // Makes screenshot.
                if (e.KeyCode == Keys.F12)
                {
                    MakeScreenshot(Application.StartupPath);
                }
            };

            SizeChanged += (o, e) =>
            {
                // Dispose old resources.
                if (renderTargetView != null)
                {
                    renderTargetView.Dispose();
                }
                if (backBufferTexture != null)
                {
                    backBufferTexture.Dispose();
                }

                // Resize buffers.
                swapChain.ResizeBuffers(1, ClientSize.Width, ClientSize.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

                InitializeOutputMerger();

                camera.UpdateProjection();

                postProcess.Initialize(ClientSize.Width, ClientSize.Height);
            };

            fillMode = FillMode.Solid;
            InitializeOutputMerger();

            // Initializes input devices.
            DirectInput directInput = new DirectInput();
            keyboard = new Keyboard(directInput);
            keyboard.Acquire();
            mouse = new Mouse(directInput);
            mouse.Acquire();

            camera       = new Camera(graphicsDevice, new Vector3(50, 50, 50), new Vector3(0, 0, 0), 0.1f, 1000.0f);
            textures     = new List <TexturePack>();
            postProcess  = new PostProcess(graphicsDevice, ClientSize.Width, ClientSize.Height);
            quadRenderer = new QuadRenderer(graphicsDevice);
        }