Ejemplo n.º 1
0
        public void Draw()
        {
            if (vertices == null || triangles == null)
            {
                return;
            }
            //if (Material == null) return;

            Gl.Disable(EnableCap.CullFace);

            if (Material != null)
            {
                Material.Use();
            }

            Gl.BindBufferToShaderAttribute(vertices, Material.Program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(normals, Material.Program, "vertexNormal");
            if (uvs != null)
            {
                Gl.BindBufferToShaderAttribute(uvs, Material.Program, "vertexUV");
            }
            Gl.BindBuffer(triangles);

            Gl.DrawElements(BeginMode.Triangles, triangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
        }
Ejemplo n.º 2
0
        public GlVertexArray(GlProgram program, float[] positions, float[] colors)
        {
            if (program == null)
            {
                throw new ArgumentNullException(nameof(program));
            }

            // Allocate buffers referenced by this vertex array
            _BufferPosition = new GlBuffer(positions);
            _BufferColor    = new GlBuffer(colors);

            // Generate VAO name
            ArrayName = Gl.GenVertexArray();
            // First bind create the VAO
            Gl.BindVertexArray(ArrayName);

            // Set position attribute

            // Select the buffer object
            Gl.BindBuffer(BufferTarget.ArrayBuffer, _BufferPosition.BufferName);
            // Format the vertex information: 2 floats from the current buffer
            Gl.VertexAttribPointer((uint)program.LocationPosition, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
            // Enable attribute
            Gl.EnableVertexAttribArray((uint)program.LocationPosition);

            // As above, but for color attribute
            Gl.BindBuffer(BufferTarget.ArrayBuffer, _BufferColor.BufferName);
            Gl.VertexAttribPointer((uint)program.LocationColor, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
            Gl.EnableVertexAttribArray((uint)program.LocationColor);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 保存した状態を復帰する。
        /// </summary>
        public void RestoreState()
        {
            Gl.UseProgram((uint)LastProgram);

            SetEnabledVertexAttribArray(0, LastVertexAttribArrayEnabled[0] != 0);
            SetEnabledVertexAttribArray(1, LastVertexAttribArrayEnabled[1] != 0);
            SetEnabledVertexAttribArray(2, LastVertexAttribArrayEnabled[2] != 0);
            SetEnabledVertexAttribArray(3, LastVertexAttribArrayEnabled[3] != 0);

            SetEnabled(EnableCap.ScissorTest, LastScissorTest);
            SetEnabled(EnableCap.StencilTest, LastStencilTest);
            SetEnabled(EnableCap.DepthTest, LastDepthTest);
            SetEnabled(EnableCap.CullFace, LastCullFace);
            SetEnabled(EnableCap.Blend, LastBlend);

            Gl.FrontFace((FrontFaceDirection)LastFrontFace);

            Gl.ColorMask(LastColorMask[0] != 0, LastColorMask[1] != 0, LastColorMask[2] != 0, LastColorMask[3] != 0);

            Gl.BindBuffer(BufferTarget.ArrayBuffer, (uint)LastArrayBufferBinding);
            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, (uint)LastElementArrayBufferBinding);

            Gl.ActiveTexture(TextureUnit.Texture1);
            Gl.BindTexture(TextureTarget.Texture2d, (uint)LastTexture1Binding2D);

            Gl.ActiveTexture(TextureUnit.Texture0);
            Gl.BindTexture(TextureTarget.Texture2d, (uint)LastTexture0Binding2D);

            Gl.ActiveTexture((TextureUnit)LastActiveTexture);

            Gl.BlendFuncSeparate((BlendingFactor)LastBlending[0], (BlendingFactor)LastBlending[1], (BlendingFactor)LastBlending[2], (BlendingFactor)LastBlending[3]);

            RestoreViewport();
            RestoreFrameBuffer();
        }
Ejemplo n.º 4
0
        private static void OnRenderFrame()
        {
            // set up the OpenGL viewport and clear both the color and depth bits
            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // use our shader program
            Gl.UseProgram(program);

            // transform the triangle
            program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(-1.5f, 0, 0)));

            // bind the vertex attribute arrays for the triangle (the hard way)
            uint vertexPositionIndex = (uint)Gl.GetAttribLocation(program.ProgramID, "vertexPosition");

            Gl.EnableVertexAttribArray(vertexPositionIndex);
            Gl.BindBuffer(triangle);
            Gl.VertexAttribPointer(vertexPositionIndex, triangle.Size, triangle.PointerType, true, 12, IntPtr.Zero);
            Gl.BindBuffer(triangleElements);

            // draw the triangle
            Gl.DrawElements(BeginMode.Triangles, triangleElements.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            // transform the square
            program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(1.5f, 0, 0)));

            // bind the vertex attribute arrays for the square (the easy way)
            Gl.BindBufferToShaderAttribute(square, program, "vertexPosition");
            Gl.BindBuffer(squareElements);

            // draw the square
            Gl.DrawElements(BeginMode.Quads, squareElements.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Glut.glutSwapBuffers();
        }
Ejemplo n.º 5
0
        private void CreateTileIdVbo(Tile[] tempTiles)
        {
//Generate an instanced vertex array to identify each draw call in the shader
            float[] vDrawId = new float[numberOfTiles * numberOfVerticesPerTile];
//            int[] vDrawId = new int[numberOfTiles*6];

//            index = 0;
//            foreach (Tile aTile in tempTiles)
//            {
//                vDrawId[index] = (int) aTile.TheTileId;
//                index++;
//            }


            for (int i = 0; i < numberOfTiles * numberOfVerticesPerTile; i++)
            {
                Tile aTile = tempTiles[i / numberOfVerticesPerTile];
                vDrawId[i] = (int)aTile.TheTileId;
            }

            gDrawIdBuffer = new VBO <float>(vDrawId, VertexAttribPointerType.Float, BufferTarget.ArrayBuffer,
                                            BufferUsageHint.StaticDraw);
//            gDrawIdBuffer = new VBO<int>(vDrawId, VertexAttribPointerType.Int, BufferTarget.ArrayBuffer,
//                BufferUsageHint.StaticDraw);
            Gl.BindBuffer(gDrawIdBuffer);

            locationDrawid = (uint)Gl.GetAttribLocation(program.ProgramID, "drawTexId");
        }
Ejemplo n.º 6
0
        public void update(Chunk chunk)
        {
            if (vaoID_ == 0)
            {
                vaoID_ = Gl.GenVertexArray();
                Gl.GenBuffers(vboID_);
            }

            Gl.ShadeModel(ShadingModel.Smooth);

            Gl.BindVertexArray(vaoID_);

            if (chunk.vertices.Count() > 0)
            {
                Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID_[0]);
                Gl.BufferData(BufferTarget.ArrayBuffer, (uint)chunk.vertices.Count() * sizeof(float) * 3, chunk.vertices.ToArray(), BufferUsage.DynamicDraw);
                Gl.VertexAttribPointer(Shader.ATTRIB_VERTICES_POS, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
                Gl.EnableVertexAttribArray(Shader.ATTRIB_VERTICES_POS);
            }
            if (chunk.triangles.Count() > 0)
            {
                Gl.BindBuffer(BufferTarget.ElementArrayBuffer, vboID_[1]);
                Gl.BufferData(BufferTarget.ElementArrayBuffer, (uint)chunk.triangles.Count() * sizeof(int), chunk.triangles.ToArray(), BufferUsage.DynamicDraw);
                current_fc = chunk.triangles.Count();
            }

            Gl.BindVertexArray(0);
            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }
Ejemplo n.º 7
0
        // Initialize Opengl buffers
        public void initialize()
        {
            shaderImage.it = new Shader(Shader.IMAGE_VERTEX_SHADER, Shader.IMAGE_FRAGMENT_SHADER);
            texID          = Gl.GetUniformLocation(shaderImage.it.getProgramId(), "texImage");

            float[] g_quad_vertex_buffer_data = new float[18] {
                -1.0f, -1.0f, 0.0f,
                1.0f, -1.0f, 0.0f,
                -1.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, 0.0f,
                1.0f, -1.0f, 0.0f,
                1.0f, 1, 0.0f
            };

            quad_vb = Gl.GenBuffer();
            Gl.BindBuffer(BufferTarget.ArrayBuffer, quad_vb);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(sizeof(float) * g_quad_vertex_buffer_data.Length), g_quad_vertex_buffer_data, BufferUsage.StaticDraw);
            Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);

            Gl.Enable(EnableCap.Texture2d);
            imageTex = Gl.GenTexture();
            Gl.BindTexture(TextureTarget.Texture2d, imageTex);
            Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureWrapS, Gl.CLAMP_TO_BORDER);
            Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureWrapT, Gl.CLAMP_TO_BORDER);
            Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureWrapR, Gl.CLAMP_TO_BORDER);
            Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureMinFilter, Gl.LINEAR);
            Gl.TexParameter(TextureTarget.Texture2d, TextureParameterName.TextureMagFilter, Gl.LINEAR);
            Gl.TexImage2D(TextureTarget.Texture2d, 0, InternalFormat.Rgba, (int)resolution.width, (int)resolution.height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, null);
            Gl.BindTexture(TextureTarget.Texture2d, 0);
        }
Ejemplo n.º 8
0
        public void Draw(ShaderProgram aProgram)
        {
            if (vertices == null || triangles == null)
            {
                return;
            }

            Gl.Disable(EnableCap.CullFace);
            if (Material != null)
            {
                Material.Use();
            }
//            Vector tempLoc = theObjectGame.Location;
            aProgram.Use();
//            if (theObjectGame.TheObjectId == ObjectGame.ObjcetIds.Player)
//            {
//                aProgram["model_matrix"].SetValue(Matrix4.CreateRotationY(-((ObjectPlayer)theObjectGame).Orientation.Angle)*
//                                                  Matrix4.CreateTranslation(new Vector3(tempLoc.X, 0, tempLoc.Y)));
//
//            }
//            else
//            {
//                aProgram["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(tempLoc.X, 0, tempLoc.Y)));
//            }

            Gl.BindBufferToShaderAttribute(vertices, Material.Program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(normals, Material.Program, "vertexNormal");
            if (uvs != null)
            {
                Gl.BindBufferToShaderAttribute(uvs, Material.Program, "vertexUV");
            }
            Gl.BindBuffer(triangles);

            Gl.DrawElements(BeginMode.Triangles, triangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Virtual Unbind implementation.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for binding.
 /// </param>
 protected virtual void UnbindCore(GraphicsContext ctx)
 {
     if (ctx.Extensions.VertexBufferObject_ARB)
     {
         Gl.BindBuffer(BufferType, InvalidObjectName);
     }
 }
Ejemplo n.º 10
0
        private static void OnRenderFrame()
        {
            //Clock tick used for animation
            watch.Stop();
            float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency;

            watch.Restart();

            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit
                     | ClearBufferMask.DepthBufferBit);

            //Use shader
            Gl.UseProgram(program);

            //Drawing cube
            #region
            Gl.BindTexture(crateTexture);
            program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)));
            Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV");
            Gl.BindBuffer(cubeElements);
            //Dibuja el cube
            Gl.DrawElements(BeginMode.Triangles, cubeElements.Count,
                            DrawElementsType.UnsignedInt, IntPtr.Zero);
            #endregion


            Glut.glutSwapBuffers();
        }
Ejemplo n.º 11
0
        private void UpdateBuffer(Texture texture)
        {
            if (texture is null)
            {
                return;
            }
            if (firstRender)
            {
                firstRender = false;

                vao = Gl.CreateVertexArray();
                Gl.BindVertexArray(vao);

                Gl.BindBuffer(BufferTarget.ArrayBuffer, texture.baseVBO);
                Gl.VertexAttribPointer(0, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)0);
                Gl.VertexAttribPointer(1, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)(2 * sizeof(float)));
                Gl.EnableVertexAttribArray(0);
                Gl.EnableVertexAttribArray(1);

                ibo = Gl.CreateBuffer();
                Gl.BindBuffer(BufferTarget.ArrayBuffer, ibo);
                Gl.VertexAttribPointer(2, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)0);
                Gl.VertexAttribPointer(3, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)(2 * sizeof(float)));
                Gl.EnableVertexAttribArray(2);
                Gl.EnableVertexAttribArray(3);
                Gl.VertexAttribDivisor(2, 1);
                Gl.VertexAttribDivisor(3, 1);
            }

            Gl.BindBuffer(BufferTarget.ArrayBuffer, ibo);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)tilesBuffer.Length * sizeof(float), tilesBuffer, BufferUsage.DynamicDraw);
            updateBuffer = false;
        }
Ejemplo n.º 12
0
        public static Geometry GenerateGeometry(GeometryData geometryData, float[] vertices, float[] normals, float[] texCoords, PrimitiveType primitiveType = PrimitiveType.Triangles)
        {
            if (vertices.Length % 3 != 0 || normals.Length % 3 != 0 || texCoords.Length % 2 != 0)
            {
                throw new ArgumentException($"Invalid count of input variables");
            }
            var geometry = new Geometry(geometryData, primitiveType);

            geometry.m_VerticesCount = vertices.Length / 3;

            geometry.VAO = Gl.GenVertexArray();
            Gl.BindVertexArray(geometry.VAO);

            geometry.m_VertexBuffer = Gl.GenBuffer();
            Gl.BindBuffer(BufferTarget.ArrayBuffer, geometry.m_VertexBuffer);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(sizeof(float) * vertices.Length), vertices, BufferUsage.StaticDraw);
            Gl.VertexAttribPointer(POSITION_LOCATION, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
            Gl.EnableVertexAttribArray(POSITION_LOCATION);

            geometry.m_NormalBuffer = Gl.GenBuffer();
            Gl.BindBuffer(BufferTarget.ArrayBuffer, geometry.m_NormalBuffer);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(sizeof(float) * normals.Length), normals, BufferUsage.StaticDraw);
            Gl.VertexAttribPointer(NORMAL_LOCATION, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
            Gl.EnableVertexAttribArray(NORMAL_LOCATION);

            geometry.m_TexCoordBuffer = Gl.GenBuffer();
            Gl.BindBuffer(BufferTarget.ArrayBuffer, geometry.m_TexCoordBuffer);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(sizeof(float) * texCoords.Length), texCoords, BufferUsage.StaticDraw);
            Gl.VertexAttribPointer(TEX_COORD_LOCATION, 2, VertexAttribType.Float, false, 0, IntPtr.Zero);
            Gl.EnableVertexAttribArray(TEX_COORD_LOCATION);

            Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
            return(geometry);
        }
Ejemplo n.º 13
0
        public override void StartDrawingModel(float[] model_color, Matrix mvp_matrix)
        {
            // コンテキストの状態を保存する
            State.SaveState();

            // 描画設定をする
            Gl.FrontFace(FrontFaceDirection.Ccw);

            Gl.Disable(EnableCap.ScissorTest);
            Gl.Disable(EnableCap.StencilTest);
            Gl.Disable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.ColorMask(true, true, true, true);

            // 不要なバッファがバインドされていたら解除する
            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);

            // モデルのパラメータをコピーする
            if ((model_color != null) && (model_color.Length == 4))
            {
                model_color.CopyTo(ModelColor, 0);
            }
            else
            {
                DefaultModelColor.CopyTo(ModelColor, 0);
            }
            MvpMatrix = (Matrix)mvp_matrix.Clone();
        }
Ejemplo n.º 14
0
        public override void Draw()
        {
            if (isTexture)
            {
                Gl.BindTexture(Data.curTexture);
            }
            Data.program["model_matrix"].SetValue(
                Matrix4.CreateRotationY(Data.yangle) * Matrix4.CreateRotationX(Data.xangle) *
                Matrix4.CreateTranslation(new Vector3(2.0f, 0, 0)));
            Gl.BindBufferToShaderAttribute(vertexes, Data.program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(normals, Data.program, "vertexNormal");
            Data.program["enable_texture"].SetValue(isTexture);
            if (isTexture)
            {
                Gl.BindBufferToShaderAttribute(texture, Data.program, "vertexUV");
            }
            else
            {
                Gl.BindBufferToShaderAttribute(colors, Data.program, "vertexColor");
            }
            Gl.BindBuffer(indexes);

            Gl.DrawElements(BeginMode.Quads, indexes.Count,
                            DrawElementsType.UnsignedInt, IntPtr.Zero);
        }
Ejemplo n.º 15
0
        protected void UpdateBuffer()
        {
            if (firstRender)
            {
                firstRender = false;

                VAO = Gl.CreateVertexArray();
                Gl.BindVertexArray(VAO);

                Gl.BindBuffer(BufferTarget.ArrayBuffer, Texture.baseVBO);
                Gl.VertexAttribPointer(0, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)0);
                Gl.VertexAttribPointer(1, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)(2 * sizeof(float)));
                Gl.EnableVertexAttribArray(0);
                Gl.EnableVertexAttribArray(1);

                ibo = Gl.CreateBuffer();
                Gl.BindBuffer(BufferTarget.ArrayBuffer, ibo);
                Gl.VertexAttribPointer(2, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)0);
                Gl.VertexAttribPointer(3, 2, VertexAttribType.Float, false, 4 * sizeof(float), (IntPtr)(2 * sizeof(float)));
                Gl.EnableVertexAttribArray(2);
                Gl.EnableVertexAttribArray(3);
                Gl.VertexAttribDivisor(2, 1);
                Gl.VertexAttribDivisor(3, 1);
            }

            Gl.BindBuffer(BufferTarget.ArrayBuffer, ibo);
            Gl.BufferData(BufferTarget.ArrayBuffer, (uint)bufferData.Length * sizeof(float), bufferData, BufferUsage.DynamicDraw);
            updateBuffer = false;
        }
Ejemplo n.º 16
0
    public void BufferData()
    {
        Gl.BindVertexArray(arrayHandle);

        if (used > 0 && dirty)
        {
            unsafe
            {
                fixed(int *p = data)
                {
                    Gl.BindBuffer(BufferTarget.ArrayBuffer, bufferHandle);

                    // BufferSubData if we can
                    if (used <= lastUsed < used)
                    {
                        Gl.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)0, (uint)(used * vertexSize), (IntPtr)p);
                    }
                    else
                    {
                        Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(used * vertexSize), (IntPtr)p, BufferUsage.StaticDraw);
                        lastUsed = used;
                    }

                    Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
                }
            }

            dirty = false;

            // Clear the data from memory as it is now stored on the GPU
            data = null;
        }

        Gl.BindVertexArray(0);
    }
Ejemplo n.º 17
0
 /// <summary>
 /// Virtual Unbind implementation.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for binding.
 /// </param>
 protected virtual void UnbindCore(GraphicsContext ctx)
 {
     if (ctx.Extensions.VertexBufferObject_ARB || ctx.Version.IsCompatible(Gl.Version_200_ES))
     {
         Gl.BindBuffer(Target, InvalidObjectName);
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Ensures the provided pointer is the currently bound data buffer of the provided type.
        /// </summary>
        /// <param name="pointer">The pointer to ensure is bound.</param>
        /// <param name="type">The type of data buffer to ensure is bound.</param>
        public static void EnsureBound(uint pointer, BufferTarget type)
        {
            // Check if it is already bound.
            if (Bound[type] == pointer)
            {
                // If in debug mode, verify this with OpenGL.
                if (!Engine.Configuration.GlDebugMode)
                {
                    return;
                }

                bool foundBindingName = Enum.TryParse($"{type}Binding", true, out GetPName bindingName);
                if (!foundBindingName)
                {
                    Engine.Log.Warning($"Couldn't find binding name for data buffer of type {type}", MessageSource.GL);
                }
                Gl.GetInteger(bindingName, out int actualBound);
                if (actualBound != pointer)
                {
                    Engine.Log.Error($"Assumed bound data buffer of type {type} was {pointer} but it was {actualBound}.", MessageSource.GL);
                }
                return;
            }

            Gl.BindBuffer(type, pointer);
            Bound[type] = pointer;
        }
Ejemplo n.º 19
0
        public void update(Vector4[] points)
        {
            if (vaoID_ == 0)
            {
                vaoID_ = Gl.GenVertexArray();
                Gl.GenBuffers(vboID_);
            }

            Gl.ShadeModel(ShadingModel.Smooth);
            index.Clear();
            for (int c = 0; c < points.Count(); c++)
            {
                index.Add(c);
            }

            Gl.BindVertexArray(vaoID_);

            if (points.Count() > 0)
            {
                Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID_[0]);
                Gl.BufferData(BufferTarget.ArrayBuffer, (uint)points.Count() * sizeof(float) * 4, points, BufferUsage.DynamicDraw);
                Gl.VertexAttribPointer(Shader.ATTRIB_VERTICES_POS, 4, VertexAttribType.Float, false, 0, IntPtr.Zero);
                Gl.EnableVertexAttribArray(Shader.ATTRIB_VERTICES_POS);
            }

            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, vboID_[1]);
            Gl.BufferData(BufferTarget.ElementArrayBuffer, (uint)index.Count() * sizeof(int), index.ToArray(), BufferUsage.DynamicDraw);
            current_fc = index.Count();

            Gl.BindVertexArray(0);
            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }
Ejemplo n.º 20
0
        /// <inheritdoc />
        public override bool BindIndexBuffer(uint bufferId)
        {
#if DEBUG
            uint actualBound = GetBoundIndexBuffer();

            if (BoundIndexBuffer != 0 && BoundIndexBuffer != actualBound)
            {
                Engine.Log.Warning($"Bound index buffer was thought to be {BoundIndexBuffer} but is actually {actualBound}.", MessageSource.GL);
            }
#endif

            // Check if already bound.
            if (BoundIndexBuffer != 0 && BoundIndexBuffer == bufferId)
            {
                return(false);
            }

            GLThread.ExecuteGLThread(() =>
            {
                Gl.BindBuffer(BufferTarget.ElementArrayBuffer, bufferId);
                BoundIndexBuffer = bufferId;
                CheckError("after binding index buffer");
            });

            return(true);
        }
Ejemplo n.º 21
0
        public void Draw(ShaderProgram aProgram)
        {
            if (vertices == null || triangles == null)
            {
                return;
            }

            Gl.Disable(EnableCap.CullFace);
            if (Material != null)
            {
                Material.Use();
            }

            aProgram.Use();
            aProgram["model_matrix"].SetValue(Matrix4.CreateTranslation(realPos));
//            aProgram["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(Position.x, Position.y, 0)));

            Gl.BindBufferToShaderAttribute(vertices, Material.Program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(normals, Material.Program, "vertexNormal");
            if (uvs != null)
            {
                Gl.BindBufferToShaderAttribute(uvs, Material.Program, "vertexUV");
            }
            Gl.BindBuffer(triangles);

            Gl.DrawElements(BeginMode.Triangles, triangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
        }
Ejemplo n.º 22
0
        public void TestGenBuffer()
        {
            if (!HasVersion(Gl.Version_150) && !HasExtension("GL_ARB_vertex_buffer_object") && !HasVersion(Gl.Version_100_ES) && !HasVersion(Gl.Version_200_ES))
            {
                Assert.Inconclusive("OpenGL 1.5 or GL_ARB_vertex_buffer_object not supported or OpenGL ES 1.0/2.0");
            }

            using (Device device = new Device())
                using (new GLContext(device))
                {
                    uint arrayBuffer = Gl.GenBuffer();
                    try {
                        Assert.AreNotEqual(0U, arrayBuffer, "Gl.GenBuffer failure");

                        // It seems that on my system glIsBuffer returns true after glGenBuffer... anyone can confirm
                        // Assert.IsFalse(Gl.IsBuffer(arrayBuffer));

                        Gl.BindBuffer(BufferTarget.ArrayBuffer, arrayBuffer);
                        Assert.IsTrue(Gl.IsBuffer(arrayBuffer));
                    } finally {
                        if (arrayBuffer != 0)
                        {
                            Gl.DeleteBuffers(arrayBuffer);
                            Assert.IsFalse(Gl.IsBuffer(arrayBuffer), "Gl.DeleteBuffers failure");
                        }
                    }
                }
        }
Ejemplo n.º 23
0
        private void DrawBatch(Batch batch)
        {
            Gl.BindVertexArray(VAO);

            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, VBO);
            Gl.BufferData(BufferTargetARB.ArrayBuffer, batch.VertexCount * (uint)VertexStride, batch.Vertices, BufferUsageARB.StreamDraw);

            Gl.BindBuffer(BufferTargetARB.ElementArrayBuffer, EBO);
            Gl.BufferData(BufferTargetARB.ElementArrayBuffer, batch.VertexCount * sizeof(int), batch.Indices, BufferUsageARB.StreamDraw);

            // Vertex position
            Gl.EnableVertexAttribArray(0);
            Gl.VertexAttribPointer(0, 3, (int)VertexPointerType.Float, false, VertexStride, 0);
            // Color
            Gl.EnableVertexAttribArray(1);
            Gl.VertexAttribPointer(1, 4, Gl.UNSIGNED_BYTE, true, VertexStride, Vector3.SizeInBytes);
            // UV
            Gl.EnableVertexAttribArray(2);
            Gl.VertexAttribPointer(2, 2, (int)VertexPointerType.Float, false, VertexStride, Vector3.SizeInBytes + Color.SizeInBytes);

            shader.Use();

            Gl.BindTexture(batch.Texture.TextureTarget, batch.Texture.TextureID);
            Gl.DrawArrays(PrimitiveType.Triangles, 0, (int)(batch.VertexCount / 3));

            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
            Gl.BindBuffer(BufferTargetARB.ElementArrayBuffer, 0);
            Gl.DisableVertexAttribArray(0);
            Gl.DisableVertexAttribArray(1);
            Gl.DisableVertexAttribArray(2);
            Gl.BindVertexArray(0);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This method is called by <code>Render</code>, directly before
        /// <code>GL.drawElements</code>. It activates the program and sets up
        /// the GL context with the following constants and attributes:
        ///
        /// <code>uMvpMatrix</code> — MVP matrix
        /// <code>aPosition</code> — vertex position (xy)
        /// </summary>
        protected virtual void BeforeDraw()
        {
            Program.Activate(); // create, upload, use program

            //is this the best place for this?
            Gl.BindBuffer(BufferTarget.ArrayBuffer, VertexBufferName);
            Gl.BindBuffer(BufferTarget.ElementArrayBuffer, IndexBufferName);

            uint attribPosition = (uint)Program.Attributes["aPosition"];

            Gl.EnableVertexAttribArray(attribPosition);
            Gl.VertexAttribPointer(attribPosition, 2, VertexAttribType.Float, false, Vertex.Size, (IntPtr)Vertex.PositionOffset);

            int uMvpMatrix = Program.Uniforms["uMvpMatrix"];

            Gl.UniformMatrix4(uMvpMatrix, false, MvpMatrix3D.RawData);

            if (Texture != null)
            {
                uint aTexCoords = (uint)Program.Attributes["aTexCoords"];
                Gl.EnableVertexAttribArray(aTexCoords);
                Gl.VertexAttribPointer(aTexCoords, 2, VertexAttribType.Float, false, Vertex.Size, (IntPtr)Vertex.TextureOffset);
                Gl.ActiveTexture(TextureUnit.Texture0);

                RenderUtil.SetSamplerStateAt(Texture.Base, Texture.NumMipMaps > 0, TextureSmoothing, TextureRepeat);
            }
            // color & alpha are set in subclasses
        }
Ejemplo n.º 25
0
        public override void OnLoad()
        {
            GameCore.TheGameCore.TheGameEventHandler += TheGameCore_TheGameEventHandler;

            theMap = TheGameStatus.TheMap;

            // create our shader program
            program = new ShaderProgram(VertexShader, FragmentShader);

            // set up the projection and view matrix
            program.Use();
            projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(TheRenderStatus.Fov, (float)Width / Height,
                                                                    TheRenderStatus.ZNear,
                                                                    TheRenderStatus.ZFar);
            program["projection_matrix"].SetValue(projectionMatrix);
//            program["model_matrix"].SetValue(Matrix4.Identity);
            program["light_direction"].SetValue(theEnvironment.LightDirection);
            program["enable_lighting"].SetValue(theEnvironment.Lighting);
            program["ambient"].SetValue(theEnvironment.LightAmbient);

            GenerateGeometry();
            GenerateArrayTexture();

            Gl.UseProgram(0);
            Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }
Ejemplo n.º 26
0
        private static void RenderFrame()
        {
            stopWatch.Stop();
            float pyramidDeltaTime = (float)stopWatch.ElapsedTicks / Stopwatch.Frequency * pyramidSpeed;
            float cubeDeltaTime    = (float)stopWatch.ElapsedTicks / Stopwatch.Frequency * cubeSpeed;

            stopWatch.Restart();

            pyramidAngle += pyramidDeltaTime;
            cubeAngle    += cubeDeltaTime;

            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            Gl.UseProgram(ShaderProgram);

            ShaderProgram["model_matrix"].SetValue(Matrix4.CreateRotationY(pyramidAngle * pyramidRodationSide) * Matrix4.CreateTranslation(new Vector3(-1.5f, 0, 0)));
            Gl.BindBufferToShaderAttribute(pyramid, ShaderProgram, "vertexPosition");
            Gl.BindBufferToShaderAttribute(pyramidColor, ShaderProgram, "vertexColor");
            Gl.BindBuffer(pyramidTriangles);

            Gl.DrawElements(BeginMode.Triangles, pyramidTriangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            ShaderProgram["model_matrix"].SetValue(Matrix4.CreateRotationY((cubeAngle / 2) * cubeRotationSide) * Matrix4.CreateRotationX(cubeAngle * cubeRotationSide) * Matrix4.CreateTranslation(new Vector3(1.5f, 0, 0)));
            Gl.BindBufferToShaderAttribute(cube, ShaderProgram, "vertexPosition");
            Gl.BindBufferToShaderAttribute(cubeColor, ShaderProgram, "vertexColor");
            Gl.BindBuffer(cubeQuads);

            Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Glut.glutSwapBuffers();
        }
Ejemplo n.º 27
0
        public void TestGenBuffer()
        {
            if (!HasVersion(1, 5) && !IsGlExtensionSupported("GL_ARB_vertex_buffer_object") && !HasEsVersion(1, 0))
            {
                Assert.Inconclusive("OpenGL 1.5 or GL_ARB_vertex_buffer_object not supported or OpenGL ES 1.0");
            }

            uint arrayBuffer = Gl.GenBuffer();

            try {
                Assert.AreNotEqual(0U, arrayBuffer, "Gl.GenBuffer failure");

                // It seems that on my system glIsBuffer returns true after glGenBuffer... anyone can confirm
                // Assert.IsFalse(Gl.IsBuffer(arrayBuffer));

                Gl.BindBuffer(BufferTarget.ArrayBuffer, arrayBuffer);
                Assert.IsTrue(Gl.IsBuffer(arrayBuffer));
            } finally {
                if (arrayBuffer != 0)
                {
                    Gl.DeleteBuffers(arrayBuffer);
                    Assert.IsFalse(Gl.IsBuffer(arrayBuffer), "Gl.DeleteBuffers failure");
                }
            }
        }
Ejemplo n.º 28
0
        private static void OnRenderFrame()
        {
            // calculate how much time has elapsed since the last frame
            watch.Stop();
            float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency;

            watch.Restart();

            // use the deltaTime to adjust the angle of the cube
            angle += deltaTime;

            // set up the OpenGL viewport and clear both the color and depth bits
            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // use our shader program and bind the crate texture
            Gl.UseProgram(program);
            Gl.BindTexture(crateTexture);

            // set the transformation of the cube
            program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle / 2) * Matrix4.CreateRotationX(angle));

            // bind the vertex positions, UV coordinates and element array
            Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV");
            Gl.BindBuffer(cubeQuads);

            // draw the textured cube
            Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Glut.glutSwapBuffers();
        }
Ejemplo n.º 29
0
        private static void OnRenderFrame()
        {
            // set up the OpenGL viewport and clear both the color and depth bits
            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // use our shader program
            Gl.UseProgram(program);

            // bind the vertex positions, colors and elements of the triangle
            program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(-1.5f, 0, 0)));
            Gl.BindBufferToShaderAttribute(triangle, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(triangleColor, program, "vertexColor");
            Gl.BindBuffer(triangleElements);

            // draw the triangle
            Gl.DrawElements(BeginMode.Triangles, triangleElements.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            // bind the vertex positions, colors and elements of the square
            program["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(1.5f, 0, 0)));
            Gl.BindBufferToShaderAttribute(square, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(squareColor, program, "vertexColor");
            Gl.BindBuffer(squareElements);

            // draw the square
            Gl.DrawElements(BeginMode.Quads, squareElements.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Glut.glutSwapBuffers();
        }
Ejemplo n.º 30
0
 public OpenGLIndexBuffer(object indices, uint count)
 {
     this.count = count;
     bufferID   = Gl.CreateBuffer();
     Gl.BindBuffer(BufferTarget.ElementArrayBuffer, bufferID);
     Gl.BufferData(BufferTarget.ElementArrayBuffer, count * sizeof(uint), indices, BufferUsage.StaticDraw);
 }