Ejemplo n.º 1
0
 public static void Draw(DeviceContext context, float scale = 1f, float offset = 0f)
 {
     data.scale = scale;
     data.offset = offset;
     context.UpdateSubresource<cBuffer>(ref data, buffer, 0, 0, 0, null);
     context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
     context.InputAssembler.InputLayout = layout;
     context.InputAssembler.SetVertexBuffers(0, binding);
     context.VertexShader.Set(vertexShader);
     context.VertexShader.SetConstantBuffer(1, buffer);
     context.Draw(6, 0);
 }
Ejemplo n.º 2
0
        internal override void Draw(DeviceContext context)
        {
            Effect effect;
            using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("Graphics/Effects/default.fx", "bidon", "fx_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None))
            {
                effect = new Effect(context.Device, byteCode);
            }
            var technique = effect.GetTechniqueByIndex(1);
            var pass = technique.GetPassByIndex(0);
            InputLayout inputLayout = new InputLayout(context.Device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0),
                new InputElement("COLOR", 0, SlimDX.DXGI.Format.R8G8B8A8_UNorm, InputElement.AppendAligned, 0)
            });

            DataStream vertices = new DataStream((Vector3.SizeInBytes + 4) * 3, true, true);
            vertices.Write(new ColoredVertex(new Vector3(0.0f, 0.5f, 0.0f), new Color4(1.0f, 1.0f, 0.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(0.45f, -0.5f, 0.0f), new Color4(1.0f, 0.0f, 1.0f, 0.0f).ToArgb()));
            vertices.Write(new ColoredVertex(new Vector3(-0.45f, -0.5f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 1.0f).ToArgb()));
            vertices.Position = 0;
            BufferDescription bd = new BufferDescription()
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 16 * 3,
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None
            };

            var vertexBuffer = new SlimDX.Direct3D11.Buffer(context.Device, vertices, bd);

            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 16, 0));
            //context.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0);

            /* scale * rotation * translation */
            Matrix worldMatrix = Matrix.Scaling(Scale) * Matrix.RotationYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) *  Matrix.Translation(Position);

            Matrix viewMatrix = Camera.ViewMatrix;

            Matrix projectionMatrix = Camera.ProjectionMatrix;

            effect.GetVariableByName("finalMatrix").AsMatrix().SetMatrix(worldMatrix * viewMatrix * projectionMatrix);

            context.InputAssembler.InputLayout = inputLayout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            pass.Apply(context);
            context.Draw(3, 0);
        }
 public virtual void Render(DeviceContext deviceContext, ShaderResourceView inputRV, RenderTargetView renderTargetView)
 {
     deviceContext.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
     deviceContext.InputAssembler.InputLayout = null;
     deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleStrip;
     deviceContext.OutputMerger.SetTargets(renderTargetView);
     deviceContext.Rasterizer.State = rasterizerState;
     deviceContext.Rasterizer.SetViewport(viewport);
     deviceContext.VertexShader.SetShaderResource(0, null); // TODO: this should be done by the depthAndColorVS
     deviceContext.VertexShader.Set(vertexShader);
     deviceContext.GeometryShader.Set(null);
     deviceContext.PixelShader.Set(pixelShader);
     deviceContext.PixelShader.SetShaderResource(0, inputRV);
     if (constantBuffer != null)
         deviceContext.PixelShader.SetConstantBuffer(0, constantBuffer);
     deviceContext.Draw(4, 0);
     RenderTargetView nullRTV = null;
     deviceContext.OutputMerger.SetTargets(nullRTV);
     deviceContext.PixelShader.SetShaderResource(0, null);
 }
Ejemplo n.º 4
0
        public void RenderQuadTexture3DOnly( DeviceContext deviceContext, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Vector3 t1, Vector3 t2, Vector3 t3, Vector3 t4, ShaderResourceView texture, Camera camera )
        {
            DataBox databox;

            databox = deviceContext.MapSubresource( mPositionVertexBuffer,
                                                    0,
                                                    QUAD_NUM_VERTICES *
                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                    MapMode.WriteDiscard,
                                                    SlimDX.Direct3D11.MapFlags.None );

            databox.Data.Write( p1 );
            databox.Data.Write( p4 );
            databox.Data.Write( p2 );
            databox.Data.Write( p3 );

            deviceContext.UnmapSubresource( mPositionVertexBuffer, 0 );

            databox = deviceContext.MapSubresource( mTexCoordVertexBuffer,
                                                    0,
                                                    QUAD_NUM_VERTICES *
                                                    TEXCOORD_NUM_COMPONENTS_PER_VERTEX *
                                                    TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                                    MapMode.WriteDiscard,
                                                    SlimDX.Direct3D11.MapFlags.None );

            databox.Data.Write( t1 );
            databox.Data.Write( t4 );
            databox.Data.Write( t2 );
            databox.Data.Write( t3 );

            deviceContext.UnmapSubresource( mTexCoordVertexBuffer, 0 );

            deviceContext.InputAssembler.InputLayout = mRenderTexture3DInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            deviceContext.InputAssembler.SetVertexBuffers( POSITION_SLOT,
                                                           new VertexBufferBinding( mPositionVertexBuffer,
                                                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );
            deviceContext.InputAssembler.SetVertexBuffers( TEXCOORD_SLOT,
                                                           new VertexBufferBinding( mTexCoordVertexBuffer,
                                                                                    TEXCOORD_NUM_COMPONENTS_PER_VERTEX *
                                                                                    TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );

            mEffect.GetVariableByName( "gTexture3D" ).AsResource().SetResource( texture );
            mEffect.GetVariableByName( "gTransform" ).AsMatrix().SetMatrix( camera.GetLookAtMatrix() * camera.GetProjectionMatrix() );

            mRenderTexture3DPass.Apply( deviceContext );
            deviceContext.Draw( QUAD_NUM_VERTICES, 0 );
        }
Ejemplo n.º 5
0
        public void RenderPoint( DeviceContext deviceContext, Vector3 p, Vector3 color, Camera camera )
        {
            var databox = deviceContext.MapSubresource( mPositionVertexBuffer,
                                                        0,
                                                        POINT_NUM_VERTICES *
                                                        POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                        POSITION_NUM_BYTES_PER_COMPONENT,
                                                        MapMode.WriteDiscard,
                                                        SlimDX.Direct3D11.MapFlags.None );

            databox.Data.Write( p );

            deviceContext.UnmapSubresource( mPositionVertexBuffer, 0 );

            deviceContext.InputAssembler.InputLayout = mRenderWireframeInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.PointList;
            deviceContext.InputAssembler.SetVertexBuffers( POSITION_SLOT,
                                                           new VertexBufferBinding( mPositionVertexBuffer,
                                                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );

            mEffect.GetVariableByName( "gColor" ).AsVector().Set( color );
            mEffect.GetVariableByName( "gTransform" ).AsMatrix().SetMatrix( camera.GetLookAtMatrix() * camera.GetProjectionMatrix() );
            mRenderWireframePass.Apply( deviceContext );

            deviceContext.Draw( POINT_NUM_VERTICES, 0 );
        }
Ejemplo n.º 6
0
        public void Render(DeviceContext context)
        {
            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout = vertexBufferLayout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, vertexSize, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.VertexShader.SetConstantBuffer(constantBuffer, 0);

            context.PixelShader.Set(pixelShader);

            context.PixelShader.SetSampler(samplerLinear, 0);
            context.PixelShader.SetShaderResource(textureView, 0);

            context.OutputMerger.BlendState = blendState;

            // Note, one can use the: SlimDX.Toolkit.ConstantBuffer<T>
            var box = context.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            box.Data.Write(cb.PrepareData());
            context.UnmapSubresource(constantBuffer, 0);

            // draw the triangle
            context.Draw(vertexCount, 0);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Draw the 3d mesh to screen
        /// </summary>
        public override void Render( DeviceContext devCont )
        {
            Device dev = Engine.g_device;

            // empty the list

            //Performance.BeginEvent(new Color4(System.Drawing.Color.Turquoise), "Set Buffers");

            /// set the layout to the engine
            devCont.InputAssembler.InputLayout = m_input_layout;

            // set the type of primitive(triangleList)
            devCont.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // set the vertex buffer
            devCont.InputAssembler.SetVertexBuffers( 0, m_VertexBufferBinding );

            // set the index buffer
            //     dev.ImmediateContext.InputAssembler.SetIndexBuffer(m_BufferIndices, Format.R32_UInt, 0);

            /// set the position of the mesh base on the world matrix
            /// all the change pass to the shader
            m_shader.SetThePositions(m_WorldMatrix);

            //Performance.EndEvent();

            //Performance.BeginEvent(new Color4(System.Drawing.Color.Tomato), "Execute Shaders");
            /// Execute all the passes of the shader
            m_shader.Execute( devCont );
            //Performance.EndEvent();

            //Performance.BeginEvent(new Color4(System.Drawing.Color.PaleVioletRed), "Draw");
            // Render
            devCont.Draw( m_polygons.Count * 3, 0 );
            //Performance.EndEvent();
        }
        public void Render(DeviceContext deviceContext, ShaderResourceView depthImageTextureRV, ShaderResourceView colorImageTextureRV, SharpDX.Direct3D11.Buffer vertexBuffer, RenderTargetView renderTargetView, DepthStencilView depthStencilView, Viewport viewport)
        {
            //bilateralFilter.Render(deviceContext, depthImageTextureRV, filteredRenderTargetView2);
            //bilateralFilter.Render(deviceContext, filteredDepthImageSRV2, filteredRenderTargetView);

            //bilateralFilter.Render(deviceContext, filteredDepthImageSRV, filteredRenderTargetView2);
            //bilateralFilter.Render(deviceContext, filteredDepthImageSRV2, filteredRenderTargetView);

            deviceContext.InputAssembler.InputLayout = vertexInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, VertexPosition.SizeInBytes, 0)); // bytes per vertex
            deviceContext.Rasterizer.State = rasterizerState;
            deviceContext.Rasterizer.SetViewport(viewport);
            deviceContext.VertexShader.Set(depthAndColorVS);
            deviceContext.VertexShader.SetShaderResource(0, depthImageTextureRV);
            //deviceContext.VertexShader.SetShaderResource(0, depthAndMaskRV);
            //deviceContext.VertexShader.SetShaderResource(0, filteredDepthImageSRV);
            deviceContext.VertexShader.SetConstantBuffer(0, constantBuffer);
            deviceContext.GeometryShader.Set(depthAndColorGS);
            deviceContext.PixelShader.Set(depthAndColorPS);
            deviceContext.PixelShader.SetShaderResource(0, colorImageTextureRV);
            deviceContext.PixelShader.SetSampler(0, colorSamplerState);
            deviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);
            deviceContext.OutputMerger.DepthStencilState = depthStencilState;
            deviceContext.Draw((Kinect2Calibration.depthImageWidth - 1) * (Kinect2Calibration.depthImageHeight - 1) * 6, 0);
        }
Ejemplo n.º 9
0
        public void Render(DeviceContext deviceContext, ProjectMV project)
        {
            var   camera = project.Camera;
            float bottom = camera.ProjectY(0.0f);
            float top    = camera.ProjectY(project.Height);
            float left   = camera.ProjectX(0.0f);
            float right  = camera.ProjectX(project.Width);

            Matrix     linesWorld;
            Matrix     projection = camera.Projection;
            Matrix     worldViewProjection;
            DataStream dataStream;

            #region Boundary Lines

            deviceContext.InputAssembler.InputLayout = _inputLayoutLines;
            deviceContext.VertexShader.Set(_vertexShaderLines);
            deviceContext.HullShader.Set(null);
            deviceContext.DomainShader.Set(null);
            deviceContext.PixelShader.Set(_pixelShaderLines);

            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineStrip;
            deviceContext.InputAssembler.SetVertexBuffers(0, _bufferBindingBoundaryLines);

            deviceContext.VertexShader.SetConstantBuffers(0, _globalBufferLines);
            deviceContext.PixelShader.SetConstantBuffers(0, _globalBufferLines);

            linesWorld     = Matrix.Identity;
            linesWorld.M11 = right - left;
            linesWorld.M22 = -top + bottom;
            linesWorld.M41 = left - camera.Width / 2.0f;
            linesWorld.M42 = -bottom + camera.Height / 2.0f;

            Matrix.Multiply(ref linesWorld, ref projection, out worldViewProjection);
            // Transpose local Matrices
            Matrix.Transpose(ref worldViewProjection, out worldViewProjection);

            dataStream = null;
            deviceContext.MapSubresource(_globalBufferLines, 0, MapMode.WriteDiscard, MapFlags.None, out dataStream);
            dataStream.Write(worldViewProjection);
            dataStream.Write(_colorBoundaryLines);
            deviceContext.UnmapSubresource(_globalBufferLines, 0);

            deviceContext.Draw(5, 0);

            #endregion
            #region  Render Background
            Vector4 workingRect = new Vector4(bottom, top, left, right);
            Vector4 metrics     = new Vector4(borderWidth, -borderWidth, camera.Width, -camera.Height);


            Matrix backgroundWorld = Matrix.Identity;
            backgroundWorld.M41 = -camera.Width / 2.0f;
            backgroundWorld.M42 = camera.Height / 2.0f;


            Matrix.Multiply(ref backgroundWorld, ref projection, out worldViewProjection);
            // Transpose local Matrices
            Matrix.Transpose(ref worldViewProjection, out worldViewProjection);

            deviceContext.VertexShader.SetConstantBuffers(0, _globalBufferBackground);
            deviceContext.PixelShader.SetConstantBuffers(0, _globalBufferBackground);

            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            deviceContext.InputAssembler.InputLayout       = _inputLayoutBackground;
            deviceContext.VertexShader.Set(_vertexShaderBackground);
            deviceContext.HullShader.Set(null);
            deviceContext.DomainShader.Set(null);
            deviceContext.PixelShader.Set(_pixelShaderBackground);

            deviceContext.InputAssembler.SetIndexBuffer(_indexBufferBackground, Format.R32_UInt, 0);
            deviceContext.InputAssembler.SetVertexBuffers(0, _bufferBindingBackground);

            dataStream = null;
            deviceContext.MapSubresource(_globalBufferBackground, 0, MapMode.WriteDiscard, MapFlags.None, out dataStream);
            dataStream.Write(worldViewProjection);
            dataStream.Write(_color1Background);
            dataStream.Write(_color2Background);
            dataStream.Write(workingRect);
            dataStream.Write(metrics);
            deviceContext.UnmapSubresource(_globalBufferBackground, 0);

            deviceContext.DrawIndexed(18, 0, 0);

            #endregion
            #region Scala Lines
            deviceContext.VertexShader.SetConstantBuffers(0, _globalBufferLines);
            deviceContext.PixelShader.SetConstantBuffers(0, _globalBufferLines);

            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList;
            deviceContext.InputAssembler.InputLayout       = _inputLayoutLines;
            deviceContext.VertexShader.Set(_vertexShaderLines);
            deviceContext.HullShader.Set(null);
            deviceContext.DomainShader.Set(null);
            deviceContext.PixelShader.Set(_pixelShaderLines);

            deviceContext.InputAssembler.SetVertexBuffers(0, _bufferBindingScalaLines);

            // Top Lines
            linesWorld     = Matrix.Identity;
            linesWorld.M42 = camera.Height / 2.0f - 15.0f;
            linesWorld.M22 = 10.0f;
            // Compute Zoom

            float level;
            float scala;
            computeScala(camera.Zoom, out scala, out level);

            float shiftStepsX = (float)Math.Floor(left / scala);
            float shiftX      = shiftStepsX * scala;
            int   endIndex    = Math.Min((int)(camera.Width / scala), _countScalaElements) + 2;
            //int beginIndex = 20 - (int)((left- shift) / 10.0f);
            //int beginIndex = 20 - (int)((left- shift) * scala / 1000.0f);
            int beginIndex = 0;

            linesWorld.M11 = scala;
            linesWorld.M41 = -camera.Width / 2.0f + left - shiftX - scala;

            Matrix.Multiply(ref linesWorld, ref projection, out worldViewProjection);
            // Transpose local Matrices
            Matrix.Transpose(ref worldViewProjection, out worldViewProjection);

            dataStream = null;
            deviceContext.MapSubresource(_globalBufferLines, 0, MapMode.WriteDiscard, MapFlags.None, out dataStream);
            dataStream.Write(worldViewProjection);
            dataStream.Write(_colorScalaLines);
            deviceContext.UnmapSubresource(_globalBufferLines, 0);

            deviceContext.Draw(20 * endIndex, beginIndex * 2);


            // Left Lines
            float shiftStepsY = (float)Math.Floor((camera.Height - bottom) / scala + 1.0f);
            float shiftY      = shiftStepsY * scala;
            endIndex = Math.Min((int)(camera.Height / scala), _countScalaElements) + 2;

            linesWorld     = Matrix.Identity;
            linesWorld.M42 = +camera.Height / 2.0f - bottom - shiftY;
            linesWorld.M12 = scala;


            linesWorld.M41 = -camera.Width / 2.0f + 15.0f;
            linesWorld.M11 = 0.0f;
            linesWorld.M22 = 0.0f;
            linesWorld.M21 = -10.0f;

            Matrix.Multiply(ref linesWorld, ref projection, out worldViewProjection);
            // Transpose local Matrices
            Matrix.Transpose(ref worldViewProjection, out worldViewProjection);

            dataStream = null;
            deviceContext.MapSubresource(_globalBufferLines, 0, MapMode.WriteDiscard, MapFlags.None, out dataStream);
            dataStream.Write(worldViewProjection);
            dataStream.Write(_colorScalaLines);
            deviceContext.UnmapSubresource(_globalBufferLines, 0);

            deviceContext.Draw(20 * endIndex, 0);
            #endregion
            #region Curser Lines
            if (_drawCursorLines)
            {
                //Vector2 curserpos = camera.UnProject(project.CurserPos);

                metrics = new Vector4(borderWidth, -borderWidth, (float)project.CurserPos.X, -(float)project.CurserPos.Y);
                Matrix cursorWorld = Matrix.Identity;
                cursorWorld.M41 = -camera.Width / 2.0f;
                cursorWorld.M42 = camera.Height / 2.0f;


                Matrix.Multiply(ref cursorWorld, ref projection, out worldViewProjection);
                // Transpose local Matrices
                Matrix.Transpose(ref worldViewProjection, out worldViewProjection);

                deviceContext.VertexShader.SetConstantBuffers(0, _globalBufferCursorLines);
                deviceContext.PixelShader.SetConstantBuffers(0, _globalBufferCursorLines);

                deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList;
                deviceContext.InputAssembler.InputLayout       = _inputLayoutCursorLines;
                deviceContext.VertexShader.Set(_vertexShaderCursorLines);
                deviceContext.HullShader.Set(null);
                deviceContext.DomainShader.Set(null);
                deviceContext.PixelShader.Set(_pixelShaderCursorLines);

                deviceContext.InputAssembler.SetVertexBuffers(0, _bufferBindingCursorLines);

                dataStream = null;
                deviceContext.MapSubresource(_globalBufferCursorLines, 0, MapMode.WriteDiscard, MapFlags.None, out dataStream);
                dataStream.Write(worldViewProjection);
                dataStream.Write(_colorCursorLines);
                dataStream.Write(metrics);
                deviceContext.UnmapSubresource(_globalBufferCursorLines, 0);

                deviceContext.Draw(4, 0);
            }
            #endregion
            #region Top Numbers
            int   digits = Math.Max(-(int)Math.Floor(Math.Log10(level)) + 0, 0);
            float valueX = -shiftStepsX * level;

            float firstX = left - shiftX;
            int   countX = (int)((camera.Width + 30.0f) / scala);

            for (int i = 0; i < countX; i++)
            {
                float posX = firstX + 5.0f + scala * i;
                _numbersRenderer.Draw(valueX, posX, camera.Height - 10.0f, deviceContext, camera, digits);
                valueX += level;
            }
            // Left Numbers
            float valueY = -shiftStepsY * level;

            float firstY = (bottom - shiftY);
            int   countY = (int)((camera.Height + 30.0f) / scala);

            //for (int i = 0; i < countY; i++)
            //{
            //	float posY = firstY - scala * i;
            //	//_numbersRenderer.Draw(valueY, 12.0f, -posY, deviceContext, camera, true);
            //	_numbersRenderer.Draw(valueY, 12.0f, camera.Height/2.0f - posY - 10.0f, deviceContext, camera, true);

            //	valueY += level;
            //}
            for (int i = 1; i < countY + 2; i++)
            {
                _numbersRenderer.Draw(level * (-shiftStepsY + i), 10.0f, camera.Height - (bottom + shiftY) + 5.0f + scala * i, deviceContext, camera, digits, true);
            }
            #endregion
        }
Ejemplo n.º 10
0
        void DrawFigure(Figure fig)
        {
            LightDirForced_variable.Set(fig.LightDirForced());
            foreach (TSOFile tso in fig.TSOFileList)
            {
                int current_spec = -1;

                foreach (TSOMesh mesh in tso.meshes)
                {
                    foreach (TSOSubMesh sub_mesh in mesh.sub_meshes)
                    {
                        TSOSubScript scr = tso.sub_scripts[sub_mesh.spec];

                        if (sub_mesh.spec != current_spec)
                        {
                            current_spec = sub_mesh.spec;

                            cb_variable.SetConstantBuffer(scr.cb);

                            TSOTex shadeTex;
                            if (tso.texmap.TryGetValue(scr.shader.ShadeTexName, out shadeTex))
                            {
                                ShadeTex_texture_variable.SetResource(shadeTex.d3d_tex_view);
                            }

                            TSOTex colorTex;
                            if (tso.texmap.TryGetValue(scr.shader.ColorTexName, out colorTex))
                            {
                                ColorTex_texture_variable.SetResource(colorTex.d3d_tex_view);
                            }
                        }

                        int technique_idx = scr.shader.technique_idx;

                        var technique = effect.GetTechniqueByIndex(technique_idx);
                        if (!technique.IsValid)
                        {
                            string technique_name = scr.shader.technique_name;
                            Console.WriteLine("technique {0} is not valid", technique_name);
                            continue;
                        }

                        LocalBoneMats_variable.SetMatrix(fig.ClipBoneMatrices(sub_mesh));

                        if (!technique.GetPassByIndex(0).IsValid)
                        {
                            Console.WriteLine("pass #0 is not valid");
                            continue;
                        }

                        ctx.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
                        ctx.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(sub_mesh.vb, 52, 0));

                        for (int i = 0; i < technique.Description.PassCount; i++)
                        {
                            ctx.OutputMerger.SetBlendState(default_blend_state);
                            ctx.OutputMerger.SetDepthStencilState(default_depth_stencil_state);
                            ctx.Rasterizer.State = default_rasterizer_state;

                            technique.GetPassByIndex(i).Apply(ctx);
                            ctx.Draw(sub_mesh.vertices.Length, 0);
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// 描画
 /// </summary>
 public void Draw(int start, int count)
 {
     context_.Draw(count, start);
 }
Ejemplo n.º 12
0
        void Render()
        {
            // Clear targets
            _immediateContext.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            //_immediateContext.ClearRenderTargetView(renderView, ambient);
            _immediateContext.ClearRenderTargetView(gBufferLightView, Color4.Black);
            _immediateContext.ClearRenderTargetView(gBufferNormalView, Color4.Black);
            _immediateContext.ClearRenderTargetView(gBufferDiffuseView, Color4.Black);


            // Read collision object transforms, create geometry, etc.
            _meshFactory.InitInstancedRender();


            // Light depth map pass
            _immediateContext.ClearDepthStencilView(lightDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            if (shadowsEnabled)
            {
                outputMerger.SetDepthStencilState(lightDepthStencilState);
                outputMerger.SetRenderTargets(lightDepthView);
                shadowGenPass.Apply(_immediateContext);
                OnRender();
                shadowLightDepthBufferVar.SetResource(lightDepthRes);
            }

            // Render geometry (colors, normals, depth) to G-buffer
            outputMerger.SetDepthStencilState(depthState);
            outputMerger.SetTargets(depthView, gBufferViews);
            gBufferGenPass.Apply(_immediateContext);
            OnRender();

            if (Demo.IsDebugDrawEnabled)
            {
                debugDrawPass.Apply(_immediateContext);
                (Demo.World.DebugDrawer as PhysicsDebugDraw).DrawDebugWorld(Demo.World);
            }

            // Light accumulation to G-buffer
            if (deferredLightingEnabled)
            {
                outputMerger.SetBlendState(additiveBlendState);
                // Can't set depthView as render target and shader variable at the same time,
                // so early HW depth test is not available for light volumes.
                //outputMerger.SetTargets(depthView, gBufferLightView);
                outputMerger.SetTargets(gBufferLightView);
                RenderLights();
            }


            // Render G-buffer
            outputMerger.SetBlendState(alphaBlendState);
            outputMerger.SetDepthStencilState(null);
            if (depthOfFieldEnabled)
            {
                outputMerger.SetTargets(gBufferPostProcessView);
            }
            else
            {
                outputMerger.SetTargets(renderView);
            }
            inputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            lightBufferVar.SetResource(lightBufferRes);
            normalBufferVar.SetResource(normalBufferRes);
            diffuseBufferVar.SetResource(diffuseBufferRes);
            depthMapVar.SetResource(depthBufferRes);

            //_immediateContext.ClearRenderTargetView(gBufferPostProcessView, Color4.Black);
            gBufferRenderPass.Apply(_immediateContext);
            _immediateContext.Draw(3, 0);

            if (depthOfFieldEnabled)
            {
                diffuseBufferVar.SetResource(postProcessBufferRes);
                outputMerger.SetTargets(gBufferPostProcessViewBlur1);
                gBufferPostProcessPass.Apply(_immediateContext);
                _immediateContext.Draw(3, 0);

                diffuseBufferVar.SetResource(postProcessBufferBlur1Res);
                outputMerger.SetTargets(gBufferPostProcessViewBlur2);
                gBufferPostProcessPass.Apply(_immediateContext);
                _immediateContext.Draw(3, 0);


                diffuseBufferVar.SetResource(postProcessBufferBlur2Res);
                outputMerger.SetTargets(gBufferPostProcessViewBlur1);
                gBufferPostProcessPass.Apply(_immediateContext);
                _immediateContext.Draw(3, 0);


                diffuseBufferVar.SetResource(postProcessBufferBlur1Res);
                outputMerger.SetTargets(gBufferPostProcessViewBlur2);
                gBufferPostProcessPass.Apply(_immediateContext);
                _immediateContext.Draw(3, 0);


                diffuseBufferVar.SetResource(postProcessBufferRes);
                normalBufferVar.SetResource(postProcessBufferBlur2Res);
                outputMerger.SetTargets(renderView);
                gBufferPostProcessPass2.Apply(_immediateContext);
                _immediateContext.Draw(3, 0);
            }


            // Render overlay
            info.Render();
            outputMerger.SetBlendState(alphaBlendState);
            diffuseBufferVar.SetResource(info.OverlayBufferRes);
            gBufferOverlayPass.Apply(_immediateContext);
            _immediateContext.Draw(4, 0);

            _swapChain.Present(0, PresentFlags.None);
        }
Ejemplo n.º 13
0
        void Render()
        {
            // Clear targets
            _immediateContext.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            _immediateContext.ClearRenderTargetView(renderView, ambient);
            _immediateContext.ClearRenderTargetView(gBufferLightView, ambient);
            _immediateContext.ClearRenderTargetView(gBufferNormalView, ambient);
            _immediateContext.ClearRenderTargetView(gBufferDiffuseView, ambient);

            _meshFactory.InitInstancedRender(Demo.World.CollisionObjectArray);

            // Light depth map pass
            if (shadowsEnabled)
            {
                _immediateContext.ClearDepthStencilView(lightDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                outputMerger.SetDepthStencilState(lightDepthStencilState);
                outputMerger.SetRenderTargets(lightDepthView);
                shadowGenPass.Apply(_immediateContext);
                OnRender();
                lightDepthMapVar.SetResource(lightDepthRes);
            }

            // Render to G-buffer
            lightBufferVar.SetResource(null);
            normalBufferVar.SetResource(null);
            diffuseBufferVar.SetResource(null);
            depthMapVar.SetResource(null);
            lightDepthMapVar.SetResource(null);

            outputMerger.SetDepthStencilState(depthStencilState);
            outputMerger.SetTargets(depthView, gBufferViews);
            gBufferGenPass.Apply(_immediateContext);
            OnRender();

            if (Demo.IsDebugDrawEnabled)
            {
                debugDrawPass.Apply(_immediateContext);
                (Demo.World.DebugDrawer as PhysicsDebugDraw).DrawDebugWorld(Demo.World);
            }

            outputMerger.SetDepthStencilState(null);
            info.OnRender(Demo.FramesPerSecond);


            outputMerger.SetTargets(renderView);
            inputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            // Render G-buffer
            lightBufferVar.SetResource(lightBufferRes);
            normalBufferVar.SetResource(normalBufferRes);
            diffuseBufferVar.SetResource(diffuseBufferRes);
            depthMapVar.SetResource(depthRes);
            lightDepthMapVar.SetResource(lightDepthRes);
            gBufferRenderPass.Apply(_immediateContext);
            _immediateContext.Draw(3, 0);


            // Render overlay
            outputMerger.SetBlendState(alphaBlendState);
            diffuseBufferVar.SetResource(info.OverlayBufferRes);
            gBufferOverlayPass.Apply(_immediateContext);
            _immediateContext.Draw(4, 0);

            _swapChain.Present(0, PresentFlags.None);
        }
Ejemplo n.º 14
0
        private void RenderTileCacheEntry(DeviceContext deviceContext, Camera camera, int datasetExtentDataSpaceX, int datasetExtentDataSpaceY, TileCacheEntry tileCacheEntry, Viewport viewport)
        {
            //
            // Check if this tile is over the edge of the image
            //
            var tileMinExtentX      = tileCacheEntry.CenterDataSpace.X - (tileCacheEntry.ExtentDataSpace.X / 2f);
            var tileMinExtentY      = tileCacheEntry.CenterDataSpace.Y - (tileCacheEntry.ExtentDataSpace.Y / 2f);
            var tileMaxExtentX      = tileCacheEntry.CenterDataSpace.X + (tileCacheEntry.ExtentDataSpace.X / 2f);
            var tileMaxExtentY      = tileCacheEntry.CenterDataSpace.Y + (tileCacheEntry.ExtentDataSpace.Y / 2f);
            var tileProportionClipX = 1f;
            var tileProportionClipY = 1f;

            if (datasetExtentDataSpaceX > 0 && tileMaxExtentX > datasetExtentDataSpaceX)
            {
                tileProportionClipX = 1 - ((tileMaxExtentX - datasetExtentDataSpaceX) / (tileMaxExtentX - tileMinExtentX));
                tileMaxExtentX      = datasetExtentDataSpaceX;
            }
            if (datasetExtentDataSpaceY > 0 && tileMaxExtentY > datasetExtentDataSpaceY)
            {
                tileProportionClipY = 1 - ((tileMaxExtentY - datasetExtentDataSpaceY) / (tileMaxExtentY - tileMinExtentY));
                tileMaxExtentY      = datasetExtentDataSpaceY;
            }

            var p1 = new Vector3(tileMinExtentX, tileMinExtentY, 0.5f);
            var p2 = new Vector3(tileMinExtentX, tileMaxExtentY, 0.5f);
            var p3 = new Vector3(tileMaxExtentX, tileMaxExtentY, 0.5f);
            var p4 = new Vector3(tileMaxExtentX, tileMinExtentY, 0.5f);

            var t1 = new Vector3(0f, 0f, 0f);
            var t2 = new Vector3(0f, tileProportionClipY, 0f);
            var t3 = new Vector3(tileProportionClipX, tileProportionClipY, 0f);
            var t4 = new Vector3(tileProportionClipX, 0f, 0f);

            DataBox databox;

            databox = deviceContext.MapSubresource(mPositionVertexBuffer,
                                                   0,
                                                   QUAD_NUM_VERTICES *
                                                   POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                   POSITION_NUM_BYTES_PER_COMPONENT,
                                                   MapMode.WriteDiscard,
                                                   SlimDX.Direct3D11.MapFlags.None);

            databox.Data.Write(p1);
            databox.Data.Write(p4);
            databox.Data.Write(p2);
            databox.Data.Write(p3);

            deviceContext.UnmapSubresource(mPositionVertexBuffer, 0);

            databox = deviceContext.MapSubresource(mTexCoordVertexBuffer,
                                                   0,
                                                   QUAD_NUM_VERTICES *
                                                   TEXCOORD_NUM_COMPONENTS_PER_VERTEX *
                                                   TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                                   MapMode.WriteDiscard,
                                                   SlimDX.Direct3D11.MapFlags.None);

            databox.Data.Write(t1);
            databox.Data.Write(t4);
            databox.Data.Write(t2);
            databox.Data.Write(t3);

            deviceContext.UnmapSubresource(mTexCoordVertexBuffer, 0);

            deviceContext.InputAssembler.InputLayout       = mInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            deviceContext.InputAssembler.SetVertexBuffers(POSITION_SLOT,
                                                          new VertexBufferBinding(mPositionVertexBuffer,
                                                                                  POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                                                  POSITION_NUM_BYTES_PER_COMPONENT,
                                                                                  0));
            deviceContext.InputAssembler.SetVertexBuffers(TEXCOORD_SLOT,
                                                          new VertexBufferBinding(mTexCoordVertexBuffer,
                                                                                  TEXCOORD_NUM_COMPONENTS_PER_VERTEX *
                                                                                  TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                                                                  0));

            mEffect.GetVariableByName("gSourceTexture3D").AsResource().SetResource(tileCacheEntry.D3D11CudaTextures.Get("SourceMap"));
            if (mTileManager.SegmentationLoaded)
            {
                //if ( tileCacheEntry.D3D11CudaTextures.Internal.ContainsKey( "IdMap" ) )
                //{
                //    mEffect.GetVariableByName( "gIdTexture3D" ).AsResource().SetResource( tileCacheEntry.D3D11CudaTextures.Get( "IdMap" ) );
                //}
                //else
                //{
                //    System.Console.WriteLine("Warning: expected IdMap not found.");
                //}
                mEffect.GetVariableByName("gIdTexture3D").AsResource().SetResource(tileCacheEntry.D3D11CudaTextures.Get("IdMap"));
                mEffect.GetVariableByName("gIdColorMapBuffer").AsResource().SetResource(mTileManager.Internal.GetIdColorMap());
                mEffect.GetVariableByName("gLabelIdMapBuffer").AsResource().SetResource(mTileManager.Internal.GetLabelIdMap());
                mEffect.GetVariableByName("gIdConfidenceMapBuffer").AsResource().SetResource(mTileManager.Internal.GetIdConfidenceMap());

                if (tileCacheEntry.D3D11CudaTextures.Internal.ContainsKey("OverlayMap"))
                {
                    mEffect.GetVariableByName("gOverlayTexture3D").AsResource().SetResource(tileCacheEntry.D3D11CudaTextures.Get("OverlayMap"));
                }
            }
            mEffect.GetVariableByName("gTransform").AsMatrix().SetMatrix(camera.GetLookAtMatrix() * camera.GetProjectionMatrix());
            mEffect.GetVariableByName("gSegmentationRatio").AsScalar().Set(mTileManager.SegmentationVisibilityRatio);
            mEffect.GetVariableByName("gBoundaryLinesVisible").AsScalar().Set(mTileManager.ShowBoundaryLines);
            mEffect.GetVariableByName("gBrushVisible").AsScalar().Set(true);
            mEffect.GetVariableByName("gSelectedSegmentId").AsScalar().Set(mTileManager.SelectedSegmentId);
            mEffect.GetVariableByName("gMouseOverSegmentId").AsScalar().Set(mTileManager.MouseOverSegmentId);

            mEffect.GetVariableByName("gMouseOverX").AsScalar().Set((mTileManager.MouseOverX - tileMinExtentX) / tileCacheEntry.ExtentDataSpace.X);
            mEffect.GetVariableByName("gMouseOverY").AsScalar().Set((mTileManager.MouseOverY - tileMinExtentY) / tileCacheEntry.ExtentDataSpace.Y);
            mEffect.GetVariableByName("gMouseHighlightSize").AsScalar().Set(mTileManager.MergeBrushSize);

            mPass.Apply(deviceContext);
            deviceContext.Draw(QUAD_NUM_VERTICES, 0);

            //mDebugRenderer.RenderQuadWireframeOnly( deviceContext, p1, p2, p3, p4, new Vector3( 1, 0, 0 ), camera );
        }
Ejemplo n.º 15
0
        public void Update(Camera camera)
        {
            if (userResized)
            {
                // Dispose all previous allocated resources
                Utilities.Dispose(ref backBuffer);
                Utilities.Dispose(ref renderView);
                Utilities.Dispose(ref depthBuffer);
                Utilities.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.SetViewport(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
//                projMatrix = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, camera.near, camera.far);

                // We are done resizing
                userResized = false;
            }
            Color4 col = new Color4(0.5f, 0.5f, 0.5f, 1.0f);

            unsafe
            {
                context.ClearRenderTargetView(renderTarget, *(RawColor4 *)&col);
            }
            swapChain.Present(0, PresentFlags.None);
//            Matrix.Translation(0.0f, 0.0f, 5.0f, out viewMatrix);
            //Camera.Current.Update();
//            Matrix.Multiply(ref camera.Parent.transform.worldMatrix, ref camera.projectionMatrix, out viewProjMatrix);
            //Matrix.Multiply(ref viewMatrix, ref Camera.Current.projectionMatrix, out viewProjMatrix);
            Matrix.Multiply(ref Camera.Current.Entity.Transform.worldMatrix, ref Camera.Current.projectionMatrix, out viewProjMatrix);
            context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            context.ClearRenderTargetView(renderView, Color.Black);

            var time = clock.ElapsedMilliseconds / 1000.0f;

            // Update WorldViewProj Matrix
            var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProjMatrix;

            worldViewProj.Transpose();
            context.UpdateSubresource(ref worldViewProj, contantBuffer);

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

            // Present!
            swapChain.Present(0, PresentFlags.None);
        }
        private void RenderTileCacheEntry( DeviceContext deviceContext, Camera camera, int datasetExtentDataSpaceX, int datasetExtentDataSpaceY, TileCacheEntry tileCacheEntry, Viewport viewport )
        {
            //Check if this tile is over the edge of the image
            var tileMinExtentX = tileCacheEntry.CenterDataSpace.X - ( tileCacheEntry.ExtentDataSpace.X / 2f );
            var tileMinExtentY = tileCacheEntry.CenterDataSpace.Y - ( tileCacheEntry.ExtentDataSpace.Y / 2f );
            var tileMaxExtentX = tileCacheEntry.CenterDataSpace.X + ( tileCacheEntry.ExtentDataSpace.X / 2f );
            var tileMaxExtentY = tileCacheEntry.CenterDataSpace.Y + ( tileCacheEntry.ExtentDataSpace.Y / 2f );
            var tileProportionClipX = 1f;
            var tileProportionClipY = 1f;

            if ( datasetExtentDataSpaceX > 0 && tileMaxExtentX > datasetExtentDataSpaceX )
            {
                tileProportionClipX = 1 - ( ( tileMaxExtentX - datasetExtentDataSpaceX ) / ( tileMaxExtentX - tileMinExtentX ) );
                tileMaxExtentX = datasetExtentDataSpaceX;
            }
            if ( datasetExtentDataSpaceY > 0 && tileMaxExtentY > datasetExtentDataSpaceY )
            {
                tileProportionClipY = 1 - ( ( tileMaxExtentY - datasetExtentDataSpaceY ) / ( tileMaxExtentY - tileMinExtentY ) );
                tileMaxExtentY = datasetExtentDataSpaceY;
            }

            var p1 = new Vector3( tileMinExtentX, tileMinExtentY, 0.5f );
            var p2 = new Vector3( tileMinExtentX, tileMaxExtentY, 0.5f );
            var p3 = new Vector3( tileMaxExtentX, tileMaxExtentY, 0.5f );
            var p4 = new Vector3( tileMaxExtentX, tileMinExtentY, 0.5f );

            var t1 = new Vector3( 0f, 0f, 0f );
            var t2 = new Vector3( 0f, tileProportionClipY, 0f );
            var t3 = new Vector3( tileProportionClipX, tileProportionClipY, 0f );
            var t4 = new Vector3( tileProportionClipX, 0f, 0f );

            DataBox databox;

            databox = deviceContext.MapSubresource( mPositionVertexBuffer,
                                                    0,
                                                    QUAD_NUM_VERTICES *
                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                    MapMode.WriteDiscard,
                                                    SlimDX.Direct3D11.MapFlags.None );

            databox.Data.Write( p1 );
            databox.Data.Write( p4 );
            databox.Data.Write( p2 );
            databox.Data.Write( p3 );

            deviceContext.UnmapSubresource( mPositionVertexBuffer, 0 );

            databox = deviceContext.MapSubresource( mTexCoordVertexBuffer,
                                                    0,
                                                    QUAD_NUM_VERTICES *
                                                    TEXCOORD_NUM_COMPONENTS_PER_VERTEX *
                                                    TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                                    MapMode.WriteDiscard,
                                                    SlimDX.Direct3D11.MapFlags.None );

            databox.Data.Write( t1 );
            databox.Data.Write( t4 );
            databox.Data.Write( t2 );
            databox.Data.Write( t3 );

            deviceContext.UnmapSubresource( mTexCoordVertexBuffer, 0 );

            deviceContext.InputAssembler.InputLayout = mInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            deviceContext.InputAssembler.SetVertexBuffers( POSITION_SLOT,
                                                           new VertexBufferBinding( mPositionVertexBuffer,
                                                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );
            deviceContext.InputAssembler.SetVertexBuffers( TEXCOORD_SLOT,
                                                           new VertexBufferBinding( mTexCoordVertexBuffer,
                                                                                    TEXCOORD_NUM_COMPONENTS_PER_VERTEX *
                                                                                    TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );

            mEffect.GetVariableByName( "gSourceTexture3D" ).AsResource().SetResource( tileCacheEntry.D3D11CudaTextures.Get( "SourceMap" ) );
            if ( mTileManager.SegmentationLoaded )
            {
                //if ( tileCacheEntry.D3D11CudaTextures.Internal.ContainsKey( "IdMap" ) )
                //{
                //    mEffect.GetVariableByName( "gIdTexture3D" ).AsResource().SetResource( tileCacheEntry.D3D11CudaTextures.Get( "IdMap" ) );
                //}
                //else
                //{
                //    System.Console.WriteLine("Warning: expected IdMap not found.");
                //}
                mEffect.GetVariableByName( "gIdTexture3D" ).AsResource().SetResource( tileCacheEntry.D3D11CudaTextures.Get( "IdMap" ) );
                mEffect.GetVariableByName( "gIdColorMapBuffer" ).AsResource().SetResource( mTileManager.Internal.GetIdColorMap() );
                mEffect.GetVariableByName( "gLabelIdMapBuffer" ).AsResource().SetResource( mTileManager.Internal.GetLabelIdMap() );
                mEffect.GetVariableByName( "gIdConfidenceMapBuffer" ).AsResource().SetResource( mTileManager.Internal.GetIdConfidenceMap() );

                if ( tileCacheEntry.D3D11CudaTextures.Internal.ContainsKey( "OverlayMap" ) )
                {
                    mEffect.GetVariableByName( "gOverlayTexture3D" ).AsResource().SetResource( tileCacheEntry.D3D11CudaTextures.Get( "OverlayMap" ) );
                }
            }
            mEffect.GetVariableByName( "gTransform" ).AsMatrix().SetMatrix( camera.GetLookAtMatrix() * camera.GetProjectionMatrix() );
            mEffect.GetVariableByName( "gSegmentationRatio" ).AsScalar().Set( mTileManager.SegmentationVisibilityRatio );
            mEffect.GetVariableByName( "gBoundaryLinesVisible" ).AsScalar().Set( mTileManager.ShowBoundaryLines );
            mEffect.GetVariableByName( "gBrushVisible" ).AsScalar().Set( mTileManager.SelectedSegmentId != 0 );
            mEffect.GetVariableByName( "gSelectedSegmentId" ).AsScalar().Set( mTileManager.SelectedSegmentId );
            mEffect.GetVariableByName( "gMouseOverSegmentId" ).AsScalar().Set( mTileManager.MouseOverSegmentId );

            mEffect.GetVariableByName( "gMouseOverX" ).AsScalar().Set( ( mTileManager.MouseOverX - tileMinExtentX ) / tileCacheEntry.ExtentDataSpace.X );
            mEffect.GetVariableByName( "gMouseOverY" ).AsScalar().Set( ( mTileManager.MouseOverY - tileMinExtentY ) / tileCacheEntry.ExtentDataSpace.Y );
            mEffect.GetVariableByName( "gMouseHighlightSize" ).AsScalar().Set( mTileManager.BrushSize );

            mPass.Apply( deviceContext );
            deviceContext.Draw( QUAD_NUM_VERTICES, 0 );

            //mDebugRenderer.RenderQuadWireframeOnly( deviceContext, p1, p2, p3, p4, new Vector3( 1, 0, 0 ), camera );
        }
Ejemplo n.º 17
0
        public void Render(DeviceContext deviceContext)
        {
            deviceContext.InputAssembler.InputLayout = vertexInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList;
            deviceContext.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
            deviceContext.Rasterizer.State = rasterizerState;

            deviceContext.VertexShader.Set(frustumVS);
            deviceContext.VertexShader.SetConstantBuffer(0, vertexShaderConstantBuffer);

            deviceContext.GeometryShader.Set(null);

            deviceContext.PixelShader.SetConstantBuffer(0, pixelShaderConstantBuffer);
            deviceContext.PixelShader.Set(frustumPS);

            deviceContext.Draw(24, 0);
        }
Ejemplo n.º 18
0
        private static void Main()
        {
            RenderForm form = new RenderForm("OculusWrap SharpDX demo");

            IntPtr          sessionPtr;
            InputLayout     inputLayout          = null;
            Buffer          contantBuffer        = null;
            Buffer          vertexBuffer         = null;
            ShaderSignature shaderSignature      = null;
            PixelShader     pixelShader          = null;
            ShaderBytecode  pixelShaderByteCode  = null;
            VertexShader    vertexShader         = null;
            ShaderBytecode  vertexShaderByteCode = null;
            Texture2D       mirrorTextureD3D     = null;

            EyeTexture[]      eyeTextures                = null;
            DeviceContext     immediateContext           = null;
            DepthStencilState depthStencilState          = null;
            DepthStencilView  depthStencilView           = null;
            Texture2D         depthBuffer                = null;
            RenderTargetView  backBufferRenderTargetView = null;
            Texture2D         backBuffer = null;

            SharpDX.DXGI.SwapChain swapChain = null;
            Factory       factory            = null;
            MirrorTexture mirrorTexture      = null;
            Guid          textureInterfaceId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c");                                                            // Interface ID of the Direct3D Texture2D interface.

            Result result;

            OvrWrap OVR = OvrWrap.Create();

            // Define initialization parameters with debug flag.
            InitParams initializationParameters = new InitParams();

            initializationParameters.Flags = InitFlags.Debug | InitFlags.RequestVersion;
            initializationParameters.RequestedMinorVersion = 17;

            // Initialize the Oculus runtime.
            string errorReason = null;

            try
            {
                result = OVR.Initialize(initializationParameters);

                if (result < Result.Success)
                {
                    errorReason = result.ToString();
                }
            }
            catch (Exception ex)
            {
                errorReason = ex.Message;
            }

            if (errorReason != null)
            {
                MessageBox.Show("Failed to initialize the Oculus runtime library:\r\n" + errorReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Use the head mounted display.
            sessionPtr = IntPtr.Zero;
            var graphicsLuid = new GraphicsLuid();

            result = OVR.Create(ref sessionPtr, ref graphicsLuid);
            if (result < Result.Success)
            {
                MessageBox.Show("The HMD is not enabled: " + result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var hmdDesc = OVR.GetHmdDesc(sessionPtr);


            try
            {
                // Create a set of layers to submit.
                eyeTextures = new EyeTexture[2];

                // 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 = new SharpDX.DXGI.Factory4();

                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.
                swapChain = new SwapChain(factory, device, swapChainDescription);

                // Retrieve the back buffer of the swap chain.
                backBuffer = swapChain.GetBackBuffer <Texture2D>(0);
                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.
                depthBuffer       = new Texture2D(device, depthBufferDescription);
                depthStencilView  = new DepthStencilView(device, depthBuffer);
                depthStencilState = new DepthStencilState(device, depthStencilStateDescription);

                var viewport = new Viewport(0, 0, hmdDesc.Resolution.Width, hmdDesc.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;
                }

                var layerEyeFov = new LayerEyeFov();
                layerEyeFov.Header.Type  = LayerType.EyeFov;
                layerEyeFov.Header.Flags = LayerFlags.None;

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

                    // Retrieve size and position of the texture for the current eye.
                    eyeTexture.FieldOfView           = hmdDesc.DefaultEyeFov[eyeIndex];
                    eyeTexture.TextureSize           = OVR.GetFovTextureSize(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex], 1.0f);
                    eyeTexture.RenderDescription     = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);
                    eyeTexture.HmdToEyeViewOffset    = eyeTexture.RenderDescription.HmdToEyePose.Position;
                    eyeTexture.ViewportSize.Position = new 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 Oculus texture swap chain description.
                    TextureSwapChainDesc textureSwapChainDesc = SharpDXHelpers.CreateTextureSwapChainDescription(eyeTexture.Texture2DDescription);

                    // Create a texture swap chain, which will contain the textures to render to, for the current eye.
                    IntPtr textureSwapChainPtr;

                    result = OVR.CreateTextureSwapChainDX(sessionPtr, device.NativePointer, ref textureSwapChainDesc, out textureSwapChainPtr);
                    WriteErrorDetails(OVR, result, "Failed to create swap chain.");

                    eyeTexture.SwapTextureSet = new TextureSwapChain(OVR, sessionPtr, textureSwapChainPtr);


                    // Retrieve the number of buffers of the created swap chain.
                    int textureSwapChainBufferCount;
                    result = eyeTexture.SwapTextureSet.GetLength(out textureSwapChainBufferCount);
                    WriteErrorDetails(OVR, result, "Failed to retrieve the number of buffers of the created swap chain.");

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

                    // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet.
                    for (int textureIndex = 0; textureIndex < textureSwapChainBufferCount; textureIndex++)
                    {
                        // Retrieve the Direct3D texture contained in the Oculus TextureSwapChainBuffer.
                        IntPtr swapChainTextureComPtr = IntPtr.Zero;
                        result = eyeTexture.SwapTextureSet.GetBufferDX(textureIndex, textureInterfaceId, out swapChainTextureComPtr);
                        WriteErrorDetails(OVR, result, "Failed to retrieve a texture from the created swap chain.");

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

                        // 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.
                    if (eyeIndex == 0)
                    {
                        layerEyeFov.ColorTextureLeft      = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
                        layerEyeFov.ViewportLeft.Position = new Vector2i(0, 0);
                        layerEyeFov.ViewportLeft.Size     = eyeTexture.TextureSize;
                        layerEyeFov.FovLeft = eyeTexture.FieldOfView;
                    }
                    else
                    {
                        layerEyeFov.ColorTextureRight      = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
                        layerEyeFov.ViewportRight.Position = new Vector2i(0, 0);
                        layerEyeFov.ViewportRight.Size     = eyeTexture.TextureSize;
                        layerEyeFov.FovRight = eyeTexture.FieldOfView;
                    }
                }

                MirrorTextureDesc mirrorTextureDescription = new MirrorTextureDesc();
                mirrorTextureDescription.Format    = TextureFormat.R8G8B8A8_UNorm_SRgb;
                mirrorTextureDescription.Width     = form.Width;
                mirrorTextureDescription.Height    = form.Height;
                mirrorTextureDescription.MiscFlags = TextureMiscFlags.None;

                // Create the texture used to display the rendered result on the computer monitor.
                IntPtr mirrorTexturePtr;
                result = OVR.CreateMirrorTextureDX(sessionPtr, device.NativePointer, ref mirrorTextureDescription, out mirrorTexturePtr);
                WriteErrorDetails(OVR, result, "Failed to create mirror texture.");

                mirrorTexture = new MirrorTexture(OVR, sessionPtr, mirrorTexturePtr);


                // Retrieve the Direct3D texture contained in the Oculus MirrorTexture.
                IntPtr mirrorTextureComPtr = IntPtr.Zero;
                result = mirrorTexture.GetBufferDX(textureInterfaceId, out mirrorTextureComPtr);
                WriteErrorDetails(OVR, result, "Failed to retrieve the texture from the created mirror texture buffer.");

                // Create a managed Texture2D, based on the unmanaged texture pointer.
                mirrorTextureD3D = new Texture2D(mirrorTextureComPtr);

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

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

                shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);

                // Specify that each vertex consists of a single vertex position and color.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                };

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

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

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

                // 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, sizeof(float) * 4 * 2, 0));
                immediateContext.VertexShader.SetConstantBuffer(0, contantBuffer);
                immediateContext.VertexShader.Set(vertexShader);
                immediateContext.PixelShader.Set(pixelShader);
                #endregion

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

                #region Render loop
                RenderLoop.Run(form, () =>
                {
                    Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset };
                    double displayMidpoint         = OVR.GetPredictedDisplayTime(sessionPtr, 0);
                    TrackingState trackingState    = OVR.GetTrackingState(sessionPtr, displayMidpoint, true);
                    Posef[] eyePoses = new Posef[2];

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

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

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

                        if (eyeIndex == 0)
                        {
                            layerEyeFov.RenderPoseLeft = eyePoses[0];
                        }
                        else
                        {
                            layerEyeFov.RenderPoseRight = eyePoses[1];
                        }

                        // Update the render description at each frame, as the HmdToEyeOffset can change at runtime.
                        eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);

                        // Retrieve the index of the active texture
                        int textureIndex;
                        result = eyeTexture.SwapTextureSet.GetCurrentIndex(out textureIndex);
                        WriteErrorDetails(OVR, result, "Failed to retrieve texture swap chain current index.");

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

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

                        Matrix world      = Matrix.Scaling(0.1f) * Matrix.RotationX(timeSinceStart / 10f) * Matrix.RotationY(timeSinceStart * 2 / 10f) * Matrix.RotationZ(timeSinceStart * 3 / 10f);
                        Matrix viewMatrix = Matrix.LookAtLH(viewPosition, viewPosition + lookAt, lookUp);

                        Matrix projectionMatrix = OVR.Matrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 100.0f, ProjectionModifier.LeftHanded).ToMatrix();
                        projectionMatrix.Transpose();

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

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

                        // Draw the cube
                        immediateContext.Draw(m_vertices.Length / 2, 0);

                        // Commits any pending changes to the TextureSwapChain, and advances its current index
                        result = eyeTexture.SwapTextureSet.Commit();
                        WriteErrorDetails(OVR, result, "Failed to commit the swap chain texture.");
                    }


                    result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, ref layerEyeFov);
                    WriteErrorDetails(OVR, result, "Failed to submit the frame of the current layers.");

                    immediateContext.CopyResource(mirrorTextureD3D, backBuffer);
                    swapChain.Present(0, PresentFlags.None);
                });
                #endregion
            }
            finally
            {
                if (immediateContext != null)
                {
                    immediateContext.ClearState();
                    immediateContext.Flush();
                }

                // Release all resources
                Dispose(inputLayout);
                Dispose(contantBuffer);
                Dispose(vertexBuffer);
                Dispose(shaderSignature);
                Dispose(pixelShader);
                Dispose(pixelShaderByteCode);
                Dispose(vertexShader);
                Dispose(vertexShaderByteCode);
                Dispose(mirrorTextureD3D);
                Dispose(mirrorTexture);
                Dispose(eyeTextures[0]);
                Dispose(eyeTextures[1]);
                Dispose(immediateContext);
                Dispose(depthStencilState);
                Dispose(depthStencilView);
                Dispose(depthBuffer);
                Dispose(backBufferRenderTargetView);
                Dispose(backBuffer);
                Dispose(swapChain);
                Dispose(factory);

                // 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();
                OVR.Destroy(sessionPtr);
            }
        }
Ejemplo n.º 19
0
        public void Replay()
        {
            foreach (var @event in _frame.Events)
            {
                var args = @event.Arguments;
                switch (@event.OperationType)
                {
                // Device operations.
                case OperationType.DeviceCreateBlendState:
                    _device.CreateBlendState(args.Get <BlendStateDescription>(0));
                    break;

                case OperationType.DeviceCreateBuffer:
                    _device.CreateBuffer(args.Get <BufferDescription>(0), args.Get <byte[]>(1));
                    break;

                case OperationType.DeviceCreateDepthStencilState:
                    _device.CreateDepthStencilState(args.Get <DepthStencilStateDescription>(0));
                    break;

                case OperationType.DeviceCreateDepthStencilView:
                    _device.CreateDepthStencilView(_device.GetDeviceChild <Resource>(args.Get <int>(0)),
                                                   args.Get <DepthStencilViewDescription?>(1));
                    break;

                case OperationType.DeviceCreateGeometryShader:
                    _device.CreateGeometryShader(args.Get <byte[]>(0));
                    break;

                case OperationType.DeviceCreateInputLayout:
                    _device.CreateInputLayout(args.Get <InputElement[]>(0), args.Get <byte[]>(1));
                    break;

                case OperationType.DeviceCreatePixelShader:
                    _device.CreatePixelShader(args.Get <byte[]>(0));
                    break;

                case OperationType.DeviceCreateRasterizerState:
                    _device.CreateRasterizerState(args.Get <RasterizerStateDescription>(0));
                    break;

                case OperationType.DeviceCreateRenderTargetView:
                    _device.CreateRenderTargetView(args.Get <Texture2D>(_device, 0),
                                                   args.Get <RenderTargetViewDescription?>(1));
                    break;

                case OperationType.DeviceCreateSamplerState:
                    _device.CreateSamplerState(args.Get <SamplerStateDescription>(0));
                    break;

                case OperationType.DeviceCreateShaderResourceView:
                    _device.CreateShaderResourceView(args.Get <Resource>(_device, 0),
                                                     args.Get <ShaderResourceViewDescription?>(1));
                    break;

                case OperationType.DeviceCreateSwapChain:
                    _device.CreateSwapChain(
                        args.Get <SwapChainDescription>(0),
                        _swapChainPresenter);
                    break;

                case OperationType.DeviceCreateTexture1D:
                    _device.CreateTexture1D(args.Get <Texture1DDescription>(0));
                    break;

                case OperationType.DeviceCreateTexture2D:
                    _device.CreateTexture2D(args.Get <Texture2DDescription>(0));
                    break;

                case OperationType.DeviceCreateTexture3D:
                    _device.CreateTexture3D(args.Get <Texture3DDescription>(0));
                    break;

                case OperationType.DeviceCreateVertexShader:
                    _device.CreateVertexShader(args.Get <byte[]>(0));
                    break;

                // Device context operations.
                case OperationType.DeviceContextClearDepthStencilView:
                    _deviceContext.ClearDepthStencilView(
                        args.Get <DepthStencilView>(_device, 0),
                        args.Get <DepthStencilClearFlags>(1),
                        args.Get <float>(2),
                        args.Get <byte>(3));
                    break;

                case OperationType.DeviceContextClearRenderTargetView:
                    _deviceContext.ClearRenderTargetView(
                        _device.GetDeviceChild <RenderTargetView>(args.Get <int>(0)),
                        args.Get <Color4>(1));
                    break;

                case OperationType.DeviceContextDraw:
                    _deviceContext.Draw(args.Get <int>(0), args.Get <int>(1));
                    break;

                case OperationType.DeviceContextDrawIndexed:
                    _deviceContext.DrawIndexed(
                        args.Get <int>(0), args.Get <int>(1),
                        args.Get <int>(2));
                    break;

                case OperationType.DeviceContextDrawInstanced:
                    _deviceContext.DrawInstanced(
                        args.Get <int>(0), args.Get <int>(1),
                        args.Get <int>(2), args.Get <int>(3));
                    break;

                case OperationType.DeviceContextGenerateMips:
                    _deviceContext.GenerateMips(args.Get <TextureBase>(_device, 0));
                    break;

                case OperationType.DeviceContextPresent:
                    _deviceContext.Present(args.Get <SwapChain>(_device, 0));
                    break;

                case OperationType.DeviceContextSetBufferData:
                    _deviceContext.SetBufferData(args.Get <Buffer>(_device, 0),
                                                 args.Get <byte[]>(1), args.Get <int>(2));
                    break;

                case OperationType.DeviceContextSetTextureData:
                    _deviceContext.SetTextureData(args.Get <TextureBase>(_device, 0),
                                                  args.Get <int>(1), args.Get <Color4[]>(2));
                    break;

                // Input assembler stage operations.
                case OperationType.InputAssemblerStageSetInputLayout:
                    _deviceContext.InputAssembler.InputLayout = args.Get <InputLayout>(_device, 0);
                    break;

                case OperationType.InputAssemblerStageSetPrimitiveTopology:
                    _deviceContext.InputAssembler.PrimitiveTopology = args.Get <PrimitiveTopology>(0);
                    break;

                case OperationType.InputAssemblerStageSetVertexBuffers:
                    _deviceContext.InputAssembler.SetVertexBuffers(args.Get <int>(0),
                                                                   args.Get <SerializedVertexBufferBinding[]>(1)
                                                                   .Select(x => new VertexBufferBinding
                    {
                        Buffer = _device.GetDeviceChild <Buffer>(x.Buffer),
                        Offset = x.Offset,
                        Stride = x.Stride
                    }).ToArray());
                    break;

                case OperationType.InputAssemblerStageSetIndexBuffer:
                    _deviceContext.InputAssembler.SetIndexBuffer(args.Get <Buffer>(_device, 0),
                                                                 args.Get <Format>(1), args.Get <int>(2));
                    break;

                // Vertex shader stage operations.
                case OperationType.VertexShaderStageSetShader:
                    _deviceContext.VertexShader.Shader = args.Get <VertexShader>(_device, 0);
                    break;

                case OperationType.VertexShaderStageSetConstantBuffers:
                    _deviceContext.VertexShader.SetConstantBuffers(args.Get <int>(0),
                                                                   args.GetArray <Buffer>(_device, 1));
                    break;

                case OperationType.VertexShaderStageSetSamplers:
                    _deviceContext.VertexShader.SetSamplers(args.Get <int>(0),
                                                            args.GetArray <SamplerState>(_device, 1));
                    break;

                case OperationType.VertexShaderStageSetShaderResources:
                    _deviceContext.VertexShader.SetShaderResources(args.Get <int>(0),
                                                                   args.GetArray <ShaderResourceView>(_device, 1));
                    break;

                // Geometry shader stage operations.
                case OperationType.GeometryShaderStageSetShader:
                    _deviceContext.GeometryShader.Shader = args.Get <GeometryShader>(_device, 0);
                    break;

                case OperationType.GeometryShaderStageSetConstantBuffers:
                    _deviceContext.GeometryShader.SetConstantBuffers(args.Get <int>(0),
                                                                     args.GetArray <Buffer>(_device, 1));
                    break;

                case OperationType.GeometryShaderStageSetSamplers:
                    _deviceContext.GeometryShader.SetSamplers(args.Get <int>(0),
                                                              args.GetArray <SamplerState>(_device, 1));
                    break;

                case OperationType.GeometryShaderStageSetShaderResources:
                    _deviceContext.GeometryShader.SetShaderResources(args.Get <int>(0),
                                                                     args.GetArray <ShaderResourceView>(_device, 1));
                    break;

                // Rasterizer stage operations.
                case OperationType.RasterizerStageSetState:
                    _deviceContext.Rasterizer.State = args.Get <RasterizerState>(_device, 0);
                    break;

                case OperationType.RasterizerStageSetViewports:
                    _deviceContext.Rasterizer.SetViewports(args.Get <Viewport[]>(0));
                    break;

                // Pixel shader stage operations.
                case OperationType.PixelShaderStageSetShader:
                    _deviceContext.PixelShader.Shader = args.Get <PixelShader>(_device, 0);
                    break;

                case OperationType.PixelShaderStageSetConstantBuffers:
                    _deviceContext.PixelShader.SetConstantBuffers(args.Get <int>(0),
                                                                  args.GetArray <Buffer>(_device, 1));
                    break;

                case OperationType.PixelShaderStageSetSamplers:
                    _deviceContext.PixelShader.SetSamplers(args.Get <int>(0),
                                                           args.GetArray <SamplerState>(_device, 1));
                    break;

                case OperationType.PixelShaderStageSetShaderResources:
                    _deviceContext.PixelShader.SetShaderResources(args.Get <int>(0),
                                                                  args.GetArray <ShaderResourceView>(_device, 1));
                    break;

                // Output merger stage operations.
                case OperationType.OutputMergerStageSetDepthStencilState:
                    _deviceContext.OutputMerger.DepthStencilState = args.Get <DepthStencilState>(_device, 0);
                    break;

                case OperationType.OutputMergerStageSetDepthStencilReference:
                    _deviceContext.OutputMerger.DepthStencilReference = args.Get <int>(0);
                    break;

                case OperationType.OutputMergerStageSetBlendState:
                    _deviceContext.OutputMerger.BlendState = args.Get <BlendState>(_device, 0);
                    break;

                case OperationType.OutputMergerStageSetBlendFactor:
                    _deviceContext.OutputMerger.BlendFactor = args.Get <Color4>(0);
                    break;

                case OperationType.OutputMergerStageSetBlendSampleMask:
                    _deviceContext.OutputMerger.BlendSampleMask = args.Get <int>(0);
                    break;

                case OperationType.OutputMergerStageSetTargets:
                    _deviceContext.OutputMerger.SetTargets(
                        args.Get <DepthStencilView>(_device, 0),
                        args.GetArray <RenderTargetView>(_device, 1));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (@event == _lastEvent)
                {
                    break;
                }
            }
        }
Ejemplo n.º 20
0
 public virtual void Draw(DeviceContext ctx)
 {
     ctx.Draw(this.VertexCount, 0);
 }
Ejemplo n.º 21
0
        public void Draw(DeviceContext dc, CameraBase camera) {
            var vp = camera.ViewProj;

            // set shader variables
            _fx.SetViewProj(vp);
            _fx.SetGameTime(_gameTime);
            _fx.SetTimeStep(_timeStep);
            _fx.SetEyePosW(EyePosW);
            _fx.SetEmitPosW(EmitPosW);
            _fx.SetEmitDirW(EmitDirW);
            _fx.SetTexArray(_texArraySRV);
            _fx.SetRandomTex(_randomTexSRV);

            dc.InputAssembler.InputLayout = InputLayouts.Particle;
            dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.PointList;

            var stride = Particle.Stride;
            const int offset = 0;
            
            // bind the input vertex buffer for the stream-out technique
            // use the _initVB when _firstRun = true
            dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_firstRun ? _initVB : _drawVB, stride, offset));
            // bind the stream-out vertex buffer
            dc.StreamOutput.SetTargets(new StreamOutputBufferBinding(_streamOutVB, offset));

            // draw the particles using the stream-out technique, which will update the particles positions
            // and output the resulting particles to the stream-out buffer
            var techDesc = _fx.StreamOutTech.Description;
            for (int p = 0; p < techDesc.PassCount; p++) {
                _fx.StreamOutTech.GetPassByIndex(p).Apply(dc);
                if (_firstRun) {
                    dc.Draw(1, 0);
                    _firstRun = false;
                } else {
                    // the _drawVB buffer was populated by the Stream-out technique, so we don't
                    // know how many vertices are contained within it.  Direct3D keeps track of this
                    // internally, however, and we can use DrawAuto to draw everything in the buffer.
                    dc.DrawAuto();
                }
            }
            // Disable stream-out
            dc.StreamOutput.SetTargets(null);

            // ping-pong the stream-out and draw buffers, since we will now want to draw the vertices
            // populated into the buffer that was bound to stream-out
            var temp = _drawVB;
            _drawVB = _streamOutVB;
            _streamOutVB = temp;

            // draw the particles using the draw technique that will transform the points to lines/quads
            dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_drawVB, stride, offset));
            techDesc = _fx.DrawTech.Description;
            for (var p = 0; p < techDesc.PassCount; p++) {
                _fx.DrawTech.GetPassByIndex(p).Apply(dc);
                dc.DrawAuto();
            }
        }
Ejemplo n.º 22
0
 private void ExecuteShaderPass(DeviceContext context)
 {
     context.Rasterizer.State = rasterizerState;
     context.VertexShader.Set(quadVertexShader);
     context.Draw(3, 0);
 }
        public void Render(DeviceContext deviceContext, ShaderResourceView depthImageTextureRV, ShaderResourceView colorImageTextureRV, SharpDX.Direct3D11.Buffer vertexBuffer, RenderTargetView renderTargetView, DepthStencilView depthStencilView, Viewport viewport)
        {
            deviceContext.InputAssembler.InputLayout = vertexInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            deviceContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 16, 0)); // bytes per vertex
            deviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);
            deviceContext.OutputMerger.DepthStencilState = depthStencilState;
            deviceContext.Rasterizer.State = rasterizerState;
            deviceContext.Rasterizer.SetViewport(viewport);
            deviceContext.VertexShader.Set(vertexShader);
            deviceContext.VertexShader.SetShaderResource(0, depthImageTextureRV);
            deviceContext.VertexShader.SetConstantBuffer(0, constantBuffer);
            deviceContext.GeometryShader.Set(geometryShader);
            deviceContext.PixelShader.Set(pixelShader);
            deviceContext.PixelShader.SetShaderResource(0, colorImageTextureRV);
            deviceContext.PixelShader.SetSampler(0, colorSamplerState);
            deviceContext.Draw((Kinect2Calibration.depthImageWidth - 1) * (Kinect2Calibration.depthImageHeight - 1) * 6, 0);

            deviceContext.VertexShader.SetShaderResource(0, null); // to avoid warnings when these are later set as render targets
            deviceContext.PixelShader.SetShaderResource(0, null);
        }
Ejemplo n.º 24
0
 //============================================================
 public void Draw(FDxFaceBuffer faceBuffer)
 {
     _nativeDevice.Draw(0, 0);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Draws the mesh vertices.
 /// </summary>
 /// <param name="device">The device context to use.</param>
 public void Render(DeviceContext context)
 {
     context.InputAssembler.SetVertexBuffers(0, new[] { vertexBuffer });
     context.Draw(vertices.Description.SizeInBytes / vertexBuffer.Stride, 0);
 }
Ejemplo n.º 26
0
        public void RenderBatches(DeviceContext context, List <RenderablePathBatch> batches, Camera camera, ShaderGlobalLights lights)
        {
            UseDynamicVerts = false;
            SetShader(context);
            SetInputLayout(context, VertexType.PC);
            SetSceneVars(context, camera, null, lights);

            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            context.InputAssembler.SetIndexBuffer(null, Format.R16_UInt, 0);
            for (int i = 0; i < batches.Count; i++)
            {
                var pbatch = batches[i];

                if (pbatch.TriangleVertexBuffer == null)
                {
                    continue;
                }
                if (pbatch.TriangleVertexCount == 0)
                {
                    continue;
                }

                context.InputAssembler.SetVertexBuffers(0, pbatch.TriangleVBBinding);
                context.Draw(pbatch.TriangleVertexCount, 0);
            }

            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList;
            context.InputAssembler.SetIndexBuffer(null, Format.R16_UInt, 0);
            for (int i = 0; i < batches.Count; i++)
            {
                var pbatch = batches[i];

                if (pbatch.PathVertexBuffer == null)
                {
                    continue;
                }
                if (pbatch.PathVertexCount == 0)
                {
                    continue;
                }

                context.InputAssembler.SetVertexBuffers(0, pbatch.PathVBBinding);
                context.Draw(pbatch.PathVertexCount, 0);
            }


            context.VertexShader.Set(boxvs);
            context.PixelShader.Set(boxps);

            VSSceneVars.SetVSCBuffer(context, 0);

            foreach (var batch in batches)
            {
                if (batch.NodeBuffer == null)
                {
                    continue;
                }

                context.VertexShader.SetShaderResource(0, batch.NodeBuffer.SRV);

                cube.DrawInstanced(context, batch.Nodes.Length);
            }

            UnbindResources(context);
        }
Ejemplo n.º 27
0
        public void Render(DeviceContext deviceContext, int vertexCount, int vertexOffset, Matrix viewMatrix, Matrix projectionMatrix, int positionIndex, ShaderResourceView pathTexture, double translation, Vector4 mainColor, Vector4 backgroundColor)
        {
            DataStream mappedResource;
            UpdateMatrixBuffer(deviceContext, ConstantMatrixBuffer, Matrix.Identity, viewMatrix, projectionMatrix);

            deviceContext.MapSubresource(ConstantPathDataBuffer, MapMode.WriteDiscard, MapFlags.None, out mappedResource);
            mappedResource.Write(new PathData
            {
                Translation = (float)translation,
                PositionIndex = positionIndex,
                MainColor = mainColor,
                BackgroundColor = backgroundColor
            });
            deviceContext.UnmapSubresource(ConstantPathDataBuffer, 0);

            deviceContext.InputAssembler.InputLayout = Layout;
            deviceContext.VertexShader.Set(VertexShader);
            deviceContext.PixelShader.Set(PixelShader);
            deviceContext.PixelShader.SetSampler(0, SamplerState);
            deviceContext.PixelShader.SetShaderResource(0, pathTexture);
            deviceContext.PixelShader.SetConstantBuffer(1, ConstantPathDataBuffer);
            deviceContext.GeometryShader.Set(GeometryShader);
            deviceContext.GeometryShader.SetConstantBuffer(0, ConstantMatrixBuffer);
            deviceContext.GeometryShader.SetConstantBuffer(1, ConstantPathDataBuffer);
            deviceContext.Draw(vertexCount-vertexOffset ,vertexOffset);
            deviceContext.GeometryShader.Set(null);
        }
Ejemplo n.º 28
0
        static void Main()
        {
            var form = new RenderForm("Triange")
            {
                ClientSize = new System.Drawing.Size(800, 800)
            };

            Device    device;
            SwapChain swapChain;

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

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

            var backBuffer = swapChain.GetBackBuffer <Texture2D>(0);
            var renderView = new RenderTargetView(device, backBuffer);

            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(@".\MiniTri.fx", "VSMain", "vs_5_0");
            var vertexShader         = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(@".\MiniTri.fx", "PSMain", "ps_5_0");
            var pixelShader         = new PixelShader(device, pixelShaderByteCode);

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

            var points = new[]
            {
                new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f)
            };

            var bufDesc = new BufferDescription
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default
            };

            var           vb      = Buffer.Create(device, points, bufDesc);
            DeviceContext context = device.ImmediateContext;

            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vb, 32, 0));

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

            context.Rasterizer.State = new RasterizerState(device, new RasterizerStateDescription
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid
            });
            context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));

            context.OutputMerger.SetTargets(renderView);

            RenderLoop.Run(form, () =>
            {
                context.ClearRenderTargetView(renderView, Color.Black);

                context.Draw(3, 0);

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

            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vb.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
        }
Ejemplo n.º 29
0
        public void RenderQuadSolidOnly( DeviceContext deviceContext, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Vector3 color, Camera camera )
        {
            DataBox databox = deviceContext.MapSubresource( mPositionVertexBuffer,
                                                    0,
                                                    QUAD_NUM_VERTICES *
                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                    MapMode.WriteDiscard,
                                                    SlimDX.Direct3D11.MapFlags.None );

            databox.Data.Write( p1 );
            databox.Data.Write( p4 );
            databox.Data.Write( p2 );
            databox.Data.Write( p3 );

            deviceContext.UnmapSubresource( mPositionVertexBuffer, 0 );

            deviceContext.InputAssembler.InputLayout = mRenderSolidInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            deviceContext.InputAssembler.SetVertexBuffers( POSITION_SLOT,
                                                           new VertexBufferBinding( mPositionVertexBuffer,
                                                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );

            mEffect.GetVariableByName( "gTransform" ).AsMatrix().SetMatrix( camera.GetLookAtMatrix() * camera.GetProjectionMatrix() );
            mEffect.GetVariableByName( "gColor" ).AsVector().Set( color );

            mRenderSolidPass.Apply( deviceContext );
            deviceContext.Draw( QUAD_NUM_VERTICES, 0 );
        }
Ejemplo n.º 30
0
 protected override void OnBatchDraw(DeviceContext context, int batchCount)
 {
     context.Draw(3 * batchCount, 0);
 }
Ejemplo n.º 31
0
        public void RenderSphereWireframeOnly( DeviceContext deviceContext, Vector3 p, float radius, Vector3 color, Camera camera )
        {
            var databox = deviceContext.MapSubresource( mPositionVertexBuffer,
                                                        0,
                                                        NUM_VERTICES *
                                                        POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                        POSITION_NUM_BYTES_PER_COMPONENT,
                                                        MapMode.WriteDiscard,
                                                        SlimDX.Direct3D11.MapFlags.None );

            var currentPoint = new Vector3();
            var furtherSouthPoint = new Vector3();
            var numVertices = 0;

            // northSouthTheta traces from north pole to south pole
            float northSouthTheta = (float)Math.PI / 2;

            for ( int i = 0; i <= NUM_LATITUDE_LINES; i++ )
            {
                float currentLatitudeRadius = (float)Math.Cos( northSouthTheta ) * radius;
                float nextLatitudeRadius = (float)Math.Cos( northSouthTheta + LATITUDE_STEP ) * radius;

                // eastWestTheta traces around each latitude line
                float eastWestTheta = 0;

                for ( int j = 0; j <= NUM_LONGITUDE_LINES; j++ )
                {
                    currentPoint.X = p.X + ( (float)Math.Cos( eastWestTheta ) * currentLatitudeRadius );
                    currentPoint.Y = p.Y + ( (float)Math.Sin( northSouthTheta ) * radius );
                    currentPoint.Z = p.Z + ( (float)Math.Sin( eastWestTheta ) * currentLatitudeRadius );

                    databox.Data.Write( currentPoint );
                    numVertices++;

                    furtherSouthPoint.X = p.X + ( (float)Math.Cos( eastWestTheta ) * nextLatitudeRadius );
                    furtherSouthPoint.Y = p.Y + ( (float)Math.Sin( northSouthTheta + LATITUDE_STEP ) * radius );
                    furtherSouthPoint.Z = p.Z + ( (float)Math.Sin( eastWestTheta ) * nextLatitudeRadius );

                    databox.Data.Write( furtherSouthPoint );
                    numVertices++;

                    eastWestTheta += LONGITUDE_STEP;
                }

                northSouthTheta += LATITUDE_STEP;
            }

            deviceContext.UnmapSubresource( mPositionVertexBuffer, 0 );

            deviceContext.InputAssembler.InputLayout = mRenderWireframeInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            deviceContext.InputAssembler.SetVertexBuffers( POSITION_SLOT,
                                                           new VertexBufferBinding( mPositionVertexBuffer,
                                                                                    POSITION_NUM_COMPONENTS_PER_VERTEX *
                                                                                    POSITION_NUM_BYTES_PER_COMPONENT,
                                                                                    0 ) );

            mEffect.GetVariableByName( "gTransform" ).AsMatrix().SetMatrix( camera.GetLookAtMatrix() * camera.GetProjectionMatrix() );
            mEffect.GetVariableByName( "gColor" ).AsVector().Set( color );

            mRenderWireframePass.Apply( deviceContext );
            deviceContext.Draw( numVertices, 0 );
        }
Ejemplo n.º 32
0
        protected override void DoRender()
        {
            DeviceContext context = this.DeviceManager.Direct3DContext;

            //// Context.InputAssembler.InputLayout = vertexLayout;
            //// Context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleStrip;
            //// Context.InputAssembler.SetVertexBuffers(0, vertexBinding);

            //// Retrieve the existing shader and IA settings
            //// using (var OldVertexLayout = Context.InputAssembler.InputLayout)
            //// using (var OldSampler = Context.PixelShader.GetSamplers(0, 1).FirstOrDefault())
            //// using (var OldPixelShader = Context.PixelShader.Get())
            //// using (var OldVertexShader = Context.VertexShader.Get())
            //// using (var OldRenderTarget = Context.OutputMerger.GetRenderTargets(1).FirstOrDefault())
            {
                context.ClearRenderTargetView(this.RenderTargetView, new RawColor4());

                // Set sampler
                RawViewportF[] viewportF = { new RawViewportF() }; // (0, 0, RenderTarget.Description.Width, RenderTarget.Description.Height, 0, 1)
                context.Rasterizer.SetViewports(viewportF);
                context.PixelShader.SetSampler(0, this.UseLinearSampling ? this.LinearSampleState : this.PointSamplerState);

                // Set shader resource
                //// Boolean isMultisampledSRV = false;
                if (this.ShaderResource != null && !this.ShaderResource.IsDisposed)
                {
                    context.PixelShader.SetShaderResource(0, this.ShaderResource);

                    //// if (this.ShaderResource.Description.Dimension == SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled)
                    //// {
                    ////     isMultisampledSRV = true;
                    //// }
                }

                // Set pixel shader
                //// if (isMultisampledSRV)
                ////     context.PixelShader.Set(pixelShaderMS);
                //// else
                context.PixelShader.Set(this.PixelShader);

                // Set vertex shader
                context.VertexShader.Set(this.VertexShader);

                // Update vertex layout to use
                context.InputAssembler.InputLayout = null;

                // Tell the IA we are using a triangle strip
                context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleStrip;

                // No vertices to pass (note: null as we will use SV_VertexId)
                //// context.InputAssembler.SetVertexBuffers(0, vertexBuffer);

                // Set the render target
                context.OutputMerger.SetTargets(RenderTargetView);

                // Draw the 4 vertices that make up the triangle strip
                context.Draw(4, 0);

                // Remove the render target from the pipeline so that we can read from it if necessary
                context.OutputMerger.SetTargets((RenderTargetView)null);

                // Restore previous shader and IA settings
                //// context.PixelShader.SetSampler(0, oldSampler);
                //// context.PixelShader.Set(oldPixelShader);
                //// context.VertexShader.Set(oldVertexShader);
                //// context.InputAssembler.InputLayout = oldVertexLayout;
                //// context.OutputMerger.SetTargets(oldRenderTarget);
            }
        }
Ejemplo n.º 33
0
 public void RenderNotIndexed(DeviceContext deviceContext, int vertexCount, Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix)
 {
     UpdateMatrixBuffer(deviceContext, ConstantMatrixBuffer, worldMatrix, viewMatrix, projectionMatrix);
     deviceContext.VertexShader.SetConstantBuffer(0, ConstantMatrixBuffer);
     deviceContext.InputAssembler.InputLayout = Layout;
     deviceContext.VertexShader.Set(VertexShader);
     deviceContext.PixelShader.Set(PixelShader);
     deviceContext.Draw(vertexCount,0);
 }
Ejemplo n.º 34
0
 public void Draw(int vertexOffset, int vertexCount)
 {
     Bind();
     DeviceContext.Draw(_device.ContextPtr, (uint)vertexCount, (uint)vertexOffset);
 }
Ejemplo n.º 35
0
        public void DrawPositionWidget(DeviceContext context, Camera cam, Vector3 camrel, Quaternion ori, float size, WidgetAxis selax)
        {
            SetShader(context);
            SetInputLayout(context, VertexType.Default);

            SceneVars.Vars.Mode   = 0; //vertices mode
            SceneVars.Vars.CamRel = camrel;
            SetSceneVars(context, cam, null, null);

            Vector3 xdir     = ori.Multiply(Vector3.UnitX);
            Vector3 ydir     = ori.Multiply(Vector3.UnitY);
            Vector3 zdir     = ori.Multiply(Vector3.UnitZ);
            Color4  xcolour  = new Color4(1.0f, 0.0f, 0.0f, 1.0f);
            Color4  ycolour  = new Color4(0.0f, 1.0f, 0.0f, 1.0f);
            Color4  zcolour  = new Color4(0.0f, 0.0f, 1.0f, 1.0f);
            Color4  selaxcol = new Color4(1.0f, 1.0f, 0.0f, 1.0f);
            Color4  selplcol = new Color4(1.0f, 1.0f, 0.0f, 0.5f);

            Vector3[]    axes        = { xdir, ydir, zdir };
            Vector3[]    sides1      = { ydir, zdir, xdir };
            Vector3[]    sides2      = { zdir, xdir, ydir };
            WidgetAxis[] sideax1     = { WidgetAxis.Y, WidgetAxis.Z, WidgetAxis.X };
            WidgetAxis[] sideax2     = { WidgetAxis.Z, WidgetAxis.X, WidgetAxis.Y };
            Color4[]     colours     = { xcolour, ycolour, zcolour };
            Color4[]     coloursdark = { xcolour * 0.5f, ycolour * 0.5f, zcolour * 0.5f };
            for (int i = 0; i < 3; i++)
            {
                coloursdark[i].Alpha = 1.0f;
            }

            float linestart  = 0.2f * size;
            float lineend    = 1.0f * size;
            float sideval    = 0.4f * size;
            float arrowstart = 1.0f * size;
            float arrowend   = 1.33f * size;
            float arrowrad   = 0.06f * size;

            float hexx = 0.5f;
            float hexy = 0.86602540378443864676372317075294f; //sqrt(0.75)

            Vector2[] arrowv =
            {
                new Vector2(-1,        0) * arrowrad,
                new Vector2(-hexx, hexy) * arrowrad,
                new Vector2(hexx,  hexy) * arrowrad,
                new Vector2(1,         0) * arrowrad,
                new Vector2(hexx,  -hexy) * arrowrad,
                new Vector2(-hexx, -hexy) * arrowrad,
                new Vector2(-1, 0) * arrowrad
            };



            //draw lines...
            Vertices.Clear();

            for (int i = 0; i < 3; i++)
            {
                WidgetAxis sa    = (WidgetAxis)(1 << i);
                bool       axsel = ((selax & sa) > 0);
                Color4     axcol = axsel ? selaxcol : colours[i];

                //axis side square lines
                Vector3 ax  = axes[i] * sideval;
                Vector3 s1  = sides1[i] * sideval;
                Vector3 s2  = sides2[i] * sideval;
                Color4  sc1 = (axsel && ((selax & sideax1[i]) > 0)) ? selaxcol : colours[i];
                Color4  sc2 = (axsel && ((selax & sideax2[i]) > 0)) ? selaxcol : colours[i];
                Vertices.Add(new WidgetShaderVertex(ax, sc1));
                Vertices.Add(new WidgetShaderVertex(ax + s1, sc1));
                Vertices.Add(new WidgetShaderVertex(ax, sc2));
                Vertices.Add(new WidgetShaderVertex(ax + s2, sc2));

                //main axis lines - draw after side lines to be on top
                Vertices.Add(new WidgetShaderVertex(axes[i] * linestart, axcol));
                Vertices.Add(new WidgetShaderVertex(axes[i] * lineend, axcol));
            }

            Vertices.Update(context);
            Vertices.SetVSResource(context, 0);

            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList;
            context.Draw(Vertices.CurrentCount, 0);



            //draw triangles...
            Vertices.Clear();

            for (int i = 0; i < 3; i++)
            {
                //axis arrows - kind of inefficient, but meh
                Vector3 aend   = axes[i] * arrowend;
                Vector3 astart = axes[i] * arrowstart;
                for (int n = 0; n < 6; n++)
                {
                    Vector2 a1  = arrowv[n];
                    Vector2 a2  = arrowv[n + 1];
                    Vector3 ap1 = astart + sides1[i] * a1.Y + sides2[i] * a1.X;
                    Vector3 ap2 = astart + sides1[i] * a2.Y + sides2[i] * a2.X;
                    Vertices.Add(new WidgetShaderVertex(aend, colours[i]));
                    Vertices.Add(new WidgetShaderVertex(ap1, colours[i]));
                    Vertices.Add(new WidgetShaderVertex(ap2, colours[i]));
                    Vertices.Add(new WidgetShaderVertex(astart, coloursdark[i]));
                    Vertices.Add(new WidgetShaderVertex(ap2, coloursdark[i]));
                    Vertices.Add(new WidgetShaderVertex(ap1, coloursdark[i]));
                }

                //selection planes
                WidgetAxis sa = (WidgetAxis)(1 << i);
                if (((selax & sa) > 0))
                {
                    Vector3 ax = axes[i] * sideval;
                    for (int n = i + 1; n < 3; n++)
                    {
                        WidgetAxis tsa = (WidgetAxis)(1 << n);
                        if (((selax & tsa) > 0))
                        {
                            Vector3 tax = axes[n] * sideval;
                            Vertices.Add(new WidgetShaderVertex(Vector3.Zero, selplcol));
                            Vertices.Add(new WidgetShaderVertex(ax, selplcol));
                            Vertices.Add(new WidgetShaderVertex(tax, selplcol));
                            Vertices.Add(new WidgetShaderVertex(tax + ax, selplcol));
                            Vertices.Add(new WidgetShaderVertex(tax, selplcol));
                            Vertices.Add(new WidgetShaderVertex(ax, selplcol));
                        }
                    }
                }
            }

            Vertices.Update(context);
            Vertices.SetVSResource(context, 0);

            context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            context.Draw(Vertices.CurrentCount, 0);

            UnbindResources(context);
        }
Ejemplo n.º 36
0
        public void Render(DeviceContext deviceContext, MeshDeviceResources meshDeviceResources, PointLight pointLight, RenderTargetView renderTargetView, DepthStencilView depthStencilView, Viewport viewport)
        {
            deviceContext.InputAssembler.InputLayout = vertexInputLayout;
            deviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            deviceContext.InputAssembler.SetVertexBuffers(0, meshDeviceResources.vertexBufferBinding);
            deviceContext.Rasterizer.State = rasterizerState;
            deviceContext.Rasterizer.SetViewport(viewport);
            deviceContext.VertexShader.Set(meshVS);
            deviceContext.VertexShader.SetConstantBuffer(0, vertexShaderConstantBuffer);
            deviceContext.GeometryShader.Set(null);
            deviceContext.PixelShader.SetSampler(0, colorSamplerState);
            deviceContext.PixelShader.SetConstantBuffer(0, pixelShaderConstantBuffer);
            deviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);
            deviceContext.OutputMerger.DepthStencilState = depthStencilState;

            foreach (var subset in meshDeviceResources.mesh.subsets)
            //var subset = meshDeviceResources.mesh.subsets[meshDeviceResources.mesh.subsets.Count - 2];
            {
                if (subset.material.textureFilename != null)
                {
                    deviceContext.PixelShader.Set(meshWithTexturePS);
                    deviceContext.PixelShader.SetShaderResource(0, meshDeviceResources.textureRVs[subset]);
                }
                else
                    deviceContext.PixelShader.Set(meshPS);

                SetPixelShaderConstants(deviceContext, subset.material, pointLight);
                deviceContext.Draw(subset.length, subset.start);
            }
        }
Ejemplo n.º 37
0
        public void Reduce(DeviceContext context, ShaderResourceView from)
        {
            PixHelper.BeginEvent(Color.Green, "MinMax {0}x{0}", 1 << ReduceFactor);

            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, sizeof(float) * 2, 0));
            context.VertexShader.Set(vertexShader);

            var viewport = new Viewport(0, 0, Size.Width, Size.Height);

            int maxLevels = texture2DMinMaxResourceView.Length;

            int lastSampleLevel = maxLevels % ReduceFactor;

            int levels = maxLevels / ReduceFactor;

            passCount = levels + (lastSampleLevel > 0 ? 1 : 0);
            for (int i = 0; i < passCount; i++)
            {
                int shaderIndex = ReduceFactor;
                int levelIndex = (i+1) * ReduceFactor - 1;
                viewport.Width = Math.Max(((int)Size.Width) / (1 << (levelIndex + 1)), 1);
                viewport.Height = Math.Max(((int)Size.Height) / (1 << (levelIndex + 1)), 1);

                PixHelper.BeginEvent(Color.GreenYellow, "MinMax Level {0} Size: ({1},{2})", levelIndex, viewport.Width, viewport.Height);

                // Special case when last level is different from ReduceFactor size
                if (i == levels)
                {
                    levelIndex = maxLevels - 1;
                    shaderIndex = lastSampleLevel;
                    viewport.Width = 1;
                    viewport.Height = 1;
                }

                context.PixelShader.Set(i == 0 ? pixelShaderMinMaxBegin[shaderIndex - 1] : pixelShaderMinMax[shaderIndex - 1]);
                context.PixelShader.SetSampler(0, sampler);
                context.PixelShader.SetShaderResource(0, from);
                context.Rasterizer.SetViewport(viewport);
                //context.ClearRenderTargetView(texture2DMinMaxRenderView[levelIndex], Colors.Black);
                context.OutputMerger.SetTargets(texture2DMinMaxRenderView[levelIndex]);
                context.Draw(4, 0);
                context.PixelShader.SetShaderResource(0, null);
                context.OutputMerger.ResetTargets();
                from = texture2DMinMaxResourceView[levelIndex];

                PixHelper.EndEvent();
            }
            PixHelper.EndEvent();
        }
Ejemplo n.º 38
0
        private void DrawCameraFrustum()
        {
            var view = _viewCam.View;

            var fovX = _viewCam.FovX;
            var fovY = _viewCam.FovY;
            // world-space camera position
            var org = _viewCam.Position;

            // vectors pointed towards the corners of the near plane of the view frustum
            var dirs = new[] {
                new Vector3(fovX, fovY, 1.0f),
                new Vector3(-fovX, fovY, 1.0f),
                new Vector3(-fovX, -fovY, 1.0f),
                new Vector3(fovX, -fovY, 1.0f)
            };
            var points = new Vector3[4];

            // view-to-world transform
            var invView = Matrix.Invert(view);

            // XZ plane
            var groundPlane = new Plane(new Vector3(), new Vector3(0, 1, 0));

            var ok = true;

            for (var i = 0; i < 4 && ok; i++)
            {
                // transform the view-space vector into world-space
                dirs[i] = Vector3.Normalize(Vector3.TransformNormal(dirs[i], invView));
                // extend the near-plane vectors into very far away points
                dirs[i] *= 100000.0f;

                Vector3 hit;
                // check if the ray between the camera origin and the far point intersects the ground plane
                if (!Plane.Intersects(groundPlane, org, dirs[i], out hit))
                {
                    ok = false;
                }
                // make sure that the intersection is on the positive side of the frustum near plane
                var n = _viewCam.FrustumPlanes[Frustum.Near];
                var d = n.Normal.X * hit.X + n.Normal.Y * hit.Y + n.Normal.Z * hit.Z + n.D;
                if (d < 0.0f)
                {
                    ok = false;
                    // if we're here, the ray was pointing away from the ground
                    // so we will instead intersect the ray with the terrain boundary planes
                    foreach (var edgePlane in _edgePlanes)
                    {
                        if (!Plane.Intersects(edgePlane, org, dirs[i], out hit))
                        {
                            continue;
                        }
                        d = n.Normal.X * hit.X + n.Normal.Y * hit.Y + n.Normal.Z * hit.Z + n.D;
                        if (!(d >= 0.0f))
                        {
                            continue;
                        }
                        // bump out the intersection point, so that if we're looking into the corners, the
                        // frustum doesn't show that we shouldn't be able to see terrain that we can see
                        hit *= 2;
                        ok   = true;
                        break;
                    }
                }
                points[i] = new Vector3(Math.Min(Math.Max(hit.X, -float.MaxValue), float.MaxValue), 0, Math.Min(Math.Max(hit.Z, -float.MaxValue), float.MaxValue));
            }

            if (!ok)
            {
                return;
            }

            // update the frustum vertex buffer
            var buf = _dc.MapSubresource(_frustumVB, MapMode.WriteDiscard, MapFlags.None);

            buf.Data.Write(new VertexPC(points[0], Color.White));
            buf.Data.Write(new VertexPC(points[1], Color.White));
            buf.Data.Write(new VertexPC(points[2], Color.White));
            buf.Data.Write(new VertexPC(points[3], Color.White));
            // include the first point twice, to complete the quad when we render as a linestrip
            buf.Data.Write(new VertexPC(points[0], Color.White));

            _dc.UnmapSubresource(_frustumVB, 0);

            _dc.InputAssembler.InputLayout       = InputLayouts.PosColor;
            _dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineStrip;
            _dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_frustumVB, VertexPC.Stride, 0));
            // draw the frustum with a basic position-color shader
            for (var i = 0; i < Effects.ColorFX.ColorTech.Description.PassCount; i++)
            {
                Effects.ColorFX.SetWorldViewProj(_orthoCamera.ViewProj);
                Effects.ColorFX.ColorTech.GetPassByIndex(i).Apply(_dc);
                _dc.Draw(5, 0);
            }
        }