Ejemplo n.º 1
0
 public void Resize(int size)
 {
     m_Handle?.Dispose();
     m_Size             = size;
     m_Desc.SizeInBytes = m_Size;
     m_Handle           = new SharpDX.Direct3D11.Buffer(Context.Instance.Dev, m_Desc);
 }
Ejemplo n.º 2
0
        public void Dispose()
        {
            System.Console.WriteLine("Renderer3d.Dispose");
            if (context != null)
            {
                DiscardDeviceResources();

                textureCollection?.Dispose();
                textureLoader?.Dispose();

                cb_shader_flags?.Dispose();
                cb_mat?.Dispose();
                cb_wvp?.Dispose();

                foreach (NiFile nif in nifs)
                {
                    foreach (Mesh mesh in nif.meshes)
                    {
                        mesh.Dispose();
                    }
                }

                context.ClearState();
                context.Flush();
                context.Dispose();
                context = null;
            }
            skeleton = null;
            device   = null;
        }
        public override void Dispose()
        {
            PerObjConstantBuffer?.Dispose();
            PerObjConstantBuffer = null;
            PerFrameConstantBuffer?.Dispose();
            PerFrameConstantBuffer = null;
            LightIndexBuffer?.Dispose();
            LightIndexBuffer = null;
            LightCenterAndRadiusBuffer?.Dispose();
            LightCenterAndRadiusBuffer = null;
            LightColorBuffer?.Dispose();
            LightColorBuffer = null;
            LightParamsBuffer?.Dispose();
            LightParamsBuffer = null;
            DirLightBuffer?.Dispose();
            DirLightBuffer = null;

            LightCenterAndRadiusSRV?.Dispose();
            LightCenterAndRadiusSRV = null;
            LightColorSRV?.Dispose();
            LightColorSRV = null;
            LightParamsSRV?.Dispose();
            LightParamsSRV = null;
            LightIndexSRV?.Dispose();
            LightIndexSRV = null;
            LightIndexURV?.Dispose();
            LightIndexURV = null;
        }
Ejemplo n.º 4
0
            private void BuildGeometry()
            {
                lock (_terrain.Locker)
                {
                    _vertexBuffer?.Dispose();
                    _indexBuffer?.Dispose();
                }

                TerrainVertex[] vertices;
                ushort[]        indices;

                _terrain._surfaceExtractor.GenLodCell(this, 1, out vertices, out indices);


                if (vertices.Length == 0)
                {
                    _geometryDirty = false;
                    return;
                }

                lock (_terrain.Locker)
                {
                    _vertexBuffer        = Buffer.Create(Renderer.Device, BindFlags.VertexBuffer, vertices);
                    _indexBuffer         = Buffer.Create(Renderer.Device, BindFlags.IndexBuffer, indices);
                    _vertexBufferBinding = new VertexBufferBinding(_vertexBuffer, TerrainVertex.Stride, 0);
                }

                _indexCount    = indices.Length;
                _geometryDirty = false;
            }
Ejemplo n.º 5
0
 public void SetOnly <VType>(VType[] vertices, int[] indices) where VType : struct
 {
     VertexBuffer?.Dispose( );
     IndexBuffer?.Dispose( );
     VertexBuffer = Buffer11.Create <VType>(Device.Device, BindFlags.VertexBuffer, vertices);
     IndexBuffer  = Buffer11.Create(Device.Device, BindFlags.IndexBuffer, indices);
     VertexSize   = SharpDX.Utilities.SizeOf <VType>();
 }
Ejemplo n.º 6
0
        public void Shutdown()
        {
            vertexBuffer_?.Dispose();
            vertexBuffer_ = null;

            indexBuffer_?.Dispose();
            indexBuffer_ = null;
        }
Ejemplo n.º 7
0
        private void ShutdownBuffers()
        {
            _indexBuffer?.Dispose();
            _indexBuffer = null;

            _vertexBuffer?.Dispose();
            _vertexBuffer = null;
            return;
        }
        public void Dispose()
        {
            _BufferDataStream?.Dispose();
            _BufferDataStream = null;

            D3D定数バッファ?.Dispose();
            D3D定数バッファ = null;

            _D3Dエフェクト定数バッファ = null;
        }
Ejemplo n.º 9
0
        public void Dispose()
        {
            VertexBuffer?.Dispose();
            IndexBuffer?.Dispose();

            DiffuseTextureView?.Dispose();
            EmissiveTextureView?.Dispose();
            SpecularTextureView?.Dispose();
            NormalTextureView?.Dispose();
        }
Ejemplo n.º 10
0
        public void Dispose()
        {
            constBuffer?.Dispose();
            for (int i = 0; i < TextureViews.Length; i++)
            {
                TextureViews[i]?.Dispose();
            }

            constBuffer = null;
        }
Ejemplo n.º 11
0
 public void Dispose()
 {
     LightBuffer.Dispose();
     MatrixBuffer.Dispose();
     VertexBuffer.Dispose();
     MaterialBuffer.Dispose();
     VertShader.Dispose();
     PixShader.Dispose();
     Layout.Dispose();
     Sampler.Dispose();
 }
Ejemplo n.º 12
0
 public void Dispose()
 {
     if (Meshes != null)
     {
         foreach (ModelMesh m in Meshes)
         {
             m.Dispose();
         }
     }
     cbuffer?.Dispose();
 }
Ejemplo n.º 13
0
        public void Dispose()
        {
            mVertexShaderResult?.Dispose();
            mPixelShaderResult?.Dispose();

            mVertexShader?.Dispose();
            mPixelShader?.Dispose();

            mWVPConstantBuffer?.Dispose();
            mLightConstantBuffer?.Dispose();
        }
Ejemplo n.º 14
0
 public void Dispose()
 {
     if (views != null)
     {
         foreach (var uav in views)
         {
             uav.Value.Dispose();
         }
     }
     View?.Dispose();
     Handle?.Dispose();
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Update the values of this buffer
        /// </summary>
        /// <param name="value"></param>
        public void UpdateValue(T[] value)
        {
            if (value.Length == 0)
            {
                return;
            }

            // Create new buffer if elements were added or removed
            if (objectCount != value.Length)
            {
                objectCount = value.Length;

                buffer?.Dispose();
                buffer = new Buffer(device, new BufferDescription
                {
                    Usage               = ResourceUsage.Default,
                    BindFlags           = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                    SizeInBytes         = elementSize * objectCount,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.BufferStructured,
                    StructureByteStride = elementSize
                });

                shaderResource?.Dispose();
                shaderResource = new ShaderResourceView(device, buffer, new ShaderResourceViewDescription()
                {
                    Format    = Format.Unknown,
                    Dimension = ShaderResourceViewDimension.Buffer,
                    Buffer    = new ShaderResourceViewDescription.BufferResource()
                    {
                        ElementWidth = objectCount
                    }
                });

                deviceContext.VertexShader.SetShaderResource(slot, shaderResource);
                deviceContext.PixelShader.SetShaderResource(slot, shaderResource);
            }

            deviceContext.UpdateSubresource(value, buffer);
        }
Ejemplo n.º 16
0
 public void Dispose()
 {
     _renderForm?.Dispose();
     _swapChain?.Dispose();
     _device?.Dispose();
     _deviceContext?.Dispose();
     _renderTargetView?.Dispose();
     _triangleVertexBuffer?.Dispose();
     _vertexShader?.Dispose();
     _pixelShader?.Dispose();
     _inputSignature?.Dispose();
     _inputLayout?.Dispose();
 }
Ejemplo n.º 17
0
        public void Dispose()
        {
            Texture?.Dispose();
            Texture = null;

            _indexBuffer?.Dispose();
            _indexBuffer = null;

            _vertexBuffer?.Dispose();
            _vertexBuffer = null;

            ModelObject = null;
        }
        public override void Resize()
        {
            base.Resize();
            int NumTiles            = GetNumTilesX() * GetNumTilesY();
            int MaxNumLightsPerTile = GetMaxNumLightsPerTile();

            LightIndexBuffer?.Dispose();
            LightIndexBuffer = new Buffer(GetDevice, new BufferDescription()
            {
                Usage       = ResourceUsage.Default,
                SizeInBytes = 4 * MaxNumLightsPerTile * NumTiles,
                BindFlags   = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
            });

            LightIndexSRV?.Dispose();
            LightIndexSRV = new ShaderResourceView(GetDevice, LightIndexBuffer, new ShaderResourceViewDescription()
            {
                Format    = Format.R32_UInt,
                Dimension = ShaderResourceViewDimension.Buffer,
                Buffer    = new ShaderResourceViewDescription.BufferResource()
                {
                    ElementOffset = 0,
                    ElementWidth  = MaxNumLightsPerTile * NumTiles,
                },
            });

            LightIndexURV?.Dispose();
            LightIndexURV = new UnorderedAccessView(GetDevice, LightIndexBuffer, new UnorderedAccessViewDescription()
            {
                Format    = Format.R32_UInt,
                Dimension = UnorderedAccessViewDimension.Buffer,
                Buffer    = new UnorderedAccessViewDescription.BufferResource()
                {
                    FirstElement = 0,
                    ElementCount = MaxNumLightsPerTile * NumTiles,
                },
            });
        }
Ejemplo n.º 19
0
        public void Dispose()
        {
            _indexBuffer?.Dispose();
            _indexBuffer = null;

            _vertexBuffer?.Dispose();
            _vertexBuffer = null;

            HeightMap?.Clear();
            HeightMap = null;

            Texture?.Dispose();
            Texture = null;
        }
Ejemplo n.º 20
0
        private void ShutdownShader()
        {
            _matrixBuffer?.Dispose();
            _matrixBuffer = null;

            _layout?.Dispose();
            _layout = null;

            _pixelShader?.Dispose();
            _pixelShader = null;

            _vertexShader?.Dispose();
            _vertexShader = null;
            return;
        }
Ejemplo n.º 21
0
        public void Dispose()
        {
            _vertexLayout?.Dispose();
            _vertexShader?.Dispose();

            _pixelShader?.Dispose();
            _blendState?.Dispose();

            _dynamicConstantBuffer?.Dispose();
            if (!_vertexBufferExternal)
            {
                _vertexBuffer?.Dispose();
            }
            _dx.RemoveRef();
        }
 public override void Dispose()
 {
     PerObjConstantBuffer?.Dispose();
     PerFrameConstantBuffer?.Dispose();
     LightBuffer?.Dispose();
     textureTarget?.Dispose();
     velocityRenderTargetView?.Dispose();
     hdrTextureTarget?.Dispose();
     hdrRenderTargetView?.Dispose();
     hdrSRV?.Dispose();
     velocitySRV?.Dispose();
     downSamplingTarget?.Dispose();
     downSamplingTargetView?.Dispose();
     downSamplingSRV?.Dispose();
 }
Ejemplo n.º 23
0
 public void Clear()
 {
     buffers.ForEach(buf => {
         if (buf.Buffer != null)
         {
             buf.Buffer.Dispose();
         }
     });
     buffers.Clear();
     if (indexBuffer != null)
     {
         indexBuffer.Dispose();
     }
     VertexCount = 0;
     NumIndices  = 0;
     InputElements.Clear();
 }
Ejemplo n.º 24
0
 public void Dispose()
 {
     if (UAV != null)
     {
         UAV.Dispose();
         UAV = null;
     }
     if (SRV != null)
     {
         SRV.Dispose();
         SRV = null;
     }
     if (Buffer != null)
     {
         Buffer.Dispose();
         Buffer = null;
     }
 }
Ejemplo n.º 25
0
 public void Dispose()
 {
     if (VertexBuffer != null)
     {
         VertexBuffer.Dispose();
         VertexBuffer = null;
     }
     if (IndexBuffer != null)
     {
         IndexBuffer.Dispose();
         IndexBuffer = null;
     }
     if (InstanceDataBuffer != null)
     {
         InstanceDataBuffer.Dispose();
         InstanceDataBuffer = null;
     }
 }
Ejemplo n.º 26
0
 public void Shutdown()
 {
     signature.Dispose();
     vertexShader.Dispose();
     pixelShader.Dispose();
     vertexBuffer.Dispose();
     layout.Dispose();
     contantBuffer.Dispose();
     depthBuffer.Dispose();
     depthView.Dispose();
     renderView.Dispose();
     backBuffer.Dispose();
     context.ClearState();
     context.Flush();
     device.Dispose();
     context.Dispose();
     swapChain.Dispose();
     factory.Dispose();
 }
Ejemplo n.º 27
0
        public static void ResizeDisplay(Control control)
        {
            if (renderTarget == null)
            {
                return;
            }

            renderTarget.Dispose();
            depthStencil.Dispose();

            backBuffer.Dispose();

            backBufferCopy.Dispose();
            backBufferCopySRV.Dispose();

            Display.Width  = control.ClientSize.Width;
            Display.Height = control.ClientSize.Height;
            context.Rasterizer.SetViewports(new Viewport(0, 0, Display.Width, Display.Height, 0.0f, 1.0f));

            swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);

            backBuffer   = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0);
            renderTarget = new RenderTargetView(device, backBuffer);

            depthBufferDesc.Width  = Display.Width;
            depthBufferDesc.Height = Display.Height;

            using (var depthBuffer = new Texture2D(device, depthBufferDesc))
                depthStencil = new DepthStencilView(device, depthBuffer);

            context.OutputMerger.SetTargets(depthStencil, renderTarget);

            backBufferCopyDesc.Width  = Display.Width;
            backBufferCopyDesc.Height = Display.Height;

            backBufferCopy    = new Texture2D(Display.device, backBufferCopyDesc);
            backBufferCopySRV = new ShaderResourceView(Display.device, backBufferCopy);

            screenMatrix = Matrix.Scaling(2f / Display.Width, -2f / Display.Height, 0) * Matrix.Translation(-1, 1, 0);
            screenMatrix.Transpose();
            screenBuffer.Dispose();
            screenBuffer = new Buffer(device, DataStream.Create <Matrix>(new[] { screenMatrix }, false, false), 64, ResourceUsage.Immutable, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
        }
Ejemplo n.º 28
0
        /*-------------------------------------
         * NON-PUBLIC METHODS
         *-----------------------------------*/

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (IndexBuffer != null)
                {
                    IndexBuffer.Dispose();
                    IndexBuffer = null;
                }

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

                Graphics = null;
            }
        }
Ejemplo n.º 29
0
        protected override void OnClosing(CancelEventArgs e)
        {
            // Release all resources
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vertices.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();

            base.OnClosing(e);
        }
Ejemplo n.º 30
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (IndexBuffer != null)
                {
                    IndexBuffer.Dispose();
                }
                if (VertexBuffer != null)
                {
                    VertexBuffer.Dispose();
                }
            }
            _disposed = true;
        }
Ejemplo n.º 31
0
        private void InitializeOculus()
        {
            RenderForm form = new RenderForm("OculusWrap SharpDX demo");

			Wrap	oculus	= new Wrap();
			Hmd		hmd;

            form.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Window_KeyUp);

            //form.moused

            //form.Activate();
            //form.Show();

            int textureWidth = 0, textureHeight = 0;
            newTextureArrived = false;

            //zoom == 2 is not implemented, because the visual quality would be too low.
            //zoom == 4 will be implemented in the future.
            if (zoom == 3)
            {
                textureWidth = 3328;
                textureHeight = 1664;
            }

            bool success = oculus.Initialize();
            if (!success)
            {
                System.Windows.Forms.MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Use the head mounted display, if it's available, otherwise use the debug HMD.
            int numberOfHeadMountedDisplays = oculus.Hmd_Detect();
            if (numberOfHeadMountedDisplays > 0)
                hmd = oculus.Hmd_Create(0);
            else
                hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2);

            if (hmd == null)
            {
                System.Windows.Forms.MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (hmd.ProductName == string.Empty)
                System.Windows.Forms.MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error);

            // Specify which head tracking capabilities to enable.
            hmd.SetEnabledCaps(OVR.HmdCaps.LowPersistence | OVR.HmdCaps.DynamicPrediction);

            // Start the sensor which informs of the Rift's pose and motion
            hmd.ConfigureTracking(OVR.TrackingCaps.ovrTrackingCap_Orientation | OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OVR.TrackingCaps.ovrTrackingCap_Position, OVR.TrackingCaps.None);

            // Create a set of layers to submit.
            EyeTexture[] eyeTextures = new EyeTexture[2];
            OVR.ovrResult result;

            // Create DirectX drawing device.
            SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug);

            // Create DirectX Graphics Interface factory, used to create the swap chain.
            Factory factory = new Factory();

            DeviceContext immediateContext = device.ImmediateContext;

            // Define the properties of the swap chain.
            SwapChainDescription swapChainDescription = new SwapChainDescription();
            swapChainDescription.BufferCount = 1;
            swapChainDescription.IsWindowed = true;
            swapChainDescription.OutputHandle = form.Handle;
            swapChainDescription.SampleDescription = new SampleDescription(1, 0);
            swapChainDescription.Usage = Usage.RenderTargetOutput | Usage.ShaderInput;
            swapChainDescription.SwapEffect = SwapEffect.Sequential;
            swapChainDescription.Flags = SwapChainFlags.AllowModeSwitch;
            swapChainDescription.ModeDescription.Width = form.Width;
            swapChainDescription.ModeDescription.Height = form.Height;
            swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm;
            swapChainDescription.ModeDescription.RefreshRate.Numerator = 0;
            swapChainDescription.ModeDescription.RefreshRate.Denominator = 1;

            // Create the swap chain.
            SharpDX.DXGI.SwapChain swapChain = new SwapChain(factory, device, swapChainDescription);

            // Retrieve the back buffer of the swap chain.
            Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0);
            RenderTargetView backBufferRenderTargetView = new RenderTargetView(device, backBuffer);

            // Create a depth buffer, using the same width and height as the back buffer.
            Texture2DDescription depthBufferDescription = new Texture2DDescription();
            depthBufferDescription.Format = Format.D32_Float;
            depthBufferDescription.ArraySize = 1;
            depthBufferDescription.MipLevels = 1;
            depthBufferDescription.Width = form.Width;
            depthBufferDescription.Height = form.Height;
            depthBufferDescription.SampleDescription = new SampleDescription(1, 0);
            depthBufferDescription.Usage = ResourceUsage.Default;
            depthBufferDescription.BindFlags = BindFlags.DepthStencil;
            depthBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            depthBufferDescription.OptionFlags = ResourceOptionFlags.None;

            // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer.
            DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription();
            depthStencilStateDescription.IsDepthEnabled = true;
            depthStencilStateDescription.DepthComparison = Comparison.Less;
            depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;

            // Create the depth buffer.
            Texture2D depthBuffer = new Texture2D(device, depthBufferDescription);
            DepthStencilView depthStencilView = new DepthStencilView(device, depthBuffer);
            DepthStencilState depthStencilState = new DepthStencilState(device, depthStencilStateDescription);
            Viewport viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f);

            immediateContext.OutputMerger.SetDepthStencilState(depthStencilState);
            immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView);
            immediateContext.Rasterizer.SetViewport(viewport);

            // Retrieve the DXGI device, in order to set the maximum frame latency.
            using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>())
            {
                dxgiDevice.MaximumFrameLatency = 1;
            }

            Layers layers = new Layers();
            LayerEyeFov layerEyeFov = layers.AddLayerEyeFov();

            for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
            {
                OVR.EyeType eye = (OVR.EyeType)eyeIndex;
                EyeTexture eyeTexture = new EyeTexture();
                eyeTextures[eyeIndex] = eyeTexture;

                // Retrieve size and position of the texture for the current eye.
                eyeTexture.FieldOfView = hmd.DefaultEyeFov[eyeIndex];
                eyeTexture.TextureSize = hmd.GetFovTextureSize(eye, hmd.DefaultEyeFov[eyeIndex], 1.0f);
                eyeTexture.RenderDescription = hmd.GetRenderDesc(eye, hmd.DefaultEyeFov[eyeIndex]);
                eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyeViewOffset;
                eyeTexture.ViewportSize.Position = new OVR.Vector2i(0, 0);
                eyeTexture.ViewportSize.Size = eyeTexture.TextureSize;
                eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f);

                // Define a texture at the size recommended for the eye texture.
                eyeTexture.Texture2DDescription = new Texture2DDescription();
                eyeTexture.Texture2DDescription.Width = eyeTexture.TextureSize.Width;
                eyeTexture.Texture2DDescription.Height = eyeTexture.TextureSize.Height;
                eyeTexture.Texture2DDescription.ArraySize = 1;
                eyeTexture.Texture2DDescription.MipLevels = 1;
                eyeTexture.Texture2DDescription.Format = Format.R8G8B8A8_UNorm;
                eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0);
                eyeTexture.Texture2DDescription.Usage = ResourceUsage.Default;
                eyeTexture.Texture2DDescription.CpuAccessFlags = CpuAccessFlags.None;
                eyeTexture.Texture2DDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;

                // Convert the SharpDX texture description to the native Direct3D texture description.
                OVR.D3D11.D3D11_TEXTURE2D_DESC swapTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(eyeTexture.Texture2DDescription);

                // Create a SwapTextureSet, which will contain the textures to render to, for the current eye.
                result = hmd.CreateSwapTextureSetD3D11(device.NativePointer, ref swapTextureDescriptionD3D11, out eyeTexture.SwapTextureSet);
                WriteErrorDetails(oculus, result, "Failed to create swap texture set.");

                // Create room for each DirectX texture in the SwapTextureSet.
                eyeTexture.Textures = new Texture2D[eyeTexture.SwapTextureSet.TextureCount];
                eyeTexture.RenderTargetViews = new RenderTargetView[eyeTexture.SwapTextureSet.TextureCount];

                // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet.
                for (int textureIndex = 0; textureIndex < eyeTexture.SwapTextureSet.TextureCount; textureIndex++)
                {
                    // Retrieve the current textureData object.
                    OVR.D3D11.D3D11TextureData textureData = eyeTexture.SwapTextureSet.Textures[textureIndex];

                    // Create a managed Texture2D, based on the unmanaged texture pointer.
                    eyeTexture.Textures[textureIndex] = new Texture2D(textureData.Texture);

                    // Create a render target view for the current Texture2D.
                    eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]);
                }

                // Define the depth buffer, at the size recommended for the eye texture.
                eyeTexture.DepthBufferDescription = new Texture2DDescription();
                eyeTexture.DepthBufferDescription.Format = Format.D32_Float;
                eyeTexture.DepthBufferDescription.Width = eyeTexture.TextureSize.Width;
                eyeTexture.DepthBufferDescription.Height = eyeTexture.TextureSize.Height;
                eyeTexture.DepthBufferDescription.ArraySize = 1;
                eyeTexture.DepthBufferDescription.MipLevels = 1;
                eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0);
                eyeTexture.DepthBufferDescription.Usage = ResourceUsage.Default;
                eyeTexture.DepthBufferDescription.BindFlags = BindFlags.DepthStencil;
                eyeTexture.DepthBufferDescription.CpuAccessFlags = CpuAccessFlags.None;
                eyeTexture.DepthBufferDescription.OptionFlags = ResourceOptionFlags.None;

                // Create the depth buffer.
                eyeTexture.DepthBuffer = new Texture2D(device, eyeTexture.DepthBufferDescription);
                eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer);

                // Specify the texture to show on the HMD.
                layerEyeFov.ColorTexture[eyeIndex] = eyeTexture.SwapTextureSet.SwapTextureSetPtr;
                layerEyeFov.Viewport[eyeIndex].Position = new OVR.Vector2i(0, 0);
                layerEyeFov.Viewport[eyeIndex].Size = eyeTexture.TextureSize;
                layerEyeFov.Fov[eyeIndex] = eyeTexture.FieldOfView;
                layerEyeFov.Header.Flags = OVR.LayerFlags.TextureOriginAtBottomLeft;
            }

            // Define the texture used to display the rendered result on the computer monitor.
            Texture2DDescription mirrorTextureDescription = new Texture2DDescription();
            mirrorTextureDescription.Width = form.Width;
            mirrorTextureDescription.Height = form.Height;
            mirrorTextureDescription.ArraySize = 1;
            mirrorTextureDescription.MipLevels = 1;
            mirrorTextureDescription.Format = Format.R8G8B8A8_UNorm;
            mirrorTextureDescription.SampleDescription = new SampleDescription(1, 0);
            mirrorTextureDescription.Usage = ResourceUsage.Default;
            mirrorTextureDescription.CpuAccessFlags = CpuAccessFlags.None;
            mirrorTextureDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;

            SamplerStateDescription samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic
            };

            RasterizerStateDescription rasterizerStateDescription = RasterizerStateDescription.Default();
            rasterizerStateDescription.IsFrontCounterClockwise = true;

            // Convert the SharpDX texture description to the native Direct3D texture description.
            OVR.D3D11.D3D11_TEXTURE2D_DESC mirrorTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(mirrorTextureDescription);

            OculusWrap.D3D11.MirrorTexture mirrorTexture;

            // Create the texture used to display the rendered result on the computer monitor.
            result = hmd.CreateMirrorTextureD3D11(device.NativePointer, ref mirrorTextureDescriptionD3D11, out mirrorTexture);
            WriteErrorDetails(oculus, result, "Failed to create mirror texture.");

            Texture2D mirrorTextureD3D11 = new Texture2D(mirrorTexture.Texture.Texture);

            #region Vertex and pixel shader
            // Create vertex shader.
            ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderMain", "vs_4_0");
            VertexShader vertexShader = new VertexShader(device, vertexShaderByteCode);

            // Create pixel shader.
            ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderMain", "ps_4_0");
            PixelShader pixelShader = new PixelShader(device, pixelShaderByteCode);

            ShaderSignature shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);



            Texture2D myTexture = new Texture2D(device, new Texture2DDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                ArraySize = 1,
                MipLevels = 1,
                Width = textureWidth,
                Height = textureHeight,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
            });


            ShaderResourceView textureView = new ShaderResourceView(device, myTexture);


            //set sampler for texture
            SamplerState samplerState = new SamplerState(device, samplerStateDescription);

            //initialize rasterizer
            RasterizerState rasterizerState = new RasterizerState(device, rasterizerStateDescription);

            // Specify that each vertex consists of a single vertex position and color.

            int[] indices = null;
            Vertex[] vertices = null;
            CreateGeometry(out indices, out vertices);

            InputElement[] inputElements = new InputElement[]
            {
                new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),
                /*new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),*/
            };

            // Define an input layout to be passed to the vertex shader.
            InputLayout inputLayout = new InputLayout(device, shaderSignature, inputElements);

            // Create a vertex buffer, containing our 3D model.
            Buffer vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, vertices);//m_vertices);

            // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader.
            Buffer constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            Buffer indexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.IndexBuffer, indices);

            // Setup the immediate context to use the shaders and model we defined.
            immediateContext.InputAssembler.InputLayout = inputLayout;
            immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0));
            immediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

            immediateContext.VertexShader.SetConstantBuffer(0, constantBuffer);

            immediateContext.VertexShader.Set(vertexShader);
            immediateContext.PixelShader.Set(pixelShader);

            immediateContext.PixelShader.SetShaderResource(0, textureView);
            immediateContext.PixelShader.SetSampler(0, samplerState);
            #endregion

            DateTime startTime = DateTime.Now;
            Vector3 position = new Vector3(0, 0, 0);

            oculusReady = true;

            #region Render loop
            RenderLoop.Run(form, () =>
            {
                OVR.Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset };
                OVR.FrameTiming frameTiming = hmd.GetFrameTiming(0);
                OVR.TrackingState trackingState = hmd.GetTrackingState(frameTiming.DisplayMidpointSeconds);
                OVR.Posef[] eyePoses = new OVR.Posef[2];

                // Calculate the position and orientation of each eye.
                oculus.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses);

                float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds;

                for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
                {
                    OVR.EyeType eye = (OVR.EyeType)eyeIndex;
                    EyeTexture eyeTexture = eyeTextures[eyeIndex];

                    layerEyeFov.RenderPose[eyeIndex] = eyePoses[eyeIndex];

                    // Retrieve the index of the active texture and select the next texture as being active next.
                    int textureIndex = eyeTexture.SwapTextureSet.CurrentIndex++;

                    immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]);
                    immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black);
                    immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                    immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport);
                    //added a custom rasterizer
                    immediateContext.Rasterizer.State = rasterizerState;

                    // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction.
                    Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation);
                    Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion);
                    Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3();
                    Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3();

                    Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3();

                    //use this to get the first rotation to goal
                    Matrix world = Matrix.Scaling(1.0f) /** Matrix.RotationX(timeSinceStart*0.2f) */* Matrix.RotationY(timeSinceStart * 2 / 10f) /** Matrix.RotationZ(timeSinceStart*3/10f)*/;
                    Matrix viewMatrix = Matrix.LookAtRH(viewPosition, viewPosition + lookAt, lookUp);

                    Matrix projectionMatrix = OVR.ovrMatrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 10.0f, OVR.ProjectionModifier.None).ToMatrix();
                    projectionMatrix.Transpose();

                    Matrix worldViewProjection = world * viewMatrix * projectionMatrix;
                    worldViewProjection.Transpose();

                    // Update the transformation matrix.
                    immediateContext.UpdateSubresource(ref worldViewProjection, constantBuffer);

                    // Draw the cube
                    //immediateContext.Draw(vertices.Length/2, 0);
                    immediateContext.DrawIndexed(indices.Length, 0, 0);
                }

                hmd.SubmitFrame(0, layers);

                immediateContext.CopyResource(mirrorTextureD3D11, backBuffer);
                swapChain.Present(0, PresentFlags.None);


                if (newTextureArrived == true)
                {
                    newTextureArrived = false;
                    DataBox map = device.ImmediateContext.MapSubresource(myTexture, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);

                    //load the BitMapSource with appropriate formating (Format32bppPRGBA)
                    SharpDX.WIC.BitmapSource bitMap = LoadBitmap(new SharpDX.WIC.ImagingFactory(), streamTexture);
                    //string newFile = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\img_merged.jpg";
                    //SharpDX.WIC.BitmapSource bitMap = LoadBitmapFromFile(new SharpDX.WIC.ImagingFactory(), newFile);

                    int width = bitMap.Size.Width;
                    int height = bitMap.Size.Height;
                    int stride = bitMap.Size.Width * 4;

                    bitMap.CopyPixels(stride, map.DataPointer, height * stride);

                    device.ImmediateContext.UnmapSubresource(myTexture, 0);

                    //bitMap.Dispose();
                    streamTexture.Seek(0, SeekOrigin.Begin);
                }


            });
            #endregion
            // Release all resources
            inputLayout.Dispose();
            constantBuffer.Dispose();
            indexBuffer.Dispose();
            vertexBuffer.Dispose();
            inputLayout.Dispose();
            shaderSignature.Dispose();
            pixelShader.Dispose();
            pixelShaderByteCode.Dispose();
            vertexShader.Dispose();
            vertexShaderByteCode.Dispose();
            mirrorTextureD3D11.Dispose();
            layers.Dispose();
            eyeTextures[0].Dispose();
            eyeTextures[1].Dispose();
            immediateContext.ClearState();
            immediateContext.Flush();
            immediateContext.Dispose();
            depthStencilState.Dispose();
            depthStencilView.Dispose();
            depthBuffer.Dispose();
            backBufferRenderTargetView.Dispose();
            backBuffer.Dispose();
            swapChain.Dispose();
            factory.Dispose();

            // Disposing the device, before the hmd, will cause the hmd to fail when disposing.
            // Disposing the device, after the hmd, will cause the dispose of the device to fail.
            // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down.
            // device.Dispose();

            hmd.Dispose();
            oculus.Dispose();
        }
Ejemplo n.º 32
0
        private static void Main()
        {
            // Form: the window in which we will show our application
            var form = new RenderForm("COMP30019 - Week 8");

            // SwapChain description: set up our double buffer
            var desc = new SwapChainDescription()
            {
                // We need one spare buffer here; if we needed more,
                // we could set a larger value
                BufferCount = 1,
                // Various properties of how the OS/Graphics card
                // will handle the window
                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
            };

            // Used for debugging dispose object references
            Configuration.EnableObjectTracking = true;

            // Disable throws on shader compilation errors - hopefully
            // we won't have any of these! :)
            //Configuration.ThrowOnShaderCompileError = false;

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Compile Vertex and Pixel shaders, given in the accompanying
            // shader file
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("week8.fx", "VS", "vs_4_0");
            var vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("week8.fx", "PS", "ps_4_0");
            var pixelShader = new PixelShader(device, pixelShaderByteCode);

            var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
            // Layout from VertexShader input signature: this tells the
            // program how to interpret the shader source code
            // Note that we need to keep track of the byte offset for each
            // element (RGBA*32 bits= 4*4 bytes= 16 bytes)
            var layout = new InputLayout(device, signature, new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 32, 0)
                    });

            // Create a set of variables for our objects
            // 8 vertices for the cube:
            Vector4 front_bottom_left = new Vector4(-1.0f, -1.0f, -1.0f, 1.0f);
            Vector4 front_top_left = new Vector4(-1.0f, 1.0f, -1.0f, 1.0f);
            Vector4 front_top_right = new Vector4(1.0f, 1.0f, -1.0f, 1.0f);
            Vector4 front_bottom_right = new Vector4(1.0f, -1.0f, -1.0f, 1.0f);
            Vector4 back_bottom_left = new Vector4(-1.0f, -1.0f, 1.0f, 1.0f);
            Vector4 back_bottom_right = new Vector4(1.0f, -1.0f, 1.0f, 1.0f);
            Vector4 back_top_left = new Vector4(-1.0f, 1.0f, 1.0f, 1.0f);
            Vector4 back_top_right = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            // Colours:
            Vector4 red = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
            Vector4 green = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
            Vector4 blue = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);
            Vector4 yellow = new Vector4(1.0f, 1.0f, 0.0f, 1.0f);
            Vector4 magenta = new Vector4(1.0f, 0.0f, 1.0f, 1.0f);
            Vector4 cyan = new Vector4(0.0f, 1.0f, 1.0f, 1.0f);
            // Normals:
            // *** These need to be calculated for each polygon (face) ***
            Vector4 top_normal = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
            Vector4 bottom_normal = new Vector4(0.0f, -1.0f, 0.0f, 1.0f);
            Vector4 left_normal = new Vector4(-1.0f, 0.0f, 0.0f, 1.0f);
            Vector4 right_normal = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
            Vector4 front_normal = new Vector4(0.0f, 0.0f, -1.0f, 1.0f);
            Vector4 back_normal = new Vector4(0.0f, 0.0f, 1.0f, 1.0f);

            //Funky Normals
            float oort = 1 / (float)Math.Sqrt(3);
            Vector4 ftr_normal = new Vector4(new Vector3( 1, 1,-1) * oort, 1);
            Vector4 btr_normal = new Vector4(new Vector3(1, 1, 1) * oort, 1);
            Vector4 btl_normal = new Vector4(new Vector3(-1, 1, 1) * oort, 1);
            Vector4 ftl_normal = new Vector4(new Vector3(-1, 1, -1) * oort, 1);
            Vector4 fbr_normal = new Vector4(new Vector3(1, -1, -1) * oort, 1);
            Vector4 bbr_normal = new Vector4(new Vector3(1, -1, 1) * oort, 1);
            Vector4 bbl_normal = new Vector4(new Vector3(-1, -1, 1) * oort, 1);
            Vector4 fbl_normal = new Vector4(new Vector3(-1, -1, -1) * oort, 1);

            // Instantiate Vertex buffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {/*
                                      // Cube vertices:
                                      // Front face
                                      front_bottom_left, red, fbl_normal,
                                      front_top_left, red, ftl_normal,
                                      front_top_right, red, ftr_normal,
                                      front_bottom_left, red, fbl_normal,
                                      front_top_right, red, ftr_normal,
                                      front_bottom_right, red, fbr_normal,

                                      // Back face
                                      back_bottom_left, green, bbl_normal,
                                      back_top_right, green, btr_normal,
                                      back_top_left, green, btl_normal,
                                      back_bottom_left, green, bbl_normal,
                                      back_bottom_right, green, bbr_normal,
                                      back_top_right, green, btr_normal,

                                      // Top face
                                      front_top_left, blue, ftl_normal,
                                      back_top_left, blue, btl_normal,
                                      back_top_right, blue, btr_normal,
                                      front_top_left, blue, ftl_normal,
                                      back_top_right, blue, btr_normal,
                                      front_top_right, blue, ftr_normal,

                                      // Bottom face
                                      front_bottom_left, yellow, fbl_normal,
                                      back_bottom_right, yellow, bbr_normal,
                                      back_bottom_left, yellow, bbl_normal,
                                      front_bottom_left, yellow, fbl_normal,
                                      front_bottom_right, yellow, fbr_normal,
                                      back_bottom_right, yellow, bbr_normal,

                                      // Left face
                                      front_bottom_left, magenta, fbl_normal,
                                      back_bottom_left, magenta, bbl_normal,
                                      back_top_left, magenta, btl_normal,
                                      front_bottom_left, magenta, fbl_normal,
                                      back_top_left, magenta, btl_normal,
                                      front_top_left, magenta, ftl_normal,

                                      // Right face
                                      front_bottom_right, cyan, fbr_normal,
                                      back_top_right, cyan, btr_normal,
                                      back_bottom_right, cyan, bbr_normal,
                                      front_bottom_right, cyan, fbr_normal,
                                      front_top_right, cyan, ftr_normal,
                                      back_top_right, cyan, btr_normal,
                                      */

                                      // Cube vertices:
                                      // Front face
                                      front_bottom_left, red, front_normal,
                                      front_top_left, red, front_normal,
                                      front_top_right, red, front_normal,
                                      front_bottom_left, red, front_normal,
                                      front_top_right, red, front_normal,
                                      front_bottom_right, red, front_normal,

                                      // Back face
                                      back_bottom_left, green, back_normal,
                                      back_top_right, green, back_normal,
                                      back_top_left, green, back_normal,
                                      back_bottom_left, green, back_normal,
                                      back_bottom_right, green, back_normal,
                                      back_top_right, green, back_normal,

                                      // Top face
                                      front_top_left, blue, top_normal,
                                      back_top_left, blue, top_normal,
                                      back_top_right, blue, top_normal,
                                      front_top_left, blue, top_normal,
                                      back_top_right, blue, top_normal,
                                      front_top_right, blue, top_normal,

                                      // Bottom face
                                      front_bottom_left, yellow, bottom_normal,
                                      back_bottom_right, yellow, bottom_normal,
                                      back_bottom_left, yellow, bottom_normal,
                                      front_bottom_left, yellow, bottom_normal,
                                      front_bottom_right, yellow, bottom_normal,
                                      back_bottom_right, yellow, bottom_normal,

                                      // Left face
                                      front_bottom_left, magenta, left_normal,
                                      back_bottom_left, magenta, left_normal,
                                      back_top_left, magenta, left_normal,
                                      front_bottom_left, magenta, left_normal,
                                      back_top_left, magenta, left_normal,
                                      front_top_left, magenta, left_normal,

                                      // Right face
                                      front_bottom_right, cyan, right_normal,
                                      back_top_right, cyan, right_normal,
                                      back_bottom_right, cyan, right_normal,
                                      front_bottom_right, cyan, right_normal,
                                      front_top_right, cyan, right_normal,
                                      back_top_right, cyan, right_normal,

                            });

            // Create Constant Buffer: this is how we pass the relevant constant variables
            // (the projection matrix, light sources, etc.) to the shader
            var constantBuffer = new Buffer(device, Utilities.SizeOf<S_SHADER_GLOBALS>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // Prepare all the stages:
            // Give the graphics card the shader structure
            context.InputAssembler.InputLayout = layout;
            // State how to interpret the vertices (in this case, as a
            // list of triangles
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            // Set up the relevant buffer to process the vertices
            // (primitives, fragments ...) using the shaders
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 3, 0));
            context.VertexShader.SetConstantBuffer(0, constantBuffer);
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // Prepare matrices:
            // Here we have our "eye" - it has a position, the direction
            // that we're "looking" towards, and which direction is "up"
            // Note that LookAtLH wants a 3D vector, but our shader is going to want
            // a 4D vector (in homogeneous coordinates)
            Vector3 eyePos3 = new Vector3(200.0f, 100.0f, -5.0f);
            Vector4 eyePos4 = new Vector4(eyePos3, 1.0f);
            var view = Matrix.LookAtLH(eyePos3, new Vector3(200, 100, 0), Vector3.UnitY);
            // We'll just use the identity matrix as our projection matrix
            // for now - this would give us orthonormal projection, but
            // we'll recalculate it later
            Matrix proj = Matrix.Identity;

            // Use the clock
            var clock = new Stopwatch();
            clock.Start();

            // Declare texture for rendering (even though we aren't
            // using texture here :) ); we also set up our swap chain back buffer
            bool userResized = true;
            Texture2D backBuffer = null;
            RenderTargetView renderView = null;
            Texture2D depthBuffer = null;
            DepthStencilView depthView = null;

            // Set up the light, a grey ambient light and a white positional light
            // The positional light is currently located above and behind the cube
            // (because it's + in Y and + in Z)
            Vector4 lightAmbCol = new Vector4(0.0f, 0.0f, 0.0f, 1.0f);
            Vector4 lightPntCol = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            Vector4 lightPntPos = new Vector4(200.0f, 100.0f, -10.0f, 1.0f);

            // Handle events where we resize our window
            form.UserResized += (sender, args) => userResized = true;

            // Main loop: render the objects for each frame of our scene
            RenderLoop.Run(form, () =>
            {
                // If the window was resized, we need to reorganise
                // various properties of the window (don't worry about
                // this right now)
                if (userResized)
                {
                    // Dispose all previous allocated resources
                    ComObject.Dispose(ref backBuffer);
                    ComObject.Dispose(ref renderView);
                    ComObject.Dispose(ref depthBuffer);
                    ComObject.Dispose(ref depthView);

                    // Resize the backbuffer
                    swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

                    // Get the backbuffer from the swapchain
                    backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);

                    // Renderview on the backbuffer
                    renderView = new RenderTargetView(device, backBuffer);

                    // Create the depth buffer
                    depthBuffer = new Texture2D(device, new Texture2DDescription()
                    {
                        Format = Format.D32_Float_S8X24_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = form.ClientSize.Width,
                        Height = form.ClientSize.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage = ResourceUsage.Default,
                        BindFlags = BindFlags.DepthStencil,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None
                    });

                    // Create the depth buffer view
                    depthView = new DepthStencilView(device, depthBuffer);

                    // Setup targets and viewport for rendering
                    context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
                    context.OutputMerger.SetTargets(depthView, renderView);

                    // Setup new projection matrix with correct aspect ratio
                    proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);

                    // We are done resizing
                    userResized = false;
                }

                // Keep track of how much time has passed
                var time = clock.ElapsedMilliseconds / 1000.0f;

                // Combine the eye with the projection matrix so that we
                // can correctly transform co-ordinates into the frustum
                var viewProj = Matrix.Multiply(view, proj);

                // Clear views
                context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                context.ClearRenderTargetView(renderView, new Color4(0.0f,0.0f,0.0f,1.0f));

                // Update WorldViewProj Matrix, to account for the scene
                // transformations according to the clock
                var world =
                    Matrix.RotationX(time * 0.2f) *
                    Matrix.RotationY(time * 0.5f) *
                    Matrix.RotationZ(time * 0.7f) *
                    Matrix.Translation(200, 100, 0);
                //var worldViewProj = Matrix.Identity;
                //worldViewProj *= viewProj;

                // Do some tricky matrix algebra so that we handle our
                // left-handed system properly
                world.Transpose();
                viewProj.Transpose();

                // Update our device handler with our struct containing all of the
                // constant variables for the shader
                // There are a couple of efficiency concerns here:
                // 1) We're creating a new variable every iteration through the render loop, and more importantly:
                // 2) We're updating all of the globals for every iteration through the render loop
                // Number (2) can mean that we're wasting a lot of effort re-writing variables to the graphics
                // card that haven't changed between iterations.
                S_SHADER_GLOBALS shaderGlobals = new S_SHADER_GLOBALS(eyePos4, lightAmbCol, lightPntPos, lightPntCol, world, viewProj);
                context.UpdateSubresource(ref shaderGlobals, constantBuffer);

                // Draw the cube
                context.Draw(36, 0);

                // Present! (Swap the buffers)
                swapChain.Present(0, PresentFlags.None);
            });
            // The main loop ends here - this means the window has been
            // closed, so the program can end

            // Release all resources
            signature.Dispose();
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vertices.Dispose();
            layout.Dispose();
            constantBuffer.Dispose();
            depthBuffer.Dispose();
            depthView.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
        }
Ejemplo n.º 33
0
        public void Run()
        {
            var form = new RenderForm("2d and 3d combined...it's like magic");
            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); };

            // DirectX DXGI 1.1 factory
            var factory1 = new Factory1();

            // The 1st graphics adapter
            var adapter1 = factory1.GetAdapter1(0);

            // ---------------------------------------------------------------------------------------------
            // Setup direct 3d version 11. It's context will be used to combine the two elements
            // ---------------------------------------------------------------------------------------------

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

            Device11 device11;
            SwapChain swapChain;

            Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain);

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

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

            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);
            context.OutputMerger.SetTargets(renderTargetView);
            context.Rasterizer.SetViewports(viewport);

            //
            // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device.
            //
            // The DirectX10 device will be used to render text onto this texture.
            // DirectX11 will then draw this texture (blended) onto the screen.
            // The KeyedMutex flag is required in order to share this resource between the two devices.
            var textureD3D11 = new Texture2D(device11, new Texture2DDescription
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            });

            // ---------------------------------------------------------------------------------------------
            // Setup a direct 3d version 10.1 adapter
            // ---------------------------------------------------------------------------------------------
            var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0);

            // ---------------------------------------------------------------------------------------------
            // Setup Direct 2d
            // ---------------------------------------------------------------------------------------------

            // Direct2D Factory
            var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information);

            // Here we bind the texture we've created on our direct3d11 device through the direct3d10
            // to the direct 2d render target....
            var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>();
            var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle);

            var surface = textureD3D10.AsSurface();
            var rtp = new RenderTargetProperties
                {
                    MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10,
                    Type = RenderTargetType.Hardware,
                    PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
                };

            var renderTarget2D = new RenderTarget(factory2D, surface, rtp);
            var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red);

            // ---------------------------------------------------------------------------------------------------
            // Setup the rendering data
            // ---------------------------------------------------------------------------------------------------

            // Load Effect. This includes both the vertex and pixel shaders.
            // Also can include more than one technique.
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(
                "effectDx11.fx",
                "fx_5_0",
                ShaderFlags.EnableStrictness);

            var effect = new Effect(device11, shaderByteCode);

            // create triangle vertex data, making sure to rewind the stream afterward
            var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true);
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f)));
            verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f)));

            verticesTriangle.Position = 0;

            // create the triangle vertex layout and buffer
            var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements);
            var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesTriangle.Close();

            // create overlay vertex data, making sure to rewind the stream afterward
            // Top Left of screen is -1, +1
            // Bottom Right of screen is +1, -1
            var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true);
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0)));
            verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1)));
            verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1)));

            verticesText.Position = 0;

            // create the overlay vertex layout and buffer
            var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements);
            var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            verticesText.Close();

            // Think of the shared textureD3D10 as an overlay.
            // The overlay needs to show the 2d content but let the underlying triangle (or whatever)
            // show thru, which is accomplished by blending.
            var bsd = new BlendStateDescription();
            bsd.RenderTarget[0].IsBlendEnabled = true;
            bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor;
            bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor;
            bsd.RenderTarget[0].BlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

            var blendStateTransparent = new BlendState(device11, bsd);

            // ---------------------------------------------------------------------------------------------------
            // Create and tesselate an ellipse
            // ---------------------------------------------------------------------------------------------------
            var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f);
            var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f));

            // Populate a PathGeometry from Ellipse tessellation
            var tesselatedGeometry = new PathGeometry(factory2D);
            _geometrySink = tesselatedGeometry.Open();

            // Force RoundLineJoin otherwise the tesselated looks buggy at line joins
            _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin);

            // Tesselate the ellipse to our TessellationSink
            ellipse.Tessellate(1, this);

            _geometrySink.Close();

            // ---------------------------------------------------------------------------------------------------
            // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface
            // ---------------------------------------------------------------------------------------------------

            var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>();
            var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>();

            // ---------------------------------------------------------------------------------------------------
            // Main rendering loop
            // ---------------------------------------------------------------------------------------------------

            bool first = true;

            RenderLoop
                .Run(form,
                     () =>
                         {
                             if(first)
                             {
                                 form.Activate();
                                 first = false;
                             }

                             // clear the render target to black
                             context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray);

                             // Draw the triangle
                             context.InputAssembler.InputLayout = layoutColor;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0));
                             context.OutputMerger.BlendState = null;
                             var currentTechnique = effect.GetTechniqueByName("Color");
                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(3, 0);
                             };

                             // Draw Ellipse on the shared Texture2D
                             device10Mutex.Acquire(0, 100);
                             renderTarget2D.BeginDraw();
                             renderTarget2D.Clear(Colors.Black);
                             renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush);
                             renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null);
                             renderTarget2D.EndDraw();
                             device10Mutex.Release(0);

                             // Draw the shared texture2D onto the screen, blending the 2d content in
                             device11Mutex.Acquire(0, 100);
                             var srv = new ShaderResourceView(device11, textureD3D11);
                             effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv);
                             context.InputAssembler.InputLayout = layoutOverlay;
                             context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
                             context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0));
                             context.OutputMerger.BlendState = blendStateTransparent;
                             currentTechnique = effect.GetTechniqueByName("Overlay");

                             for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
                             {
                                 using (var effectPass = currentTechnique.GetPassByIndex(pass))
                                 {
                                     System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
                                     effectPass.Apply(context);
                                 }
                                 context.Draw(4, 0);
                             }
                             srv.Dispose();
                             device11Mutex.Release(0);

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

            // dispose everything
            vertexBufferColor.Dispose();
            vertexBufferOverlay.Dispose();
            layoutColor.Dispose();
            layoutOverlay.Dispose();
            effect.Dispose();
            shaderByteCode.Dispose();
            renderTarget2D.Dispose();
            swapChain.Dispose();
            device11.Dispose();
            device10.Dispose();
            textureD3D10.Dispose();
            textureD3D11.Dispose();
            factory1.Dispose();
            adapter1.Dispose();
            sharedResource.Dispose();
            factory2D.Dispose();
            surface.Dispose();
            solidColorBrush.Dispose();
            blendStateTransparent.Dispose();

            device10Mutex.Dispose();
            device11Mutex.Dispose();
        }
Ejemplo n.º 34
0
  //      [STAThread]
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample");

            // SwapChain description
            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
            };

            // Used for debugging dispose object references
            // Configuration.EnableObjectTracking = true;

            // Disable throws on shader compilation errors
            //Configuration.ThrowOnShaderCompileError = false;

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0");
            var vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0");
            var pixelShader = new PixelShader(device, pixelShaderByteCode);

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

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top
                                      new Vector4(-1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                            });

            // Create Constant Buffer
            var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);



            // Prepare All the stages
            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0));
            context.VertexShader.SetConstantBuffer(0, contantBuffer);
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // Prepare matrices
            var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            Matrix proj = Matrix.Identity;

            // Use clock
            var clock = new Stopwatch();
            clock.Start();

            // Declare texture for rendering
            bool userResized = true;
            Texture2D backBuffer = null;
            RenderTargetView renderView = null;
            Texture2D depthBuffer = null;
            DepthStencilView depthView = null;

            // Setup handler on resize form
            form.UserResized += (sender, args) => userResized = true;

            // Setup full screen mode change F5 (Full) F4 (Window)
            form.KeyUp += (sender, args) =>
                {
                    if (args.KeyCode == Keys.F5)
                        swapChain.SetFullscreenState(true, null);
                    else if (args.KeyCode == Keys.F4)
                        swapChain.SetFullscreenState(false, null);
                    else if (args.KeyCode == Keys.Escape)
                        form.Close();
                };

            // Main loop
            RenderLoop.Run(form, () =>
            {
                // If Form resized
                if (userResized)
                {
                    // Dispose all previous allocated resources
                    ComObject.Dispose(ref backBuffer);
                    ComObject.Dispose(ref renderView);
                    ComObject.Dispose(ref depthBuffer);
                    ComObject.Dispose(ref depthView);

                    // Resize the backbuffer
                    swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

                    // Get the backbuffer from the swapchain
                    backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);

                    // Renderview on the backbuffer
                    renderView = new RenderTargetView(device, backBuffer);

                    // Create the depth buffer
                    depthBuffer = new Texture2D(device, new Texture2DDescription()
                    {
                        Format = Format.D32_Float_S8X24_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = form.ClientSize.Width,
                        Height = form.ClientSize.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage = ResourceUsage.Default,
                        BindFlags = BindFlags.DepthStencil,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.None
                    });

                    // Create the depth buffer view
                    depthView = new DepthStencilView(device, depthBuffer);

                    // Setup targets and viewport for rendering
                    context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
                    context.OutputMerger.SetTargets(depthView, renderView);

                    // Setup new projection matrix with correct aspect ratio
                    proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);

                    // We are done resizing
                    userResized = false;
                }

                var time = clock.ElapsedMilliseconds / 1000.0f;

                var viewProj = Matrix.Multiply(view, proj);

                // Clear views
                context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                context.ClearRenderTargetView(renderView, Color.Black);

                // Update WorldViewProj Matrix
                var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj;
                worldViewProj.Transpose();
                context.UpdateSubresource(ref worldViewProj, contantBuffer);

                // Draw the cube
                context.Draw(36, 0);

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

            // Release all resources
            signature.Dispose();
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vertices.Dispose();
            layout.Dispose();
            contantBuffer.Dispose();
            depthBuffer.Dispose();
            depthView.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }