Exemplo n.º 1
0
 public void ClearBuffers()
 {
     if (BufferInitialized)
     {
         ElementBuffer.Clear(BufferTarget.ArrayBuffer);
     }
 }
        public void Draw(GLShaderProgram shaderProgram)
        {
            Material.Bind(shaderProgram);
            ElementBuffer.Bind();

            GL.DrawElements(PrimitiveType, ElementBuffer.Length, DrawElementsType.UnsignedInt, 0);
        }
Exemplo n.º 3
0
        public ParticleEffectPool(CommandBuffer commands)
        {
            cmd = commands;
            //Free particles (is this efficient?)
            for (int i = MAX_PARTICLES - 1; i >= 0; i--)
            {
                FreeParticles.Push(i);
            }
            //Set up vertices
            vbo = new VertexBuffer(typeof(ParticleVertex), MAX_PARTICLES * 4, true);
            //Indices
            ibo = new ElementBuffer(MAX_PARTICLES * 6);
            ushort[] indices = new ushort[MAX_PARTICLES * 6];
            int      iptr    = 0;

            for (int i = 0; i < (MAX_PARTICLES * 4); i += 4)
            {
                //Triangle 1
                indices[iptr++] = (ushort)i;
                indices[iptr++] = (ushort)(i + 1);
                indices[iptr++] = (ushort)(i + 2);
                //Triangle 2
                indices[iptr++] = (ushort)(i + 1);
                indices[iptr++] = (ushort)(i + 3);
                indices[iptr++] = (ushort)(i + 2);
            }
            ibo.SetData(indices);
            vbo.SetElementBuffer(ibo);
            basicShader = Shaders.Particle.Get();
        }
Exemplo n.º 4
0
        static void Load()
        {
            if (loaded)
            {
                return;
            }
            loaded   = true;
            vertices = new VertexBuffer(typeof(VertexPositionTexture), 4);
            vertices.SetData(new[]
            {
                new VertexPositionTexture(new Vector3(-GRID_SIZE, 0, -GRID_SIZE), Vector2.Zero),
                new VertexPositionTexture(new Vector3(GRID_SIZE, 0, -GRID_SIZE), new Vector2(TEXCOORD, 0)),
                new VertexPositionTexture(new Vector3(-GRID_SIZE, 0, GRID_SIZE), new Vector2(0, TEXCOORD)),
                new VertexPositionTexture(new Vector3(GRID_SIZE, 0, GRID_SIZE), new Vector2(TEXCOORD, TEXCOORD)),
            });
            elements = new ElementBuffer(6);
            elements.SetData(new short[] { 0, 1, 2, 1, 3, 2 });
            vertices.SetElementBuffer(elements);
            string glslVer = RenderContext.GLES ? "310 es\nprecision mediump float;\nprecision mediump int;" : "140";

            shader    = new Shader(VertexShader.Replace("{0}", glslVer), FragmentShader.Replace("{0}", glslVer));
            viewProj  = shader.GetLocation("ViewProjection");
            view      = shader.GetLocation("View");
            gridColor = shader.GetLocation("GridColor");
            gridScale = shader.GetLocation("GridScale");
        }
Exemplo n.º 5
0
        public static void Init(ResourceManager res)
        {
            if (inited)
            {
                return;
            }
            inited     = true;
            lines      = new VertexPositionColor[MAX_GIZMOS * 6];
            tris       = new VertexPositionColor[MAX_GIZMOS * 8];
            lineBuffer = new VertexBuffer(typeof(VertexPositionColor), MAX_GIZMOS * 6, true);
            ushort[] indices = new ushort[MAX_GIZMOS * idxcube.Length];
            for (int i = 0; i < MAX_GIZMOS; i++)
            {
                for (int j = 0; j < idxcube.Length; j++)
                {
                    indices[i * idxcube.Length + j] = (ushort)(idxcube[j] + (8 * i));
                }
            }
            triBuffer = new VertexBuffer(typeof(VertexPositionColor), MAX_GIZMOS * 8, true);
            triElems  = new ElementBuffer(MAX_GIZMOS * idxcube.Length);
            triElems.SetData(indices);
            triBuffer.SetElementBuffer(triElems);

            gizmoMaterial        = new Material(res);
            gizmoMaterial.Dc     = Color4.White;
            gizmoMaterial.DtName = ResourceManager.WhiteTextureName;
        }
Exemplo n.º 6
0
        public void SetUp()
        {
            adapter = new Mock<IBufferAdapter>();
            adapter.Setup(a => a.GenBuffer())
                   .Returns(1);

            elementBuffer = new ElementBuffer<ushort>(adapter.Object);
        }
Exemplo n.º 7
0
 private void setUpIndexBuffer()
 {
     if (ElementBuffer == null)
     {
         ElementBuffer = new ElementBuffer(indices.Length);
         ElementBuffer.SetData(indices);
         VertexBuffer.SetElementBuffer(ElementBuffer);
     }
 }
Exemplo n.º 8
0
        public void SetElements(IEnumerable <T> elements)
        {
            if (!BufferInitialized)
            {
                CreateBuffers();
            }

            ElementBuffer.Init(BufferTarget.ArrayBuffer, elements.ToArray());
        }
Exemplo n.º 9
0
        public OpenCylinder(int slices)
        {
            vertices     = new VertexPositionNormalTexture[(slices + 2) * 2];
            indices      = new ushort[slices * 6];
            indices_temp = new ushort[slices * 6];
            indices_sort = new int[slices * 2];
            primCount    = slices * 2;
            float height = 0.5f, radius = 1;
            int   iptr       = 0;
            int   vptr       = 0;
            float texAdvance = 1f / slices;

            for (int i = 0; i < slices; i++)
            {
                var normal = GetCircleVector(i, slices);
                //generate vertices
                vertices[vptr++] = new VertexPositionNormalTexture(
                    normal * radius + Vector3.Up * height,
                    normal,
                    new Vector2(i, 1)
                    );
                vertices[vptr++] = new VertexPositionNormalTexture(
                    normal * radius + Vector3.Down * height,
                    normal,
                    new Vector2(i, 0)
                    );
                //generate indicess
                indices[iptr++] = (ushort)((i * 2 + 2) % ((slices + 1) * 2));
                indices[iptr++] = (ushort)(i * 2 + 1);
                indices[iptr++] = (ushort)(i * 2);

                indices[iptr++] = (ushort)((i * 2 + 2) % ((slices + 1) * 2));
                indices[iptr++] = (ushort)((i * 2 + 3) % ((slices + 1) * 2));
                indices[iptr++] = (ushort)(i * 2 + 1);
            }
            //last vertex
            var last = GetCircleVector(slices, slices);

            vertices[vptr++] = new VertexPositionNormalTexture(
                last * radius + Vector3.Up * height,
                last,
                new Vector2(slices, 1)
                );
            vertices[vptr++] = new VertexPositionNormalTexture(
                last * radius + Vector3.Down * height,
                last,
                new Vector2(slices, 0)
                );
            //upload
            VertexBuffer = new VertexBuffer(typeof(VertexPositionNormalTexture), vertices.Length);
            VertexBuffer.SetData(vertices);
            elemBuffer = new ElementBuffer(indices.Length);
            elemBuffer.SetData(indices);
            VertexBuffer.SetElementBuffer(elemBuffer);
        }
Exemplo n.º 10
0
        public void Initialize(ResourceManager cache)
        {
            List<DfmVertex> vertices = new List<DfmVertex>();
            for (int i = 0; i < PointIndices.Length; i++)
            {
                var first = PointBoneFirst[PointIndices[i]];
                var count = PointBoneCount[PointIndices[i]];
                int id1 = 0, id2 = 0, id3 = 0, id4 = 0;
                var weights = new Vector4(1, 0, 0, 0);
                if(count > 0) {
                    id1 = BoneIdChain[first];
                    weights.X = BoneWeightChain[first];
                }
                if (count > 1) {
                    id2 = BoneIdChain[first + 1];
                    weights.Y = BoneWeightChain[first + 1];
                }
                if (count > 2) {
                    id3 = BoneIdChain[first + 2];
                    weights.Z = BoneWeightChain[first + 2];
                }
                if (count > 3) {
                    id4 = BoneIdChain[first + 3];
                    weights.W = BoneWeightChain[first + 3];
                }
                if (count > 4) throw new NotImplementedException();
                var uv = UV0[UV0Indices[i]];
                uv.Y = 1 - uv.Y;
                vertices.Add(new DfmVertex(Points[PointIndices[i]], VertexNormals[PointIndices[i]], uv, weights, id1, id2, id3, id4));
            }

            vertexBuffer = new VertexBuffer(typeof(DfmVertex), vertices.Count);
            vertexBuffer.SetData<DfmVertex>(vertices.ToArray());

            int indexCount = 0;
            foreach (FaceGroup faceGroup in FaceGroups)
            {
                faceGroup.StartIndex = indexCount;
                faceGroup.Initialize(cache);
                indexCount += faceGroup.TriangleStripIndices.Length;
            }
            var indices = new ushort[indexCount];
            elementBuffer = new ElementBuffer(indexCount);
            indexCount = 0;
            foreach (FaceGroup faceGroup in FaceGroups)
            {
                faceGroup.TriangleStripIndices.CopyTo(indices, indexCount);
                indexCount += faceGroup.TriangleStripIndices.Length;
            }
            elementBuffer.SetData(indices);
            vertexBuffer.SetElementBuffer(elementBuffer);
            ready = true;
        }
Exemplo n.º 11
0
 /// <summary> Called before Render (normally by RenderList::Render) to set up data for the render.
 /// currentstate may be null, meaning, don't apply
 /// RenderState may be null, meaning don't change</summary>
 public void Bind(GLRenderState currentstate, IGLProgramShader shader, GLMatrixCalc matrixcalc)
 {
     if (currentstate != null && RenderState != null)    // if either null, it means the last render state applied is the same as our render state, so no need to apply
     {
         currentstate.ApplyState(RenderState);           // else go to this state
     }
     VertexArray?.Bind();                                // give the VA a chance to bind to GL
     RenderData?.Bind(this, shader, matrixcalc);         // optional render data supplied by the user to bind
     ElementBuffer?.BindElement();                       // if we have an element buffer, give it a chance to bind
     IndirectBuffer?.BindIndirect();                     // if we have an indirect buffer, give it a chance to bind
     ParameterBuffer?.BindParameter();                   // if we have a parameter buffer, give it a chance to bind
 }
Exemplo n.º 12
0
        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            if (Handle != -1)
            {
                GL.DeleteVertexArrays(1, ref Handle);
            }
            Handle = -1;

            if (ElementBuffer != null)
            {
                ElementBuffer.Dispose();
            }
            ElementBuffer = null;
        }
        public void Render(int numSprites)
        {
            ElementBuffer.Bind();
            GL.DrawElements(BeginMode.Triangles, numSprites * 6, DrawElementsType.UnsignedInt, IntPtr.Zero);

            // Tell opengl we don't need this data anymore.
            VertexBuffer.Bind();
            VertexBuffer.Invalidate();

            UVBuffer.Bind();
            UVBuffer.Invalidate();

            ColorBuffer.Bind();
            ColorBuffer.Invalidate();
        }
Exemplo n.º 14
0
        /// <summary>
        /// Create a <see cref="ArrayBufferBase"/> for testing.
        /// </summary>
        /// <returns>
        /// It returns the <see cref="ArrayBufferBase"/> instance to test.
        /// </returns>
        private void CreateClientInstance(Buffer buffer)
        {
            if (buffer.GetType() == typeof(ArrayBuffer))
            {
                ArrayBuffer arrayBufferObject = (ArrayBuffer)buffer;

                arrayBufferObject.Create(CreateTestArray());
            }
            else if (buffer.GetType() == typeof(ElementBuffer))
            {
                ElementBuffer elementBufferObject = (ElementBuffer)buffer;

                elementBufferObject.Create(CreateTestArray());
            }
        }
Exemplo n.º 15
0
        public static Model CreateModel <TVertex>(TVertex[] vertexData, int[] indices) where TVertex : struct
        {
            var vbo = VertexBuffer.CreateVertexBuffer();

            vbo.LoadData(vertexData);
            var vao = VertexArray.CreateVertexArray();

            vao.Bind();
            var shaderProgram = ShaderProgramFactory.CreateDefault2DShaderProgram();
            var ebo           = ElementBuffer.CreateElementBuffer();

            ebo.Bind();
            ebo.LoadData(indices);
            return(new Model(vao, vbo, ebo, shaderProgram));
        }
Exemplo n.º 16
0
        void GenerateVertexBuffer()
        {
            switch (FlexibleVertexFormat)
            {
            case D3DFVF.XYZ:     //(D3DFVF)0x0002:
                VertexBuffer = new VertexBuffer(typeof(VertexPosition), VertexCount);
                VertexBuffer.SetData <VertexPosition>(verticesVertexPosition);
                break;

            case D3DFVF.XYZ | D3DFVF.NORMAL:     //(D3DFVF)0x0012:
                VertexBuffer = new VertexBuffer(typeof(VertexPositionNormal), VertexCount);
                VertexBuffer.SetData <VertexPositionNormal>(verticesVertexPositionNormal);
                break;

            case D3DFVF.XYZ | D3DFVF.TEX1:     //(D3DFVF)0x0102:
                VertexBuffer = new VertexBuffer(typeof(VertexPositionTexture), VertexCount);
                VertexBuffer.SetData <VertexPositionTexture>(verticesVertexPositionTexture);
                break;

            case D3DFVF.XYZ | D3DFVF.NORMAL | D3DFVF.TEX1:     //(D3DFVF)0x0112:
                VertexBuffer = new VertexBuffer(typeof(VertexPositionNormalTexture), VertexCount);
                VertexBuffer.SetData <VertexPositionNormalTexture>(verticesVertexPositionNormalTexture);
                break;

            case D3DFVF.XYZ | D3DFVF.NORMAL | D3DFVF.DIFFUSE | D3DFVF.TEX1:     //(D3DFVF)0x0152:
                VertexBuffer = new VertexBuffer(typeof(VertexPositionNormalColorTexture), VertexCount);
                VertexBuffer.SetData <VertexPositionNormalColorTexture>(verticesVertexPositionNormalColorTexture);
                break;

            case D3DFVF.XYZ | D3DFVF.NORMAL | D3DFVF.TEX2:     //(D3DFVF)0x0212:
                VertexBuffer = new VertexBuffer(typeof(VertexPositionNormalTextureTwo), VertexCount);
                VertexBuffer.SetData <VertexPositionNormalTextureTwo>(verticesVertexPositionNormalTextureTwo);
                break;

            case D3DFVF.XYZ | D3DFVF.NORMAL | D3DFVF.DIFFUSE | D3DFVF.TEX2:     //(D3DFVF)0x0252:
                VertexBuffer = new VertexBuffer(typeof(VertexPositionNormalDiffuseTextureTwo), VertexCount);
                VertexBuffer.SetData <VertexPositionNormalDiffuseTextureTwo>(verticesVertexPositionNormalDiffuseTextureTwo);
                break;

                /*case D3DFVF.XYZ | D3DFVF.NORMAL | D3DFVF.TEX4: //(D3DFVF)0x0412:
                 *  VertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalTextureTangentBinormal), VertexCount, BufferUsage.WriteOnly);
                 *  VertexBuffer.SetData<VertexPositionNormalTextureTangentBinormal>(verticesVertexPositionNormalTextureTangentBinormal);
                 *  break;*/
            }
            ElementBuffer = new ElementBuffer(IndexCount);
            ElementBuffer.SetData(Indices);
            VertexBuffer.SetElementBuffer(ElementBuffer);
        }
Exemplo n.º 17
0
        private bool mDisposed = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!mDisposed)
            {
                if (disposing)
                {
                    PositionBuffer.Dispose();
                    NormalBuffer?.Dispose();
                    TextureCoordinateChannel0Buffer?.Dispose();
                    ElementBuffer.Dispose();
                    GL.DeleteVertexArray(Id);
                }

                mDisposed = true;
            }
        }
Exemplo n.º 18
0
        public Quad()
        {
            VertexPositionTexture[] vertices = new VertexPositionTexture[VERTEX_COUNT];

            vertices[0] = new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 1));
            vertices[1] = new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 1));
            vertices[2] = new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 0));
            vertices[3] = new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 0));

            VertexBuffer = new VertexBuffer(typeof(VertexPositionTexture), VERTEX_COUNT);
            VertexBuffer.SetData <VertexPositionTexture>(vertices);

            ElementBuffer = new ElementBuffer(indices.Length);
            ElementBuffer.SetData(indices);
            VertexBuffer.SetElementBuffer(ElementBuffer);
        }
Exemplo n.º 19
0
        public void Bind_BindsToGl_UnbindsOnDispose()
        {
            // Arrange
            var gl = Substitute.For<IOpenGL30>();
            gl.When(g => g.GenBuffers(Arg.Any<int>(), Arg.Any<uint[]>())).Do(x => ((uint[])x[1])[0] = 1);
            var buffer = new ElementBuffer<int>(new[] { 1, 2, 3 }, gl);

            // Act
            using (buffer.Bind())
            {
            }

            // Assert
            gl.Received().BindBuffer((uint)BufferTarget.ElementArray, 1);
            gl.Received().BindBuffer((uint)BufferTarget.ElementArray, 0);
        }
Exemplo n.º 20
0
        public void Dispose()
        {
            if (ElementBuffer != null)
            {
                ElementBuffer.Dispose();
                ElementBuffer = null;
            }

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

            IsDisposed = true;
        }
Exemplo n.º 21
0
        public Ellipsoid(Vector3 Size, int stacks, int slices)
        {
            VertexPositionTexture[] vertices = new VertexPositionTexture[(slices + 1) * (stacks + 1)];
            ushort[] indices = new ushort[slices * stacks * 6];

            float  deltaTheta = MathHelper.Pi / stacks;
            float  deltaPhi = MathHelper.TwoPi / slices;
            ushort vertexIndex = 0, index = 0;
            ushort sliceCount = (ushort)(slices + 1);

            for (ushort stack = 0; stack <= stacks; stack++)
            {
                float theta = MathHelper.PiOver2 - stack * deltaTheta;
                float y     = Size.Y * (float)Math.Sin(theta);

                for (ushort slice = 0; slice <= slices; slice++)
                {
                    float phi = slice * deltaPhi;
                    float x   = -Size.X * (float)Math.Cos(theta) * (float)Math.Sin(phi);
                    float z   = -Size.Z * (float)Math.Cos(theta) * (float)Math.Cos(phi);

                    Vector3 pos = new Vector3(x, y, z);
                    vertices[vertexIndex++] = new VertexPositionTexture(
                        pos,
                        new Vector2((float)slice / (float)slices, (float)stack / (float)stacks)
                        );

                    if (stack < stacks && slice < slices)
                    {
                        indices[index++] = (ushort)((stack + 0) * sliceCount + slice);
                        indices[index++] = (ushort)((stack + 1) * sliceCount + slice);
                        indices[index++] = (ushort)((stack + 0) * sliceCount + slice + 1);

                        indices[index++] = (ushort)((stack + 0) * sliceCount + slice + 1);
                        indices[index++] = (ushort)((stack + 1) * sliceCount + slice);
                        indices[index++] = (ushort)((stack + 1) * sliceCount + slice + 1);
                    }
                }
            }

            VertexBuffer = new VertexBuffer(typeof(VertexPositionTexture), vertices.Length);
            VertexBuffer.SetData <VertexPositionTexture>(vertices);

            ElementBuffer = new ElementBuffer(indices.Length);
            ElementBuffer.SetData(indices);
            VertexBuffer.SetElementBuffer(ElementBuffer);
        }
Exemplo n.º 22
0
        public virtual void Dispose()
        {
            if (!cleanedUp)
            {
                cleanedUp = true;

                for (int i = 0; i < ArrayBufferObjects.Length; i++)
                {
                    ArrayBufferObjects[i].Dispose();
                }

                if (ElementBuffer != null)
                {
                    ElementBuffer.Dispose();
                }
            }
        }
Exemplo n.º 23
0
        public void Constructor_Ok()
        {
            // Arrange
            var gl = Substitute.For<IOpenGL30>();
            gl.WhenForAnyArgs(g => g.GenBuffers(Arg.Any<int>(), Arg.Any<uint[]>()))
                .Do(x =>
                { ((uint[])x[1])[0] = 1; });


            // Act
            var buffer = new ElementBuffer<int>(new[] { 1, 2, 3 }, gl);

            // Assert
            Assert.AreEqual(1, buffer.Handle);
            Assert.AreEqual(3, buffer.Elements);
            Assert.AreEqual(4, buffer.ElementSize);
            Assert.AreEqual(typeof(int), buffer.ElementType);
        }
Exemplo n.º 24
0
        public static Model CreateModel <TVertex>(Texture texture, TVertex[] vertexData, int[] indices) where TVertex : struct
        {
            var shader = ShaderProgramFactory.CreateDefault2DShaderProgramWithTexture();
            var vbo    = VertexBuffer.CreateVertexBuffer();

            vbo.LoadData(vertexData);
            var vao = VertexArray.CreateVertexArray();

            vao.Bind();
            shader.Use();
            shader.SetVertexAttributes();
            vbo.Bind();
            texture.Bind();
            var ebo   = ElementBuffer.CreateElementBuffer(indices);
            var model = new Model(vao, vbo, ebo, shader);

            return(model);
        }
        public SpriteVertexBuffer()
            : base(BufferUsageHint.StreamDraw, 3)
        {
            Bind();

            InitializeArrayBuffer(0, 2, VertexAttribPointerType.Float, false, 0, 0, BufferUsageHint.StreamDraw);
            VertexBuffer.SetData(MAX_SPRITES * 8 * sizeof(float));

            InitializeArrayBuffer(1, 2, VertexAttribPointerType.Float, false, 0, 0, BufferUsageHint.StreamDraw);
            UVBuffer.SetData(MAX_SPRITES * 8 * sizeof(float));

            InitializeArrayBuffer(2, 4, VertexAttribPointerType.UnsignedByte, true, 0, 0, BufferUsageHint.StreamDraw);
            ColorBuffer.SetData(MAX_SPRITES * 16 * sizeof(byte));

            InitializeElementBuffer(BufferUsageHint.StaticDraw);
            ElementBuffer.SetData(MAX_SPRITES * 6 * sizeof(uint), ConstructElementBuffer());

            Unbind();
        }
Exemplo n.º 26
0
        public static Model CreateModel <TVertex>(TVertex[] vertexData, Texture[] textures, int[] indices, ShaderProgram shader) where TVertex : struct
        {
            var vbo = VertexBuffer.CreateVertexBuffer();

            vbo.LoadData(vertexData);
            var vao = VertexArray.CreateVertexArray();

            vao.Bind();
            shader.Use();
            shader.SetVertexAttributes();
            vbo.Bind();
            var ebo   = ElementBuffer.CreateElementBuffer(indices);
            var model = new Model(vao, vbo, ebo, shader);

            for (int i = 0; i < textures.Length; i++)
            {
                textures[i].Bind(i);
            }
            return(model);
        }
Exemplo n.º 27
0
        public void Update(float[] vertices, uint[] indexes, float[] colors, float[] normals)
        {
            Bind();

            ElementBuffer.Bind();
            ElementBuffer.SetData(sizeof(uint) * indexes.Length, indexes);

            VertexBuffer.Bind();
            VertexBuffer.SetData(sizeof(float) * vertices.Length, vertices);

            ColorBuffer.Bind();
            ColorBuffer.SetData(sizeof(float) * colors.Length, colors);

            NormalBuffer.Bind();
            NormalBuffer.SetData(sizeof(float) * normals.Length, normals);

            VertexCount = indexes.Length;

            Unbind();
        }
Exemplo n.º 28
0
        public override void Setup()
        {
            GL.Enable(EnableCap.DepthTest);
            GL.ClearColor(0.4f, 0.7f, 0.9f, 0.5f);

            var vertices = new ColoredTexturedVertex[] {
                new ColoredTexturedVertex(new Vector3(0.5f, 0.5f, 0.0f), Color4.Blue, new Vector2(1.0f, 1.0f)),
                new ColoredTexturedVertex(new Vector3(0.5f, -0.5f, 0.0f), Color4.Green, new Vector2(1.0f, 0.0f)),
                new ColoredTexturedVertex(new Vector3(-0.5f, -0.5f, 0.0f), Color4.Red, new Vector2(0.0f, 0.0f)),
                new ColoredTexturedVertex(new Vector3(-0.5f, 0.5f, 0.0f), Color4.Yellow, new Vector2(0.0f, 1.0f))
            };
            var indices = new int [] {
                0, 1, 3,
                1, 2, 3
            };
            var vao = VertexArray.CreateVertexArray();

            vao.Bind();
            _vao = vao;
            var vbo = VertexBuffer.CreateVertexBuffer();

            vbo.LoadData(vertices);
            _vbo = vbo;
            var ebo = ElementBuffer.CreateElementBuffer();

            ebo.LoadData(indices);
            _ebo = ebo;
            var shader = ShaderProgramFactory.CreateDefault3DShaderProgramWithTexture();

            _shader = shader;
            var texture0 = Texture.LoadTexture("Assets/Textures/container.png");

            texture0.Bind(0);
            var texture1 = Texture.LoadTexture("Assets/Textures/awesomeface.png");

            texture1.Bind(1);
            _shader.SetInt("texture1", 0);
            _shader.SetInt("texture2", 1);
            base.Setup();
        }
Exemplo n.º 29
0
        public override void Setup()
        {
            GL.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            var vertices = new ColoredVertex[]
            {
                new ColoredVertex(new Vector3(0.5f, 0.5f, 0.0f), Color4.AliceBlue), //Bottom-left vertex
                // new ColoredVertex(new Vector3(0.5f, -0.5f, 0.0f),Color4.BlanchedAlmond), //Bottom-right vertex
                // new ColoredVertex(new Vector3(-0.5f,  -0.5f, 0.0f),Color4.Fuchsia), //Top vertex
                new ColoredVertex(new Vector3(-0.5f, -0.5f, 0.0f), Color4.Red),
                new ColoredVertex(new Vector3(-0.5f, 0.5f, 0.0f), Color4.Blue),
                new ColoredVertex(new Vector3(0.5f, 0.5f, 0.0f), Color4.Yellow)
            };
            var vbo = VertexBuffer.CreateVertexBuffer();

            vbo.Bind();
            vbo.LoadData(vertices);
            var ebo = ElementBuffer.CreateElementBuffer();

            ebo.Bind();
            ebo.LoadData(indices);
            var attributes = new [] {
                new VertexAttribute("aPosition", 3, VertexAttribPointerType.Float, sizeof(float) * (3 + 4), 0),
                new VertexAttribute("aColor", 4, VertexAttribPointerType.Float, sizeof(float) * (3 + 4), sizeof(float) * 3)
            };
            var shader = ShaderProgram.CreateShaderProgram("Assets/vertex.shader", "Assets/frag.shader", attributes);

            shader.Use();
            var vao = VertexArray.CreateVertexArray();

            vao.Bind();
            shader.SetVertexAttributes();
            vbo.Bind();
            ebo.Bind();
            VertexArrayObject   = vao;
            VertexBufferObject  = vbo;
            ElementBufferObject = ebo;
            Shader = shader;
            base.Setup();
        }
Exemplo n.º 30
0
        public void ExampleSetVertexArraysIndexedElements(GraphicsContext ctx, ShaderProgram shaderProgram)
        {
            VertexArrays vao = new VertexArrays();

            // ... create and setup buffers ...

            ElementBuffer <int> indexBuffer = new ElementBuffer <int>(BufferUsage.StaticDraw);

            indexBuffer.Create(new int[] { 0, 1, 2, 3, 2, 1 });

            // Draw the first 6 deferenced vertices as GL_TRIANGLES
            int idx1 = vao.SetElementArray(PrimitiveType.Triangles, indexBuffer);
            // Draw the first two deferenced vertices as GL_LINES
            int idx2 = vao.SetElementArray(PrimitiveType.Lines, indexBuffer, 0, 2);

            // Create/update all resources linked to this instance
            vao.Create(ctx);

            // Draw all elements
            vao.Draw(ctx, shaderProgram);
            // Draw only the triangles
            vao.Draw(ctx, shaderProgram, idx1);
        }
 static void Load()
 {
     if (loaded)
     {
         return;
     }
     loaded   = true;
     vertices = new VertexBuffer(typeof(VertexPositionTexture), 4);
     vertices.SetData(new[]
     {
         new VertexPositionTexture(new Vector3(-GRID_SIZE, 0, -GRID_SIZE), Vector2.Zero),
         new VertexPositionTexture(new Vector3(GRID_SIZE, 0, -GRID_SIZE), new Vector2(TEXCOORD, 0)),
         new VertexPositionTexture(new Vector3(-GRID_SIZE, 0, GRID_SIZE), new Vector2(0, TEXCOORD)),
         new VertexPositionTexture(new Vector3(GRID_SIZE, 0, GRID_SIZE), new Vector2(TEXCOORD, TEXCOORD)),
     });
     elements = new ElementBuffer(6);
     elements.SetData(new short[] { 0, 1, 2, 1, 3, 2 });
     vertices.SetElementBuffer(elements);
     shader    = new Shader(VertexShader, FragmentShader);
     viewProj  = shader.GetLocation("ViewProjection");
     view      = shader.GetLocation("View");
     gridColor = shader.GetLocation("GridColor");
     gridScale = shader.GetLocation("GridScale");
 }
Exemplo n.º 32
0
        public static Terrain Build(IOpenGL33 gl, int columns, int rows, float width, float depth)
        {
            var noise = new PerlinNoise();
            var noise2 = new PerlinNoise();
            
            var vertexBuffer = new VertexBuffer<PositionNormalTexCoord>((columns + 1) * (rows + 1), gl);
            var indexBuffer = new ElementBuffer<uint>(columns * rows * 6 , gl);

            float fx = - width / 2;
            float fy = -depth / 2;

            float dx = width / columns;
            float dy = depth / rows;

            int i = 0;

            for (int y = 0; y < (rows + 1); y++)
            {
                for (int x = 0; x < (columns + 1); x++, i++)
                {
                    float ix = fx + x * dx;
                    float iy = fy + y * dy;

                    const float detail = 0.25f;
                    const float detailScale = 0.2f;
                    const float macro = 0.008f;
                    const float macroScale = 4f;
                    var fUp = (float)((noise.Noise(x * detail, 0, (y + 1) * detail) - noise2.Noise(x * detail, 0, (y + 1) * detail) * 0.25f) * detailScale + noise.Noise(x * macro, 0, (y + 1) * macro) * macroScale) ;
                    var fDown = (float)((noise.Noise(x * detail, 0,  (y - 1) * detail) - noise2.Noise(x * detail, 0,  (y - 1) * detail) * 0.25f) * detailScale + noise.Noise(x * macro, 0,  (y - 1) * macro) * macroScale) ;
                    var fLeft = (float)((noise.Noise((x - 1) * detail, 0, y * detail) - noise2.Noise((x - 1) * detail, 0, y * detail) * 0.25f) * detailScale + noise.Noise((x - 1) * macro, 0, y * macro) * macroScale);
                    var fRight = (float)((noise.Noise((x + 1) * detail, 0, y * detail) - noise2.Noise((x + 1) * detail, 0, y * detail) * 0.25f) * detailScale + noise.Noise((x + 1) * macro, 0, y * macro) * macroScale);
                    var fThis = (float)((noise.Noise(x * detail, 0, y * detail) - noise2.Noise(x * detail, 0, y * detail) * 0.25f) * detailScale + noise.Noise(x * macro, 0, y * macro) * macroScale);

                    var vUp = new Vector3f(ix, fUp, iy - dy);
                    var vDown = new Vector3f(ix, fDown, iy + dy);
                    var vLeft = new Vector3f(ix - 1, fLeft, iy);
                    var vRight = new Vector3f(ix + 1, fRight, iy);
                    var vThis = new Vector3f(ix, fThis, iy);

                    var upperLeft = CalculateNormal(vLeft, vUp, vThis);
                    var upperRight = CalculateNormal(vUp, vRight, vThis);
                    var lowerRight = CalculateNormal(vRight, vDown, vThis);
                    var lowerLeft = CalculateNormal(vDown, vLeft, vThis);

                    var normal = upperLeft + upperRight + lowerLeft + lowerRight;
                    normal = new Vector3f(normal.X * 0.25f, normal.Y * 0.25f, normal.Z * 0.25f);

                    vertexBuffer[i] = new PositionNormalTexCoord { Normal = normal.Normalize(), Position = vThis, TexCoord = new Vector2f(vThis.X, vThis.Z)};
                }
            }
            int offset = 0;
            foreach(var index in Enumerable.Range(0, columns * rows + columns).Where(index => (index % (columns + 1)) != columns))
            {
                indexBuffer[offset] = (uint)index;
                indexBuffer[offset + 1] = (uint)(index + (columns + 1) + 1); 
                indexBuffer[offset + 2] = (uint)index + 1;

                indexBuffer[offset + 3] = (uint)index;                
                indexBuffer[offset + 4] = (uint)(index + (columns + 1));
                indexBuffer[offset + 5] = (uint)(index + (columns + 1) + 1);
                offset += 6;
            }

            using(vertexBuffer.Bind())
                vertexBuffer.BufferData(BufferUsage.StaticDraw);

            using(indexBuffer.Bind())
                indexBuffer.BufferData(BufferUsage.StaticDraw);

            var vertexArray = new VertexArray(gl, new[] {vertexBuffer}, new[] {PositionNormalTexCoord.Descriptor});

            var shader = new TerrainShader(gl);

            return new Terrain(gl, vertexArray, vertexBuffer, indexBuffer, shader);
        }
Exemplo n.º 33
0
        unsafe void RenderImDrawData(ImDrawDataPtr draw_data, RenderState rstate)
        {
            var io = ImGui.GetIO();
            //Set cursor
            var cur = ImGuiNative.igGetMouseCursor();

            switch (cur)
            {
            case ImGuiMouseCursor.Arrow:
                game.CursorKind = CursorKind.Arrow;
                break;

            case ImGuiMouseCursor.ResizeAll:
                game.CursorKind = CursorKind.Move;
                break;

            case ImGuiMouseCursor.TextInput:
                game.CursorKind = CursorKind.TextInput;
                break;

            case ImGuiMouseCursor.ResizeNS:
                game.CursorKind = CursorKind.ResizeNS;
                break;

            case ImGuiMouseCursor.ResizeNESW:
                game.CursorKind = CursorKind.ResizeNESW;
                break;

            case ImGuiMouseCursor.ResizeNWSE:
                game.CursorKind = CursorKind.ResizeNWSE;
                break;
            }
            //Render
            draw_data.ScaleClipRects(io.DisplayFramebufferScale);

            var    mat        = Matrix4.CreateOrthographicOffCenter(0, game.Width, game.Height, 0, 0, 1);
            Shader lastShader = textShader;

            textShader.SetMatrix(textShader.GetLocation("modelviewproj"), ref mat);
            textShader.SetInteger(textShader.GetLocation("tex"), 0);
            colorShader.SetMatrix(textShader.GetLocation("modelviewproj"), ref mat);
            colorShader.SetInteger(textShader.GetLocation("tex"), 0);
            textShader.UseProgram();
            rstate.Cull         = false;
            rstate.BlendMode    = BlendMode.Normal;
            rstate.DepthEnabled = false;
            for (int n = 0; n < draw_data.CmdListsCount; n++)
            {
                var     cmd_list   = draw_data.CmdListsRange[n];
                byte *  vtx_buffer = (byte *)cmd_list.VtxBuffer.Data;
                ushort *idx_buffer = (ushort *)cmd_list.IdxBuffer.Data;
                var     vtxCount   = cmd_list.VtxBuffer.Size;
                var     idxCount   = cmd_list.IdxBuffer.Size;
                if (vboSize < vtxCount || iboSize < idxCount)
                {
                    if (vbo != null)
                    {
                        vbo.Dispose();
                    }
                    if (ibo != null)
                    {
                        ibo.Dispose();
                    }
                    vboSize = Math.Max(vboSize, vtxCount);
                    iboSize = Math.Max(iboSize, idxCount);
                    vbo     = new VertexBuffer(typeof(Vertex2D), vboSize, true);
                    ibo     = new ElementBuffer(iboSize, true);
                    vbo.SetElementBuffer(ibo);
                    vbuffer = new Vertex2D[vboSize];
                    ibuffer = new ushort[iboSize];
                }
                for (int i = 0; i < cmd_list.IdxBuffer.Size; i++)
                {
                    ibuffer[i] = idx_buffer[i];
                }
                for (int i = 0; i < cmd_list.VtxBuffer.Size; i++)
                {
                    var ptr   = (ImDrawVert *)vtx_buffer;
                    var unint = ptr[i].col;
                    var a     = unint >> 24 & 0xFF;
                    var b     = unint >> 16 & 0xFF;
                    var g     = unint >> 8 & 0xFF;
                    var r     = unint & 0xFF;
                    vbuffer[i] = new Vertex2D(ptr[i].pos, ptr[i].uv, new Color4(r / 255f, g / 255f, b / 255f, a / 255f));
                }
                vbo.SetData(vbuffer, cmd_list.VtxBuffer.Size);
                ibo.SetData(ibuffer, cmd_list.IdxBuffer.Size);
                int startIndex = 0;
                for (int cmd_i = 0; cmd_i < cmd_list.CmdBuffer.Size; cmd_i++)
                {
                    var pcmd = cmd_list.CmdBuffer[cmd_i];
                    //TODO: Do something with pcmd->UserCallback ??
                    var       tid = pcmd.TextureId.ToInt32();
                    Texture2D tex;
                    if (tid == FONT_TEXTURE_ID)
                    {
                        if (lastShader != textShader)
                        {
                            textShader.UseProgram();
                            lastShader = textShader;
                        }
                        fontTexture.BindTo(0);
                    }
                    else if (textures.TryGetValue(tid, out tex))
                    {
                        if (lastShader != colorShader)
                        {
                            colorShader.UseProgram();
                            lastShader = colorShader;
                        }
                        tex.BindTo(0);
                    }
                    else
                    {
                        dot.BindTo(0);
                    }

                    GL.Enable(GL.GL_SCISSOR_TEST);
                    GL.Scissor(
                        (int)pcmd.ClipRect.X,
                        (int)(io.DisplaySize.Y - pcmd.ClipRect.W),
                        (int)(pcmd.ClipRect.Z - pcmd.ClipRect.X),
                        (int)(pcmd.ClipRect.W - pcmd.ClipRect.Y));
                    vbo.Draw(PrimitiveTypes.TriangleList, 0, startIndex, (int)pcmd.ElemCount / 3);
                    GL.Disable(GL.GL_SCISSOR_TEST);
                    startIndex += (int)pcmd.ElemCount;
                }
            }
        }
Exemplo n.º 34
0
 public void Dispose()
 {
     ElementBuffer.Dispose();
     Material.Dispose();
 }
Exemplo n.º 35
0
        public void Bind_WithIndexAndRange_BindsToGl_UnbindsOnDispose()
        {
            // Arrange
            var gl = Substitute.For<IOpenGL30>();
            gl.When(g => g.GenBuffers(Arg.Any<int>(), Arg.Any<uint[]>())).Do(x => ((uint[])x[1])[0] = 1);
            var buffer = new ElementBuffer<int>(new[] { 1, 2, 3 }, gl);

            // Act
            using (buffer.Bind(index: 2, startIndex:2, elements: 4))
            {
            }

            // Assert
            gl.Received().BindBufferRange((uint)BufferTarget.ElementArray, 2,  1, new IntPtr(8), new IntPtr(16));
            gl.Received().BindBufferBase((uint)BufferTarget.ElementArray, 2,  0);
        }
Exemplo n.º 36
0
        public void BufferSubData_Direct_Ok()
        {
            // Arrange
            var gl = Substitute.For<IOpenGL30>();
            gl.WhenForAnyArgs(g => g.GenBuffers(Arg.Any<int>(), Arg.Any<uint[]>()))
                .Do(x =>
                { ((uint[])x[1])[0] = 1; });

            var buffer = new ElementBuffer<int>(new[] { 1, 2, 3 }, gl);

            // Act
            buffer.BufferSubData(BufferUsage.StaticDraw, 1, 2);

            // Assert
            gl.Received().BufferSubData((uint)BufferTarget.ElementArray, new IntPtr(1), new IntPtr(2), Arg.Any<IntPtr>());
        }