Ejemplo n.º 1
0
        unsafe void UpdateMatrixBuffer()
        {
            var mb = new MatrixBuffer()
            {
                View = viewMatrix, World = worldMatrix, Text = textMatrix
            };

            deviceContext.UpdateSubresource(matrixBuffer, 0, null, (IntPtr)(&mb), 1, 0);
            deviceContext.VertexShader.SetConstantBuffer(0, matrixBuffer);
        }
Ejemplo n.º 2
0
        private void FillBuffers()
        {
            float speed = _waveSpeed;
            float dx    = _wavesCB._spatialStep;
            float dt    = _waveTimeStep;

            uint m = _wavesCB.RowCount;
            uint n = _wavesCB.ColumnCount;

            var d = _waveDamping * dt + 2.0f;
            var e = (speed * speed) * (dt * dt) / (dx * dx);

            var w2 = (n - 1) * dx * 0.5f;
            var d2 = (m - 1) * dx * 0.5f;



            var WaveSolutions = new WaveSolution[m * n];

            for (var i = 0; i < m; i++)
            {
                var z = d2 - i * dx;
                for (var j = 0; j < n; j++)
                {
                    var x = -w2 + j * dx;
                    WaveSolutions[i * n + j]         = new WaveSolution();
                    WaveSolutions[i * n + j].Pos     = new Vector4(x, 0, z, 0);
                    WaveSolutions[i * n + j].Normal  = new Vector4(0, 1, 0, 1);
                    WaveSolutions[i * n + j].Tangent = new Vector4(1.0f, 0, 0, 1);
                }
            }

            ImmediateContext.UpdateSubresource <WaveSolution>(WaveSolutions, _inputBuf1);

            WaveSolutions = new WaveSolution[m * n];

            for (var i = 0; i < m; i++)
            {
                var z = d2 - i * dx;
                for (var j = 0; j < n; j++)
                {
                    var x = -w2 + j * dx;
                    WaveSolutions[i * n + j]         = new WaveSolution();
                    WaveSolutions[i * n + j].Pos     = new Vector4(x, 0, z, 0);
                    WaveSolutions[i * n + j].Normal  = new Vector4(0, 1, 0, 1);
                    WaveSolutions[i * n + j].Tangent = new Vector4(1.0f, 0, 0, 1);
                }
            }
            ImmediateContext.UpdateSubresource <WaveSolution>(WaveSolutions, _inputBuf2);
        }
Ejemplo n.º 3
0
        // TODO henning make this more generic to setup own description
        //[HandleProcessCorruptedStateExceptions]
        public static Texture2D CreateTex2DFromFile(Device device, DeviceContext deviceContext, string filename)
        {
            try
            {
                using (Surface image = Surface.LoadFromFile(filename, true))
                {
                    image.ConvertTo(ImageConversion.To32Bits);
                    Texture2DDescription desc;
                    desc.Width                     = image.Width;
                    desc.Height                    = image.Height;
                    desc.ArraySize                 = 1;
                    desc.BindFlags                 = BindFlags.ShaderResource | BindFlags.RenderTarget;
                    desc.Usage                     = ResourceUsage.Default;
                    desc.CpuAccessFlags            = CpuAccessFlags.None;
                    desc.Format                    = Format.B8G8R8A8_UNorm;
                    desc.MipLevels                 = 0;
                    desc.OptionFlags               = ResourceOptionFlags.GenerateMipMaps;
                    desc.SampleDescription.Count   = 1;
                    desc.SampleDescription.Quality = 0;

                    var t2D = new Texture2D(device, desc);
                    deviceContext.UpdateSubresource(new DataBox(image.DataPtr, image.Pitch, 0), t2D);
                    return(t2D);
                }
            }
            catch
            {
                using (Surface image = Surface.LoadFromFile("Resources/Textures/MissingTexture.tga", true))
                {
                    Texture2DDescription desc;
                    desc.Width                     = image.Width;
                    desc.Height                    = image.Height;
                    desc.ArraySize                 = 1;
                    desc.BindFlags                 = BindFlags.ShaderResource | BindFlags.RenderTarget;
                    desc.Usage                     = ResourceUsage.Default;
                    desc.CpuAccessFlags            = CpuAccessFlags.None;
                    desc.Format                    = Format.B8G8R8A8_UNorm;
                    desc.MipLevels                 = 0;
                    desc.OptionFlags               = ResourceOptionFlags.GenerateMipMaps;
                    desc.SampleDescription.Count   = 1;
                    desc.SampleDescription.Quality = 0;

                    // Create our texture without data and only update the data later with the first mip level so we can auto generate them
                    var t2D = new Texture2D(device, desc);
                    deviceContext.UpdateSubresource(new DataBox(image.DataPtr, image.Pitch, 0), t2D);
                    return(t2D);
                }
            }
        }
Ejemplo n.º 4
0
        private void Draw()
        {
            d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 32, 64));
            d3dDeviceContext.ClearDepthStencilView(depthStencilView, D3D11.DepthStencilClearFlags.Depth | D3D11.DepthStencilClearFlags.Stencil, 1.0f, 0);

            // Camera
            var view = Matrix.LookAtLH(freeCamPos, freeCamPos + freeCamLookDir, new Vector3(0, 1, 0));
            var proj = Matrix.PerspectiveFovLH(45.0f * TORAD, (float)width / height, 0.1f, 100.0f);

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

            var binding = new D3D11.VertexBufferBinding(cubeBuffer, Utilities.SizeOf <Vertex>(), 0);

            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, binding);

            VertexShaderConstants c;

            for (int i = 0; i < renderObjects.Count; i++)
            {
                var o = renderObjects[i];
                c.modelViewProj = o.transform * viewProj;
                c.modelViewProj.Transpose();
                c.color = o.color.ToVector4();

                d3dDeviceContext.UpdateSubresource(ref c, constantBuffer);
                d3dDeviceContext.Draw(cubeVertices.Count(), 0);
            }

            swapChain.Present(1, PresentFlags.None);
        }
Ejemplo n.º 5
0
        private void UpdateConstantBuffer(ConstantBuffer data)
        {
            deviceContext.UpdateSubresource(ref data, constantBuffer);

            deviceContext.VertexShader.SetConstantBuffer(0, constantBuffer);
            deviceContext.PixelShader.SetConstantBuffer(0, constantBuffer);
        }
Ejemplo n.º 6
0
        private void Render(D3D11.Device device, D3D11.RenderTargetView[] rtvs)
        {
            D3D11.DeviceContext deviceContext = device.ImmediateContext;


            for (int i = 0; i < 6; ++i)
            {
                deviceContext.OutputMerger.SetRenderTargets(rtvs[i]);
                deviceContext.ClearRenderTargetView(rtvs[i], Color.Red);

                //if (i == 5)
                //    continue;
                KDX_SKYBOX_ENV_RENDERER_BUFFER buffer = new KDX_SKYBOX_ENV_RENDERER_BUFFER();
                buffer.World = Matrix.Transpose(Matrix.Identity);
                buffer.View  = Matrix.Transpose(views[i]);
                buffer.Proj  = Matrix.Transpose(Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(90), 1, 0.01f, 100.0f));
                buffer.MVP   = (buffer.Proj * buffer.View * buffer.World);

                deviceContext.UpdateSubresource(ref buffer, perFaceBuffer);

                deviceContext.DrawIndexed(cubeMesh.Triangles.Count() * 3, 0, 0);

                rtvs[i].Dispose();
            }
        }
Ejemplo n.º 7
0
        public void Draw(Matrix worldViewProjMatrix, D3D11.Texture2D texture)
        {
            // Set the shaders to use for the draw operation
            d3dDeviceContext.VertexShader.Set(vertexShader);
            d3dDeviceContext.PixelShader.Set(pixelShader);

            // Set the primitive topology to triangle list
            d3dDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;

            // Set the input layout of the vertices
            d3dDeviceContext.InputAssembler.InputLayout = inputLayout;

            // Bind the texture resource to the pixel shader
            var textureView = new D3D11.ShaderResourceView(d3dDevice, texture);

            d3dDeviceContext.PixelShader.SetShaderResource(0, textureView);
            d3dDeviceContext.PixelShader.SetSampler(0, samplerState);
            textureView.Dispose();

            // Pass the world view projection matrix to the vertex shader
            d3dDeviceContext.VertexShader.SetConstantBuffer(0, worldViewProjBuffer);
            d3dDeviceContext.UpdateSubresource(ref worldViewProjMatrix, worldViewProjBuffer);

            // Draw the rectangle
            d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <VertexXYUV>(), 0));
            d3dDeviceContext.Draw(numVertices, 0);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// displays all drawn content
        /// </summary>
        public void Display()
        {
            VertexArray = TriangleList.ToArray();

            deviceContext.UpdateSubresource(VertexArray, vertexBuffer);
            invCamara = camara.GetInvertedCamaraPosition();
            deviceContext.UpdateSubresource(ref invCamara, camaraBuffer);

            if (VertexArray.Length != lastVertexArrayLength)
            {
                vertexBuffer.Dispose();
                vertexBuffer = D3D11.Buffer.Create <Vertex>(device, D3D11.BindFlags.VertexBuffer, VertexArray);
                deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0));
            }

            deviceContext.Draw(VertexArray.Count(), 0);

            swapChain.Present(1, PresentFlags.None);
        }
Ejemplo n.º 9
0
        private void UpdateConstantBuffer(float time)
        {
            ConstantBuffer data = new ConstantBuffer();

            data.parameters   = new Vector4(0, 0.5f, 0.5f, 0.5f); // Tip: set yzw to something (focus plane for dof, perhaps radius and strength for ssao, etc.)
            data.parameters.X = time;

            deviceContext.UpdateSubresource(ref data, constantBuffer);

            deviceContext.VertexShader.SetConstantBuffer(0, constantBuffer);
            deviceContext.PixelShader.SetConstantBuffer(0, constantBuffer);
        }
Ejemplo n.º 10
0
        public void RenderNextAnimationFrame()
        {
            var eye = new Vector3(0.0f, 0.7f, 1.5f);  // Define camera position.
            var at  = new Vector3(0.0f, -0.1f, 0.0f); // Define focus position.
            var up  = new Vector3(0.0f, 1.0f, 0.0f);  // Define up direction.

            if (frameCount >= float.MaxValue)
            {
                frameCount = 0;
            }

            // Set view based on camera position, focal point, and up direction.
            constantBufferData.view = Matrix.Transpose(Matrix.LookAtRH(eye, at, up));

            // Rotate around Y axis by (pi/4) * 16ms per elapsed frame.
            constantBufferData.model = Matrix.Transpose(Matrix.RotationY(frameCount++ *0.016f * MathUtil.PiOverFour));

            // Clear depth/stencil view.
            d3dContext.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);

            // Set render target.
            d3dContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);

            // Map update to constant buffer.
            d3dContext.UpdateSubresource(ref constantBufferData, constantBuffer);

            // Set vertex buffer.
            int stride = Utilities.SizeOf <VertexPositionColor>();

            d3dContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, stride, 0));

            // Set index buffer.
            d3dContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0);

            // Set topology to triangle list.
            d3dContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Set input layout.
            d3dContext.InputAssembler.InputLayout = inputLayout;

            // Set vertex shader.
            d3dContext.VertexShader.Set(vertexShader);

            // Set constant buffer.
            d3dContext.VertexShader.SetConstantBuffer(0, constantBuffer);

            // Set pixel shader.
            d3dContext.PixelShader.Set(pixelShader);

            // Draw cube faces.
            d3dContext.DrawIndexed(indexCount, 0, 0);
        }
Ejemplo n.º 11
0
        public static void Render(SharpDX.Direct3D11.DeviceContext context)
        {
            //we apply wvp here to update z
            var origin    = (Origin * WVP).TranslationVector;
            var direction = (Direction * WVP).TranslationVector;
            var ray       = new SharpDX.Ray(origin, direction);


            //if ray is inside panel, show
            if (AdjustmentPanelModel.CheckBounds(ref ray, out var z))
            {
                var k = Direction.TranslationVector.Length();
                vertices[5] = -z * k;
                shader.Apply(context);
                context.UpdateSubresource(vertices, vertexBuffer);
                context.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList;
                context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
                context.Draw(2, 0);
            }
        }
Ejemplo n.º 12
0
        protected override void Draw(DemoTime time)
        {
            var now = DateTime.Now;

            // Don't over-render, it costs CPU and that's energy
            var delta = (int)(now - lastFrame).TotalMilliseconds;

            if (delta < msPerFrame)
            {
                System.Threading.Thread.Sleep(msPerFrame - delta);
            }
            lastFrame = now;

            base.Draw(time);

            // Update WorldViewProj Matrix
            var viewProj      = Matrix.Multiply(view, proj);
            var worldViewProj = Matrix.Translation(new Vector3(0, (float)(instruments.pitch * 0.5 / Math.PI), 0)) * Matrix.RotationZ(instruments.roll) * viewProj;

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

//            var attitude = adhrs.RawRead();
            if (attitude.Count() > 0)
            {
                lastRead = now;
                instruments.SetFromAhrs(attitude);
            }

            if ((now - lastRead).TotalSeconds > 1.2)
            {
                RenderTarget2D.DrawLine(new Vector2(0, 0), new Vector2(Stock.ClientRectangle.Width, Stock.ClientRectangle.Height), errorBrush, 3.0f);
                RenderTarget2D.DrawLine(new Vector2(Stock.ClientRectangle.Width, 0), new Vector2(0, Stock.ClientRectangle.Height), errorBrush, 3.0f);
            }

            context.Draw(36, 0);

            instruments.Draw(RenderTarget2D, instrumentColorBrush);
        }
Ejemplo n.º 13
0
        private void ProcessFrame(Direct3D11CaptureFrame frame)
        {
            // Do proecssing
            using (frame)
            {
                using (var texture = Direct3D11Helper.CreateSharpDXTexture2D(frame.Surface))
                {
                    var hdrMetadata = currentSession.HdrMetadata;
                    var vertices    = new ShaderInputStructure[]
                    {
                        // Left-Top
                        new ShaderInputStructure {
                            Position     = new Vector3(currentSession.DestD3DVsTopLeft.X, currentSession.DestD3DVsTopLeft.Y, 0),
                            TextureCoord = new Vector2(currentSession.DestD3DPsSamplerTopLeft.X, currentSession.DestD3DPsSamplerTopLeft.Y),
                        },
                        // Right-Top
                        new ShaderInputStructure {
                            Position     = new Vector3(currentSession.DestD3DVsBottomRight.X, currentSession.DestD3DVsTopLeft.Y, 0),
                            TextureCoord = new Vector2(currentSession.DestD3DPsSamplerBottomRight.X, currentSession.DestD3DPsSamplerTopLeft.Y)
                        },
                        // Left-Bottom
                        new ShaderInputStructure {
                            Position     = new Vector3(currentSession.DestD3DVsTopLeft.X, currentSession.DestD3DVsBottomRight.Y, 0),
                            TextureCoord = new Vector2(currentSession.DestD3DPsSamplerTopLeft.X, currentSession.DestD3DPsSamplerBottomRight.Y)
                        },
                        // Right-Top
                        new ShaderInputStructure {
                            Position     = new Vector3(currentSession.DestD3DVsBottomRight.X, currentSession.DestD3DVsTopLeft.Y, 0),
                            TextureCoord = new Vector2(currentSession.DestD3DPsSamplerBottomRight.X, currentSession.DestD3DPsSamplerTopLeft.Y)
                        },
                        // Right-Bottom
                        new ShaderInputStructure {
                            Position     = new Vector3(currentSession.DestD3DVsBottomRight.X, currentSession.DestD3DVsBottomRight.Y, 0),
                            TextureCoord = new Vector2(currentSession.DestD3DPsSamplerBottomRight.X, currentSession.DestD3DPsSamplerBottomRight.Y)
                        },
                        // Left-Bottom
                        new ShaderInputStructure {
                            Position     = new Vector3(currentSession.DestD3DVsTopLeft.X, currentSession.DestD3DVsBottomRight.Y, 0),
                            TextureCoord = new Vector2(currentSession.DestD3DPsSamplerTopLeft.X, currentSession.DestD3DPsSamplerBottomRight.Y)
                        },
                    };

                    var triangleVertexBuffer = D3D11.Buffer.Create(d3dDevice, D3D11.BindFlags.VertexBuffer, vertices);
                    var hdrMetadataBuffer    = new D3D11.Buffer(d3dDevice,
                                                                Utilities.SizeOf <ShaderHdrMetadata>(),
                                                                D3D11.ResourceUsage.Default,
                                                                D3D11.BindFlags.ConstantBuffer,
                                                                D3D11.CpuAccessFlags.None,
                                                                D3D11.ResourceOptionFlags.None,
                                                                0);

                    d3dContext.UpdateSubresource(ref hdrMetadata, hdrMetadataBuffer);

                    d3dContext.InputAssembler.PrimitiveTopology = D3D.PrimitiveTopology.TriangleList;
                    d3dContext.InputAssembler.InputLayout       = inputLayout;
                    d3dContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(triangleVertexBuffer, Utilities.SizeOf <ShaderInputStructure>(), 0));

                    d3dContext.VertexShader.Set(vsQuad);
                    d3dContext.PixelShader.SetConstantBuffer(0, hdrMetadataBuffer);
                    d3dContext.PixelShader.SetSampler(0, samplerState);

                    var canvasTexture = new D3D11.Texture2D(d3dDevice, new D3D11.Texture2DDescription
                    {
                        Width             = texture.Description.Width,
                        Height            = texture.Description.Height,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        Format            = currentSession.HdrMetadata.EnableHdrProcessing ? DXGI.Format.R16G16B16A16_Float : DXGI.Format.B8G8R8A8_UNorm_SRgb,
                        Usage             = D3D11.ResourceUsage.Default,
                        SampleDescription = new DXGI.SampleDescription(1, 0),
                        BindFlags         = D3D11.BindFlags.ShaderResource,
                        CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                        OptionFlags       = D3D11.ResourceOptionFlags.None,
                    });

                    using (canvasTexture)
                        using (var shaderResView = new D3D11.ShaderResourceView(d3dDevice, canvasTexture))
                        {
                            d3dContext.CopyResource(texture, canvasTexture);
                            d3dContext.PixelShader.SetShaderResource(0, shaderResView);
                            d3dContext.PixelShader.Set(psToneMapping);
                            d3dContext.Draw(vertices.Length, 0);
                        }

                    triangleVertexBuffer.Dispose();
                    hdrMetadataBuffer.Dispose();
                }
            }

            // Cleanup and signal event to proceed
            currentSession.Session.Dispose();
        }
Ejemplo n.º 14
0
 internal void UpdateSubresource(DataBox source, IResource resource, int subresource = 0)
 {
     m_deviceContext.UpdateSubresource(source, resource.Resource, subresource);
     CheckErrors();
 }
Ejemplo n.º 15
0
        public void Run()
        {
            if (_userResized)
            {
                Utilities.Dispose(ref _backBuffer);
                Utilities.Dispose(ref _renderView);
                Utilities.Dispose(ref _depthBuffer);
                Utilities.Dispose(ref _depthView);

                _swapChain.ResizeBuffers(_swapChainDescription.BufferCount, _form.ClientSize.Width, _form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);

                _backBuffer = D3D11.Resource.FromSwapChain <D3D11.Texture2D>(_swapChain, 0);

                _renderView = new D3D11.RenderTargetView(_device, _backBuffer);

                _depthBuffer = new D3D11.Texture2D(_device, new D3D11.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             = D3D11.ResourceUsage.Default,
                    BindFlags         = D3D11.BindFlags.DepthStencil,
                    CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                    OptionFlags       = D3D11.ResourceOptionFlags.None
                });

                _depthView = new D3D11.DepthStencilView(_device, _depthBuffer);

                _context.Rasterizer.SetViewport(new Viewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0.0f, 1.0f));
                _context.Rasterizer.State = new D3D11.RasterizerState(_device, new D3D11.RasterizerStateDescription
                {
                    FillMode = D3D11.FillMode.Solid,
                    CullMode = D3D11.CullMode.Front,
                    IsFrontCounterClockwise = false,
                });
                _context.OutputMerger.SetTargets(_depthView, _renderView);

                const float rads = (60.0f / 360.0f) * (float)Math.PI * 2.0f;

                _proj        = Matrix.PerspectiveFovLH(rads, _form.ClientSize.Width / (float)_form.ClientSize.Height, 0.1f, 1000.0f);
                _userResized = false;
            }

            var time = _clock.ElapsedMilliseconds / 1000.0f;
            var dt   = time - lastTime;

            if (key == Keys.W)
            {
                camera.goForward(dt);
            }

            if (key == Keys.S)
            {
                camera.goBack(dt);
            }
            lastTime = time;
            var point = new System.Drawing.Point(_form.Location.X + (_form.Size.Width / 2), _form.Location.Y + (_form.Size.Height / 2));
            //Cursor.Position = point;


            var modelMatrix = Matrix.RotationX(time) * Matrix.RotationY(time) * Matrix.RotationZ(time) * Matrix.Translation(_primordialObject.Position);


            var worldViewProj = modelMatrix * camera.ViewProjectionMatrix;

            modelMatrix.Transpose();
            worldViewProj.Transpose();
            var modelMatrixArray = modelMatrix.ToArray();
            var MVPMatrix        = worldViewProj.ToArray();

            var modelInverse = modelMatrix;

            modelInverse.Invert();
            //modelInverse.Transpose();


            //_primordialObject.Position = new Vector3((float)Math.Cos(time * 2), (float)Math.Sin(time*2), (float)Math.Sin(time * 2)* (float)Math.Cos(time * 2));
            var renderTime = _clock.ElapsedMilliseconds;

            _context.ClearDepthStencilView(_depthView, D3D11.DepthStencilClearFlags.Depth, 1.0f, 0);
            _context.ClearRenderTargetView(_renderView, SharpDX.Color.Black);

            _context.UpdateSubresource(MVPMatrix, _contantBuffer);
            _context.UpdateSubresource(modelMatrixArray, _contantBuffer2);
            _context.UpdateSubresource(modelInverse.ToArray(), _contantBuffer3);

            var frameTime = _clock.ElapsedMilliseconds;

            _context.Draw(_primordialObject.VertexData.Length, 0);

            _swapChain.Present(0, PresentFlags.None);
            if ((_clock.ElapsedMilliseconds - frameTime) > 15)
            {
                File.AppendAllText(fileTitle + ".txt", (_clock.ElapsedMilliseconds - frameTime).ToString() + "\n");
                count++;
            }
            // if(count > 1)
            //_form.Close();
            if (_clock.Elapsed.TotalSeconds > 105)
            {
                // _form.Close();
            }
        }
Ejemplo n.º 16
0
        public void Draw()
        {
            lock (_drawLock)
            {
                if (_ui == null || !_ui.ready)
                {
                    return;
                }

                if (_ui.gameStarted)
                {
                    // Update Device Tracking
                    compositor.WaitGetPoses(currentPoses, nextPoses);

                    if (currentPoses[headset].bPoseIsValid)
                    {
                        Convert(ref currentPoses[headset].mDeviceToAbsoluteTracking, ref head);
                    }

                    // Render Left Eye
                    context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                    context.OutputMerger.SetTargets(eyeDepthView, leftEyeTextureView);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.ClearRenderTargetView(leftEyeTextureView, backgroundColor);
                    context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                    Shaders.Normal.Apply(context);

                    context.Rasterizer.State = rasterizerState;

                    context.OutputMerger.SetBlendState(blendState);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.PixelShader.SetSampler(0, samplerState);

                    var ratio = (float)headsetSize.Width / (float)headsetSize.Height;

                    var projection = leftEyeProjection;
                    var view       = Matrix.Invert(leftEyeView * head);
                    var world      = Matrix.Translation(0, 0, -100.0f);

                    var worldViewProjection = world * view * projection;

                    //context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                    context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                    context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                    //Shapes.Cube.Begin(context);
                    //Shapes.Cube.Draw(context);

                    //Shapes.Sphere.Begin(context);
                    //Shapes.Sphere.Draw(context);

                    DrawPixels(worldViewProjection);

                    // Draw Controllers
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                    Shaders.NormalTexture.Apply(context);

                    context.PixelShader.SetSampler(0, samplerState);

                    foreach (var controller in controllers)
                    {
                        context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                        context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                        context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                        Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                        shaderParameters.WorldViewProjection = world * view * projection;
                        shaderParameters.Diffuse             = new Vector4(1, 1, 1, 1);

                        context.UpdateSubresource(ref shaderParameters, shaderParameterBuffer);

                        context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                        context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                        context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                    }

                    var texture = new Texture_t
                    {
                        eType       = ETextureType.DirectX,
                        eColorSpace = EColorSpace.Gamma,
                        handle      = leftEyeTextureView.Resource.NativePointer
                    };

                    var bounds = new VRTextureBounds_t
                    {
                        uMin = 0.0f,
                        uMax = 1.0f,
                        vMin = 0.0f,
                        vMax = 1.0f,
                    };

                    var submitError = compositor.Submit(EVREye.Eye_Left, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                    if (submitError != EVRCompositorError.None)
                    {
                        System.Diagnostics.Debug.WriteLine(submitError);
                    }

                    // Render Right Eye
                    context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                    context.OutputMerger.SetTargets(eyeDepthView, rightEyeTextureView);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.ClearRenderTargetView(rightEyeTextureView, backgroundColor);
                    context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                    Shaders.Normal.Apply(context);

                    context.Rasterizer.State = rasterizerState;

                    context.OutputMerger.SetBlendState(blendState);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.PixelShader.SetSampler(0, samplerState);

                    projection = rightEyeProjection;
                    view       = Matrix.Invert(rightEyeView * head);
                    world      = Matrix.Translation(0, 0, -100.0f);

                    worldViewProjection = world * view * projection;

                    //context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                    context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                    context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                    //Shapes.Cube.Begin(context);
                    //Shapes.Cube.Draw(context);

                    //Shapes.Sphere.Begin(context);
                    //Shapes.Sphere.Draw(context);

                    DrawPixels(worldViewProjection);

                    // Draw Controllers
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                    Shaders.NormalTexture.Apply(context);

                    context.PixelShader.SetSampler(0, samplerState);

                    foreach (var controller in controllers)
                    {
                        context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                        context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                        context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                        Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                        shaderParameters.WorldViewProjection = world * view * projection;
                        shaderParameters.Diffuse             = new Vector4(1, 1, 1, 1);

                        context.UpdateSubresource(ref shaderParameters, shaderParameterBuffer);

                        context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                        context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                        context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                    }

                    texture.handle = rightEyeTextureView.Resource.NativePointer;

                    submitError = compositor.Submit(EVREye.Eye_Right, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                    if (submitError != EVRCompositorError.None)
                    {
                        System.Diagnostics.Debug.WriteLine(submitError);
                    }

                    // Render Window
                    context.Rasterizer.SetViewport(0, 0, windowSize.Width, windowSize.Height);

                    context.OutputMerger.SetTargets(depthStencilView, backBufferView);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.ClearRenderTargetView(backBufferView, backgroundColor);
                    context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);

                    Shaders.Normal.Apply(context);

                    context.Rasterizer.State = rasterizerState;

                    context.OutputMerger.SetBlendState(blendState);
                    context.OutputMerger.SetDepthStencilState(depthStencilState);

                    context.PixelShader.SetSampler(0, samplerState);

                    ratio = (float)ClientSize.Width / (float)ClientSize.Height;

                    projection = Matrix.PerspectiveFovRH(3.14F / 3.0F, ratio, 0.01f, 1000);
                    view       = Matrix.Invert(head);
                    world      = Matrix.Translation(0, 0, -100.0f);

                    worldViewProjection = world * view * projection;

                    //context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                    context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                    context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                    //Shapes.Cube.Begin(context);
                    //Shapes.Cube.Draw(context);

                    //Shapes.Sphere.Begin(context);
                    //Shapes.Sphere.Draw(context);

                    DrawPixels(worldViewProjection);

                    // Draw Controllers
                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                    Shaders.NormalTexture.Apply(context);

                    context.PixelShader.SetSampler(0, samplerState);

                    foreach (var controller in controllers)
                    {
                        context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                        context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                        Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                        shaderParameters.WorldViewProjection = world * view * projection;
                        shaderParameters.Diffuse             = new Vector4(1, 1, 1, 1);

                        context.UpdateSubresource(ref shaderParameters, shaderParameterBuffer);

                        context.VertexShader.SetConstantBuffer(0, shaderParameterBuffer);
                        context.PixelShader.SetConstantBuffer(0, shaderParameterBuffer);

                        context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                    }

                    // Show Backbuffer
                    swapChain.Present(0, PresentFlags.None);
                }
            }
        }
Ejemplo n.º 17
0
 public void SetValue(SharpDX.Direct3D11.DeviceContext context, T value)
 {
     _value = value;
     context.UpdateSubresource <T>(ref value, Buffer);
 }
Ejemplo n.º 18
0
 public void UpdateBufferData <T>(Buffer buffer, T data) where T : struct
 {
     context.UpdateSubresource(ref data, buffer);
 }