Exemplo n.º 1
0
        /// <summary>
        /// Maps buffers, sets data and unmaps it.
        /// </summary>
        /// <param name="offset">The element offset.</param>
        public unsafe void SetData <T>([NotNull] T[] data, ulong offset) where T : struct
        {
            lock (syncRoot)
            {
                AssertNotDisposed();

                // Validate T.
                ulong structSize = (ulong)Marshal.SizeOf(typeof(T));

                if (structSize != format.ByteSize)
                {
                    throw new ArgumentException("The T is not compatible with vertex format.");
                }

                // We first map it, it may throw (if it throws, it is automatically unlocked).
                byte[] dstBuffer = TypelessBuffer.Map(MapOptions.Write,
                                                      this.offset + offset * format.ByteSize, (ulong)data.LongLength * format.ByteSize);



                try
                {
                    fixed(byte *p = dstBuffer)
                    {
                        Common.Memcpy(data, p, (ulong)dstBuffer.LongLength);
                    }
                }
                finally
                {
                    // Must unmap.
                    TypelessBuffer.UnMap();
                }
            }
        }
Exemplo n.º 2
0
        void Dispose(bool fin)
        {
            if (isDisposed)
            {
                return;
            }

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

            isDisposed = true;

            if (!fin)
            {
                typelessBuffer.Release();
            }

            // We leave buffer to be garbage collected.
            if (!fin)
            {
                typelessBuffer = null;
                GC.SuppressFinalize(this);
            }
        }
Exemplo n.º 3
0
        internal IndexBufferView(TypelessBuffer buffer, ulong offset, IndexFormat format)
        {
            this.typelessBuffer = buffer;
            this.offset         = offset;
            this.format         = format;

            buffer.AddRef();
        }
Exemplo n.º 4
0
        public void DAGUsageCases2()
        {
            // We first initialize our shader.
            ShaderCode code = new ShaderCode(BindingStage.VertexShader);
            {
                // We write a simple Tranform code:
                code.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx3);
                Pin positon = code.InputOperation.PinAsOutput(PinComponent.Position);

                // We first need to expand our position to float4 (adding 1 at the end).
                ExpandOperation expand = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW);
                expand.BindInputs(positon);
                Pin expPosition = expand.Outputs[0];

                // We now create constant transform matrix.
                ConstantOperation mvpConstant = code.CreateConstant("MVP", PinFormat.Float4x4);
                Pin MVP = mvpConstant.Outputs[0];

                // We multiply matrix and pin.
                MultiplyOperation mul = new MultiplyOperation();
                mul.BindInputs(MVP, expPosition);
                Pin transPosition = mul.Outputs[0];

                // We just bind transformed position to output.
                code.OutputOperation.AddComponentAndLink(PinComponent.Position, transPosition);
            }

            // We create constant buffer manually.
            ConstantBufferLayoutBuilder builder = new ConstantBufferLayoutBuilder();

            builder.AppendElement("MVP", PinFormat.Float4x4, Pin.NotArray);
            ConstantBufferLayout layout = builder.CreateLayout();

            // We now fill the data.
            FixedShaderParameters parameters = code.FixedParameters;

            parameters.AppendLayout(layout);
            if (!parameters.IsDefined)
            {
                throw new Exception();
            }

            GraphicsDevice device = InitializeDevice();

            // We have all parameters defined, compile the shader.
            VShader shader = code.Compile(device, parameters) as VShader;

            // Shader expects data in constant buffers.
            TypelessBuffer     buffer         = new TypelessBuffer(Usage.Default, BufferUsage.ConstantBuffer, CPUAccess.Write, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 4);
            ConstantBufferView constantBuffer = buffer.CreateConstantBuffer(layout);

            // We fill the buffer.
            constantBuffer.Map(MapOptions.Write);
            constantBuffer.SetConstant("MVP", Math.Matrix.Matrix4x4f.Identity);
            constantBuffer.UnMap();
        }
Exemplo n.º 5
0
        /// <summary>
        /// A helper to create a vertex buffer.
        /// </summary>
        /// <returns></returns>
        public static VertexBufferView Create(GraphicsDevice device, VertexFormat format, Usage usage,
                                              CPUAccess access, GraphicsLocality locality, ulong elementCount)
        {
            TypelessBuffer buffer = new TypelessBuffer(usage, BufferUsage.VertexBuffer, access, locality,
                                                       format.ByteSize * elementCount);

            buffer.DisposeOnViewDispose = true;

            return(buffer.CreateVertexBuffer(format));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates a constant buffer layout.
        /// </summary>
        /// <returns></returns>
        public static ConstantBufferView Create(GraphicsDevice device, Usage usage, CPUAccess access, GraphicsLocality locality,
                                                ConstantBufferLayout layout)
        {
            TypelessBuffer buffer = new TypelessBuffer(device, usage, BufferUsage.ConstantBuffer, access,
                                                       locality, layout.MinimumBufferSizeInBytes);

            buffer.DisposeOnViewDispose = true;

            return(buffer.CreateConstantBuffer(layout));
        }
Exemplo n.º 7
0
        internal VertexBufferView(TypelessBuffer buffer, VertexFormat format, ulong offset, uint stride,
                                  UpdateFrequency updateFrequency, uint updateFrequencyCount)
        {
            this.offset               = offset;
            this.format               = format;
            this.typelessBuffer       = buffer;
            this.updateFrequencyCount = updateFrequencyCount;
            this.updateFrequency      = updateFrequency;
            this.stride               = stride;

            // Add reference to buffer.
            buffer.AddRef();
        }
Exemplo n.º 8
0
        void Dispose(bool fin)
        {
            if (!disposed)
            {
                if (view != null)
                {
                    view.Dispose();
                    view = null;
                }
                buffer = null;

                if (!fin)
                {
                    GC.SuppressFinalize(this);
                }
            }
        }
Exemplo n.º 9
0
        public void Dispose(bool finalizer)
        {
            if (!isDisposed)
            {
                if (view != null)
                {
                    view.Dispose();
                    view       = null;
                    isDisposed = true;
                }

                typelessBuffer.Release();

                if (!finalizer)
                {
                    GC.SuppressFinalize(this);
                    typelessBuffer = null;
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Reads data to buffer.
        /// </summary>
        public unsafe T[] GetData <T>(ulong offset, ulong count) where T : struct
        {
            lock (syncRoot)
            {
                AssertNotDisposed();

                // Validate T.
                ulong structSize = (ulong)Marshal.SizeOf(typeof(T));

                if (structSize != format.ByteSize)
                {
                    throw new ArgumentException("The T is not compatible with vertex format.");
                }

                T[] data = new T[count];

                // We first map it, it may throw (if it throws, it is automatically unlocked).
                byte[] srcBuffer = TypelessBuffer.Map(MapOptions.Read,
                                                      this.offset + offset * format.ByteSize, count * format.ByteSize);



                try
                {
                    fixed(byte *p = srcBuffer)
                    {
                        Common.Memcpy(p, data, (ulong)srcBuffer.LongLength);
                    }
                }
                finally
                {
                    // Must unmap.
                    TypelessBuffer.UnMap();
                }

                return(data);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates dynamic buffers that are are update (usually each frame).
        /// </summary>
        /// <param name="device"></param>
        /// <param name="vertexFormat"></param>
        /// <param name="indexFormat"></param>
        /// <param name="maxVertices"></param>
        /// <param name="maxIndices"></param>
        /// <returns></returns>
        public static GeometryBatch CreateBatch(VertexFormat vertexFormat, IndexFormat indexFormat,
                                                ulong maxVertices, ulong maxIndices, uint maxCyclicBuffers)
        {
            if (maxCyclicBuffers == 0)
            {
                maxCyclicBuffers = 1;
            }

            VertexBufferView[] vbufferView = new VertexBufferView[maxCyclicBuffers];
            IndexBufferView[]  ibufferView = new IndexBufferView[maxCyclicBuffers];

            for (uint i = 0; i < maxCyclicBuffers; i++)
            {
                // We create vertex buffer.
                TypelessBuffer vbuffer = new TypelessBuffer(Usage.Dynamic, BufferUsage.VertexBuffer, CPUAccess.Write,
                                                            GraphicsLocality.DeviceOrSystemMemory, vertexFormat.ByteSize * maxVertices);
                vbuffer.DisposeOnViewDispose = true;

                // We create view.
                vbufferView[i] = vbuffer.CreateVertexBuffer(vertexFormat);

                // We may also create index buffer.
                if (maxIndices > 0)
                {
                    TypelessBuffer ibuffer = new TypelessBuffer(Usage.Dynamic, BufferUsage.IndexBuffer, CPUAccess.Write,
                                                                GraphicsLocality.DeviceOrSystemMemory, indexFormat.ByteSize * maxIndices);
                    ibuffer.DisposeOnViewDispose = true;

                    // We create view.
                    ibufferView[i] = ibuffer.CreateIndexBuffer(indexFormat);
                }
            }

            // We create geometry.
            GeometryBatch geometry = new GeometryBatch(vbufferView, ibufferView);

            return(geometry);
        }
Exemplo n.º 12
0
        public unsafe void DAGUsageCases()
        {
            // We first initialize our shader.
            ShaderCode code = new ShaderCode(BindingStage.VertexShader);

            {
                // We write a simple Tranform code:
                code.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx3);
                Pin positon = code.InputOperation.PinAsOutput(PinComponent.Position);

                // We first need to expand our position to float4 (adding 1 at the end).
                ExpandOperation expand = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW);
                expand.BindInputs(positon);
                Pin expPosition = expand.Outputs[0];

                // We now create constant transform matrix.
                ConstantOperation mvpConstant = code.CreateConstant("MVP", PinFormat.Float4x4);
                Pin MVP = mvpConstant.Outputs[0];

                // We multiply matrix and pin.
                MultiplyOperation mul = new MultiplyOperation();
                mul.BindInputs(MVP, expPosition);
                Pin transPosition = mul.Outputs[0];

                // We just bind transformed position to output.
                code.OutputOperation.AddComponentAndLink(PinComponent.Position, transPosition);
            }

            // Immutate it.
            code.Immutable = true;


            // We create constant buffer manually.
            ConstantBufferLayoutBuilder builder = new ConstantBufferLayoutBuilder();

            builder.AppendElement("MVP", PinFormat.Float4x4, Pin.NotArray);
            ConstantBufferLayout layout = builder.CreateLayout();

            // We now fill the data.
            FixedShaderParameters parameters = code.FixedParameters;

            parameters.AppendLayout(layout);
            if (!parameters.IsDefined)
            {
                throw new Exception();
            }



            using (GraphicsDevice device = InitializeDevice())
            {
                // We create shaders.

                // We have all parameters defined, compile the shader.
                VShader shader = code.Compile(device, parameters) as VShader;

                // Shader expects data in constant buffers.
                TypelessBuffer     tbuffer        = new TypelessBuffer(Usage.Dynamic, BufferUsage.ConstantBuffer, CPUAccess.Write, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 4);
                ConstantBufferView constantBuffer = tbuffer.CreateConstantBuffer(layout);

                // We fill the buffer.
                constantBuffer.Map(MapOptions.Write);
                constantBuffer.SetConstant("MVP", new Math.Matrix.Matrix4x4f(1, 0, 0, 0,
                                                                             0, 1, 0, 0,
                                                                             0, 0, 1, 0,
                                                                             -0.5f, -0.5f, 0, 1));
                constantBuffer.UnMap();

                PShader pshader;
                VShader vshader = shader;
                using (ShaderCompiler compiler = device.CreateShaderCompiler())
                {
                    // And pixel shader.
                    compiler.Begin(BindingStage.PixelShader);
                    ShaderCompiler.Operand colour = compiler.CreateFixed(PinFormat.Floatx4, Pin.NotArray, new Vector4f(1, 0, 0, 1));
                    compiler.Output(colour, PinComponent.RenderTarget0);
                    pshader = compiler.End(null) as PShader;
                }

                // We create triangles.
                Geometry       geometry = new Geometry();
                TypelessBuffer buffer   = new TypelessBuffer(Usage.Static,
                                                             BufferUsage.VertexBuffer, CPUAccess.None, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 3);

                byte[] d = buffer.Map(MapOptions.Read);
                fixed(byte *p = d)
                {
                    float *data = (float *)p;

                    // Vertex 0:
                    data[0] = -0.5f; data[1] = -0.5f; data[2] = 0.0f; data[3] = 1.0f;

                    // Vertex 1:
                    data[4] = 0.5f; data[5] = -0.5f; data[6] = 0.0f; data[7] = 1.0f;

                    // Vertex 2:
                    data[8] = 0.0f; data[9] = 0.5f; data[10] = 0.0f; data[11] = 1.0f;
                }

                buffer.UnMap();


                // Create vertex buffer and view.
                VertexBufferView vbuffer = buffer.CreateVertexBuffer(VertexFormat.Parse("P.Fx4"));

                // We construct geometry.
                geometry[0]       = vbuffer;
                geometry.Topology = Topology.Triangle;

                // Blend state.
                BlendState blendState = new BlendState();
                blendState[0] = false;

                blendState = StateManager.Intern(blendState);

                RasterizationState rastState = new RasterizationState();
                rastState.CullMode = CullMode.None;
                rastState.FillMode = FillMode.Solid;

                rastState = StateManager.Intern(rastState);

                DepthStencilState depthState = new DepthStencilState();
                depthState.DepthTestEnabled  = false;
                depthState.DepthWriteEnabled = false;

                depthState = StateManager.Intern(depthState);

                // Enter rendering loop.
                bool isClosed = false;
                window.Closed += delegate(Window w)
                {
                    isClosed = true;
                };

                for (uint i = 0; i < 1000; i++)
                {
                    window.DoEvents();

                    if (!isClosed)
                    {
                        SwapChain chain = device.SwapChain;

                        device.Enter();
                        try
                        {
                            // We just clear.
                            device.Clear(chain, Colour.Black);

                            // Set blend/rast.
                            device.SetBlendState(blendState, Colour.White, 0xFFFFFFFF);
                            device.RasterizationState = rastState;
                            device.SetDepthStencilState(depthState, 0);

                            // Sets states.
                            device.SetVertexShader(vshader, geometry, null, null, new ConstantBufferView[] { constantBuffer });
                            device.SetPixelShader(pshader, null, null, null, new RenderTargetView[] { chain }, null);

                            device.Viewport = new Region2i(0, 0, (int)chain.Width, (int)chain.Height);

                            // Render.
                            device.Draw(0, 3);
                        }
                        finally
                        {
                            device.Exit();
                        }

                        chain.Present();
                        //Thread.Sleep(10);

                        Console.WriteLine(device.DevicePerformance.CurrentFPS);
                    }
                }


                // Dispose all.
                vshader.Dispose();
                pshader.Dispose();
                geometry.Dispose();
                vbuffer.Dispose();
                buffer.Dispose();
            }
        }
Exemplo n.º 13
0
        public unsafe void TriangleTest()
        {
            using (GraphicsDevice device = InitializeDevice())
            {
                // We create shaders.
                VShader vshader;
                PShader pshader;
                using (ShaderCompiler compiler = device.CreateShaderCompiler())
                {
                    // Vertex shader (copy paste position).
                    compiler.Begin(BindingStage.VertexShader);
                    ShaderCompiler.Operand position = compiler.CreateInput(PinFormat.Floatx4, PinComponent.Position);
                    compiler.Output(position, PinComponent.Position);
                    vshader = compiler.End(null) as VShader;

                    // And pixel shader.
                    compiler.Begin(BindingStage.PixelShader);
                    ShaderCompiler.Operand colour = compiler.CreateFixed(PinFormat.Floatx4, Pin.NotArray, new Vector4f(1, 0, 0, 1));
                    compiler.Output(colour, PinComponent.RenderTarget0);
                    pshader = compiler.End(null) as PShader;
                }

                // We create triangles.
                Geometry       geometry = new Geometry();
                TypelessBuffer buffer   = new TypelessBuffer(Usage.Static,
                                                             BufferUsage.VertexBuffer, CPUAccess.None, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 3);

                byte[] d = buffer.Map(MapOptions.Read);
                fixed(byte *p = d)
                {
                    float *data = (float *)p;

                    // Vertex 0:
                    data[0] = -0.5f; data[1] = -0.5f; data[2] = 0.0f; data[3] = 1.0f;

                    // Vertex 1:
                    data[4] = 0.5f; data[5] = -0.5f; data[6] = 0.0f; data[7] = 1.0f;

                    // Vertex 2:
                    data[8] = 0.0f; data[9] = 0.5f; data[10] = 0.0f; data[11] = 1.0f;
                }

                buffer.UnMap();


                // Create vertex buffer and view.
                VertexBufferView vbuffer = buffer.CreateVertexBuffer(VertexFormat.Parse("P.Fx4"));

                // We construct geometry.
                geometry[0]       = vbuffer;
                geometry.Topology = Topology.Triangle;

                // Blend state.
                BlendState blendState = new BlendState();
                blendState[0] = false;

                blendState = StateManager.Intern(blendState);

                RasterizationState rastState = new RasterizationState();
                rastState.CullMode = CullMode.None;
                rastState.FillMode = FillMode.Solid;

                rastState = StateManager.Intern(rastState);

                DepthStencilState depthState = new DepthStencilState();
                depthState.DepthTestEnabled  = false;
                depthState.DepthWriteEnabled = false;

                depthState = StateManager.Intern(depthState);

                // Enter rendering loop.
                bool isClosed = false;
                window.Closed += delegate(Window w)
                {
                    isClosed = true;
                };

                while (!isClosed)
                {
                    window.DoEvents();

                    if (!isClosed)
                    {
                        SwapChain chain = device.SwapChain;

                        device.Enter();
                        try
                        {
                            // We just clear.
                            device.Clear(chain, Colour.Black);

                            // Set blend/rast.
                            device.SetBlendState(blendState, Colour.White, 0xFFFFFFFF);
                            device.RasterizationState = rastState;
                            device.SetDepthStencilState(depthState, 0);

                            // Sets states.
                            device.SetVertexShader(vshader, geometry, null, null, null);
                            device.SetPixelShader(pshader, null, null, null, new RenderTargetView[] { chain }, null);

                            device.Viewport = new Region2i(0, 0, (int)chain.Width, (int)chain.Height);

                            // Render.
                            device.Draw(0, 3);
                        }
                        finally
                        {
                            device.Exit();
                        }

                        chain.Present();
                        Thread.Sleep(10);
                    }
                }


                // Dispose all.
                vshader.Dispose();
                pshader.Dispose();
                geometry.Dispose();
                vbuffer.Dispose();
                buffer.Dispose();
            }
        }
Exemplo n.º 14
0
 internal ConstantBufferView(TypelessBuffer buffer, ConstantBufferLayout layout)
 {
     this.buffer = buffer;
     this.layout = layout;
 }