Пример #1
0
        public virtual void SetupVertexAttribs(IReadOnlyList <VertexFormatDescriptor> desc)
        {
            vao.Bind();

            uint vertexSize = 0;

            for (int count = desc.Count, i = 0; i < count; i++)
            {
                vertexSize += desc[i].ComponentCount * desc[i].ComponentSize;
            }

            uint index  = 0;
            uint offset = 0;

            for (int count = desc.Count, i = 0; i < count; i++)
            {
                var e = desc[i];

                uint type = uint.MaxValue;
                if (!e.IsFloat)
                {
                    if (e.ComponentSize == 4)
                    {
                        type = e.IsSigned ? GL_INT : GL_UNSIGNED_INT;
                    }
                    else if (e.ComponentSize == 2)
                    {
                        type = e.IsSigned ? GL_SHORT : GL_UNSIGNED_SHORT;
                    }
                    else if (e.ComponentSize == 1)
                    {
                        type = e.IsSigned ? GL_BYTE : GL_UNSIGNED_BYTE;
                    }
                }
                else
                {
                    if (e.ComponentSize == 4)
                    {
                        type = GL_FLOAT;
                    }
                    else if (e.ComponentSize == 8)
                    {
                        type = GL_DOUBLE;
                    }
                }
                Debug.Assert(type != uint.MaxValue);

                vao.SetVertexAttrib(index, vertexBuffer, (int)e.ComponentCount, (DataType)type, true, (int)vertexSize, offset);

                offset += e.ComponentSize * e.ComponentCount;
                index++;
            }
        }
Пример #2
0
        public override void Start()
        {
            this.EnableDraw(true); // set to be rendered

            map = new NoiseMap(0, size);

            vao = new VertexArray();
            vbo = GenVertices();
            vao.Bind(vbo, OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer);
            vao.AttributePointer(0, 3, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 6, 0);
            vao.AttributePointer(1, 3, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 6, sizeof(float) * 3);
            ebo = GenIndices();
            vao.Bind(ebo, OpenTK.Graphics.OpenGL4.BufferTarget.ElementArrayBuffer);
        }
Пример #3
0
        public override void Start()
        {
            base.Start();

            vbo = Primitive.Plane;
            ebo = Primitive.PlaneIndices;

            vao = new VertexArray();
            vao.Bind(vbo, OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer);
            vao.Bind(ebo, OpenTK.Graphics.OpenGL4.BufferTarget.ElementArrayBuffer);

            vao.AttributePointer(0, 3, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 8, 0);
            vao.AttributePointer(1, 3, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 8, sizeof(float) * 5);
            vao.AttributePointer(2, 2, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 8, sizeof(float) * 3);
        }
Пример #4
0
 public void DrawDirectionalLight(Vector3 eyePosition, DirectionalLight light)
 {
     _directionalProgram.Use();
     _directionalProgram.ModelViewProjectionMatrix.Set(Matrix4.Identity);
     _directionalProgram.EyePosition.Set(eyePosition);
     // set light properties
     _directionalProgram.LightDirection.Set(light.Direction);
     _directionalProgram.LightColor.Set(light.Color);
     _directionalProgram.AmbientIntensity.Set(light.AmbientIntensity);
     _directionalProgram.DiffuseIntensity.Set(light.DiffuseIntensity);
     _gbuffer.BindBuffers(_directionalProgram);
     // draw fullscreen quad
     _vaoFullScreenQuad.Bind();
     _vaoFullScreenQuad.DrawArrays(_quad.DefaultMode, 0, _quad.Vertices.Length);
 }
Пример #5
0
        public void Render(VertexArray vao, int indiceCount, RenderData data, IResourceProvider provider)
        {
            foreach (KeyValuePair <int, Texture> pair in textures) // Bind textures
            {
                pair.Value.Bind(pair.Key);
            }


            BindFrameBufferTextures(provider, true);
            {
                shader.Bind();
                {
                    SetUniformValues(data);

                    vao.Bind();
                    {
                        GL.DrawElements(PrimitiveType.Triangles, indiceCount, DrawElementsType.UnsignedInt, 0);
                    }
                    vao.Unbind();
                }
                shader.Unbind();
            }
            BindFrameBufferTextures(provider, false);


            foreach (Texture texture in textures.Values)
            {
                texture.Unbind();
            }
        }
Пример #6
0
        public override void Draw(float time)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            _time += goBack ? -time : time;

            Lamp.Shader.Use();
            Lamp.Shader.SetMatrix4("model", Matrix4.Identity);
            Lamp.Shader.SetMatrix4("view", Camera.View);
            Lamp.Shader.SetMatrix4("projection", Camera.Projection);
            Lamp.Shader.SetVector3("objectColor", Lamp.Position);
            Lamp.Shader.SetVector3("lightColor", new Vector3(_time));
            Lamp.Shader.SetFloat("time", _time);
            Lamp.Shader.SetVector3("viewPos", Camera.Position);
            Lamp.Shader.SetVector3("lightPos", Lamp.Position);
            Lamp.Bind();
            GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            _modelShader.Use();
            var lampMatrix = Matrix4.Identity;

            lampMatrix *= Matrix4.CreateScale(0.5f);
            lampMatrix *= Matrix4.CreateTranslation(Lamp.Position) * Matrix4.CreateRotationY((Lamp.Position * _time).X);

            _modelShader.SetMatrix4("model", lampMatrix);
            _modelShader.SetMatrix4("view", Camera.View);
            _modelShader.SetMatrix4("projection", Camera.Projection);
            _modelVao.Bind();
            GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            if (_time >= 360.0f || _time < 0.0f)
            {
                goBack = !goBack;
            }
            base.Draw(time);
        }
Пример #7
0
 private void OnLoad(object sender, EventArgs e)
 {
     // initialize shader
     _program = ProgramFactory.Create<SkyboxProgram>();
     // initialize cube shape
     _cube = new Cube();
     _cube.UpdateBuffers();
     // initialize vertex array and attributes
     _vao = new VertexArray();
     _vao.Bind();
     _vao.BindAttribute(_program.InPosition, _cube.VertexBuffer);
     _vao.BindElementBuffer(_cube.IndexBuffer);
     // create cubemap texture and load all faces
     for (var i = 0; i < 6; i++)
     {
         using (var bitmap = new Bitmap(string.Format("Data/Textures/city{0}.jpg", i)))
         {
             bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
             if (_skybox == null) BitmapTexture.CreateCompatible(bitmap, out _skybox, 1);
             _skybox.LoadBitmap(bitmap, i);
         }
     }
     // activate shader and bind texture to it
     _program.Use();
     _program.Texture.BindTexture(TextureUnit.Texture0, _skybox);
     // enable seamless filtering to reduce artifacts at the edges of the cube faces
     GL.Enable(EnableCap.TextureCubeMapSeamless);
     // cull front faces because we are inside the cube
     // this is not really necessary but removes some artifacts when the user leaves the cube
     // which should be impossible for a real skybox, but in this demonstration it is possible by zooming out
     GL.Enable(EnableCap.CullFace);
     GL.CullFace(CullFaceMode.Front);
     // set a nice clear color
     GL.ClearColor(Color.MidnightBlue);
 }
Пример #8
0
 private void OnLoad(object sender, EventArgs e)
 {
     // maximize window
     WindowState = WindowState.Maximized;
     // load program
     _programOdd   = ProgramFactory.Create <GeodesicProgramOdd>();
     _programEqual = ProgramFactory.Create <GeodesicProgram>();
     _program      = _programOdd;
     // create icosahedron and set model matrix
     _modelMatrix = Matrix4.CreateScale(1);
     _icosahedron = new Icosahedron(5);
     _icosahedron.UpdateBuffers();
     // bind it to an vao
     _vao = new VertexArray();
     _vao.Bind();
     _vao.BindElementBuffer(_icosahedron.IndexBuffer);
     _vao.BindAttribute(_program.Position, _icosahedron.VertexBuffer);
     // set some reasonable default state
     GL.ClearColor(Color4.Black);
     GL.Enable(EnableCap.DepthTest);
     // backface culling is done in the tesselation control shader
     GL.Enable(EnableCap.CullFace);
     GL.CullFace(CullFaceMode.Back);
     GL.PatchParameter(PatchParameterInt.PatchVertices, 3);
     // lighting stuff
     _deferredRenderer = new DeferredRenderer();
     // enable controls
     _variableHandler.Enable(this);
 }
Пример #9
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create <ExampleProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create vertices for a triangle
            var vertices = new[] { new Vector3(-1, -1, 0), new Vector3(1, -1, 0), new Vector3(0, 1, 0) };

            // create buffer object and upload vertex data
            _vbo = new Buffer <Vector3>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();
            // set up binding of the shader variable to the buffer object
            _vao.BindAttribute(_program.InPosition, _vbo);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0, 0, 3);
            Camera.ResetToDefault();

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
Пример #10
0
        /*
         * public static Program GenerateProgram(Dictionary<ShaderType, Shader.Shader> shaderList)
         * {
         *  Program program = new Program(shaderList);
         *  shaderList.Clear();
         *  return program;
         * } //for each group of shaders, put that into a loop within some xml loading function, xml passed from Main
         */

        public static void Draw()
        {
            //todo: everything, clean up
            //this is going to consist of several other methods, skybox pass, normal pass, hud pass, post process pass etc
            //TODO: Generalize, right now this function is used for testing.
            GL.ClearColor(OpenTK.Color.Aqua);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            //currentProgram.Use();
            //foreach vao
            //something to segregate shaders and buffers
            context.ProgramList["default"].Use();
            OpenTK.Matrix4 model, view, projection;
            model      = OpenTK.Matrix4.Identity;//OpenTK.Matrix4.CreateTranslation(15.0f, 0.0f, 0.0f);
            view       = OpenTK.Matrix4.Identity;
            projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView(1.7f, 1.67f, 0.1f, 100.0f);

            context.ProgramList["default"].SetAttribute("model", model);
            context.ProgramList["default"].SetAttribute("view", view);

            context.ProgramList["default"].SetAttribute("projection", projection);

            currentVAO.Bind();
            GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
            currentVAO.Unbind();
        }
Пример #11
0
        private void CreateBuffers()
        {
            _dataSpecification = new BufferDataSpecification
            {
                Count              = 2,
                Name               = "in_position",
                Offset             = 0,
                ShouldBeNormalised = false,
                Stride             = 0,
                Type               = VertexAttribPointerType.Float
            };

            _vertexArray = new VertexArray {
                DrawPrimitiveType = PrimitiveType.Triangles
            };
            _vertexArray.Bind();

            var size = 3 * 2 * sizeof(float);

            _vertexBuffer = new VertexBuffer
            {
                BufferUsage     = BufferUsageHint.StreamDraw,
                DrawableIndices = 3,
                MaxSize         = size
            };
            _vertexBuffer.Bind();
            _vertexBuffer.Initialise();
            _vertexBuffer.DataSpecifications.Add(_dataSpecification);

            _vertexArray.Load(_shaderProgram, _vertexBuffer);
            _vertexArray.UnBind();
        }
Пример #12
0
        protected override void OnLoad(EventArgs e)
        {
            prog = new ShaderProgram(Shader.FromFile(vertPath), Shader.FromFile(fragPath));

            textureWall      = new Texture(System.Drawing.Image.FromFile("Data/wall.jpg"), 0, "wall");
            textureContainer = new Texture(System.Drawing.Image.FromFile("Data/container2.png"), 1, "container");



            vbo = new VertexBuffer <float>();
            vbo.Bind();
            vbo.BufferData(vertices);


            vao = new VertexArray();
            vao.Bind();

            ibo = new IndexBuffer();
            ibo.Bind();
            ibo.BufferData(indices);

            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5 * 4, 0);
            GL.EnableVertexAttribArray(0);
            GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5 * 4, 3 * 4);
            GL.EnableVertexAttribArray(1);

            vao.Unbind();
            ibo.Unbind();
            vbo.Unbind();
            prog.Use();

            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
        }
Пример #13
0
        public void CreateBuffers()
        {
            if (!BufferInitialized)
            {
                Vao               = new VertexArray();
                IndexBuffer       = new Buffer <int>();
                VertexBuffer      = new Buffer <T>();
                BufferInitialized = true;

                Vao.Bind();
                Vao.BindElementBuffer(IndexBuffer);

                if (TempIndices.Count > 0)
                {
                    IndexBuffer.Init(BufferTarget.ElementArrayBuffer, TempIndices.ToArray());
                }

                if (TempVertices.Count > 0)
                {
                    VertexBuffer.Init(BufferTarget.ArrayBuffer, TempVertices.ToArray());
                }

                TempIndices.Clear();
                TempVertices.Clear();
            }
        }
Пример #14
0
        public static void RenderElements()
        {
            UIShader.Use();
            UIShader.Projection.Set(ProjectionMatrix);

            VAO.Bind();
            VBO.Init(OpenTK.Graphics.OpenGL.BufferTarget.ArrayBuffer, VertexList.ToArray());

            foreach (var spriteGroup in SpritesToRender.GroupBy(x => x.Texture))
            {
                spriteGroup.Key.Bind(OpenTK.Graphics.OpenGL.TextureUnit.Texture1);
                UIShader.Texture.BindTexture(OpenTK.Graphics.OpenGL.TextureUnit.Texture1, spriteGroup.Key);

                foreach (var sprite in spriteGroup)
                {
                    UIShader.Opacity.Set(sprite.Opacity);
                    VAO.DrawArrays(OpenTK.Graphics.OpenGL.PrimitiveType.Quads, sprite.Offset, sprite.ElemCount);
                }
            }

            if (Freetype6Loaded)
            {
                TextRenderer.RefreshBuffers();
                TextRenderer.Draw();
                TextRenderer.DisableShader();
            }
        }
Пример #15
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create<ExampleProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create vertices for a triangle
            var vertices = new[] { new Vector3(-1,-1,0), new Vector3(1,-1,0), new Vector3(0,1,0) };

            // create buffer object and upload vertex data
            _vbo = new Buffer<Vector3>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();
            // set up binding of the shader variable to the buffer object
            _vao.BindAttribute(_program.InPosition, _vbo);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0,0,3);
            Camera.ResetToDefault();

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
Пример #16
0
        private void GenerateMesh(int width, int height)
        {
            if (_initialized)
            {
                Dispose();
            }

            _sampler = new Sampler();
            _sampler.SetWrapMode(TextureWrapMode.Clamp);

            _program = ProgramFactory.Create <SpriteShaderProgram>();

            var w = width / 2;
            var h = height / 2;

            var vertices = new[] {
                new Vertex(-w, h, 0, 0, 0),
                new Vertex(w, h, 0, 1, 0),
                new Vertex(-w, -h, 0, 0, 1),
                new Vertex(w, -h, 0, 1, 1)
            };

            _vbo = new Buffer <Vertex>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            _vao = new VertexArray();
            _vao.Bind();
            _vao.BindAttribute(_program.InPosition, _vbo);
            _vao.BindAttribute(_program.InTexCoord, _vbo, 12);
            _initialized = true;
        }
        public override void Draw(float time)
        {
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            Lamp.Shader.Use();
            _diffuseMap.Bind(0);
            Lamp.Shader.SetInt("material.diffuse", 0);
            _specularMap.Bind(1);
            Lamp.Shader.SetInt("material.specular", 1);

            Lamp.Shader.SetMatrix4("model", Matrix4.Identity);
            Lamp.Shader.SetMatrix4("view", Camera.View);
            Lamp.Shader.SetMatrix4("projection", Camera.Projection);
            Lamp.Shader.SetVector3("light.position", Lamp.Position);
            Lamp.Shader.SetVector3("light.ambient", new Vector3(0.2f));
            Lamp.Shader.SetVector3("light.diffuse", new Vector3(.5f));
            Lamp.Shader.SetVector3("light.specular", new Vector3(1.0f));
            Lamp.Shader.SetVector3("viewPos", Camera.Position);

            Lamp.Bind();

            GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            _modelShader.Use();
            var lampMatrix = Matrix4.Identity;

            lampMatrix *= Matrix4.CreateScale(0.2f);
            lampMatrix *= Matrix4.CreateTranslation(Lamp.Position);

            _modelShader.SetMatrix4("model", lampMatrix);
            _modelShader.SetMatrix4("view", Camera.View);
            _modelShader.SetMatrix4("projection", Camera.Projection);
            _modelVao.Bind();
            GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            base.Draw(time);
        }
Пример #18
0
        public void Render(Matrix4 viewMatrix, Matrix4 viewProjectionMatrix)
        {
            SetDefaultMaterialParameter(ref Material, this.GameObject.LocalToWorldMatrix, viewMatrix, viewProjectionMatrix, GameObject.NormalMatrix);

            vertexBuffer.Bind();
            vertexBuffer.BufferData();

            vertexArray.Bind();

            indexBuffer.Bind();
            indexBuffer.BufferData();

            GL.DrawElements(BeginMode.Triangles, indexBuffer.Count, DrawElementsType.UnsignedShort, 0);

            foreach (var renderer in subMeshRenderers)
            {
                renderer.Render(viewMatrix, viewProjectionMatrix);
            }

            // reset state for potential further draw calls (optional, but good practice)
            vertexArray.Reset();
            vertexBuffer.Reset();
            indexBuffer.Reset();
            Material.CleanUp();
        }
Пример #19
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            // set up viewport
            GL.Viewport(0, 0, Size.X, Size.Y);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            SetupPerspective();

            // determinate object view rotation vectors and apply them
            _objectView = _baseView;
            var rotation = _rotateVectors[_rotateIndex];

            if (rotation != Vector3.Zero)
            {
                _objectView *= Matrix4.CreateFromAxisAngle(_rotateVectors[_rotateIndex], (float)(_stopwatch.Elapsed.TotalSeconds * 1.0));
            }

            // set transformation matrix
            _textureProgram.Use();
            _textureProgram.ModelViewProjectionMatrix.Set(_objectView * ModelView * Projection);

            // render cube with texture
            _cubeVao.Bind();
            _cubeVao.DrawArrays(_cube.DefaultMode, 0, _cube.VertexBuffer.ElementCount);

            // swap buffers
            SwapBuffers();
        }
Пример #20
0
        protected override void OnLoad()
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create <GravityProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();

            // create and bind transform feedback object
            _feedback = new TransformFeedback();
            _feedback.Bind();

            // Writing to a buffer while reading from it is not allowed
            // so we need two buffer objects here, which can be achieved by using the BufferPod<T> type.
            // It contains two buffers, Ping and Pong, to simplify this process.
            _buffers = new BufferPod <Particle>();
            InitializeParticles(_particleCount);

            // enable point sprite rendering
            GL.Enable(EnableCap.PointSprite);
            // enable modification of the point sprite size from the program (vertex shader in this case)
            GL.Enable(EnableCap.ProgramPointSize);
            // enable depth testing
            GL.Enable(EnableCap.DepthTest);
            // set a nice clear color
            GL.ClearColor(Color.Black);

            // set a nice camera angle
            Camera.DefaultState.Position = new Vector3(0, 2, -8);
            Camera.ResetToDefault();
        }
Пример #21
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            t += (float)e.Time;

            GL.ClearColor(0.1f, 0.1f, 0.1f, 1.0f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            prog.Use();


            textureWall.ActivateTextureUnit();
            textureWall.Bind();
            GL.Uniform1(prog.GetUniformLoc("ourTexture1"), textureWall.TextureUnitAsInt);

            textureContainer.ActivateTextureUnit();
            textureContainer.Bind();
            GL.Uniform1(prog.GetUniformLoc("ourTexture2"), textureContainer.TextureUnitAsInt);


            vao.Bind();
            GL.DrawElements(BeginMode.Triangles, 6, DrawElementsType.UnsignedInt, 0);


            vao.Unbind();

            this.SwapBuffers();
        }
Пример #22
0
        /// <summary>
        /// Draws all the entities
        /// </summary>
        /// <param name="cameraMatrix"></param>
        private void DrawEntities(Matrix4f cameraMatrix)
        {
            uint currentIndicieCount = 0;

            foreach (IRenderable comp in renderComponents)
            {
                uint quadsCount = (uint)(comp.Vertices.Length / 4);

                if (!comp.Enabled || !comp.Entity.Enabled)
                {
                    currentIndicieCount += quadsCount * 6 * sizeof(int);
                    continue;
                }

                // Set Model view perspective
                Matrix4f mvp = cameraMatrix * comp.Entity.Transform.GetMatrix();

                testShader.SetUniformM4("MVP", mvp);

                testShader.Bind();
                VertexArray.Bind();
                IndexBuffer.Bind();

                for (int i = 0; i < quadsCount; i++)
                {
                    Gl.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, (IntPtr)(currentIndicieCount + (i * 6 * sizeof(int))));
                }

                IndexBuffer.Unbind();
                VertexArray.Unbind();
                testShader.Unbind();

                currentIndicieCount += quadsCount * 6 * sizeof(int);
            }
        }
Пример #23
0
        private void InitialiseRendering()
        {
            _dataSpecification = new BufferDataSpecification
            {
                Count              = 2,
                Name               = "in_position",
                Offset             = 0,
                ShouldBeNormalised = false,
                Stride             = 0,
                Type               = VertexAttribPointerType.Float,
                SizeInBytes        = sizeof(float)
            };

            _vertexArray = new VertexArray {
                DrawPrimitiveType = PrimitiveType.Triangles
            };
            _vertexArray.Bind();

            _vertexBuffer = new VertexBuffer
            {
                BufferUsage        = BufferUsageHint.StreamDraw,
                DrawableIndices    = _sides.Count(b => b) * 6 * 3,
                MaxDrawableIndices = _sides.Count(b => b) * 6 * 3
            };
            _vertexBuffer.AddSpec(_dataSpecification);
            _vertexBuffer.CalculateMaxSize();
            _vertexBuffer.Bind();
            _vertexBuffer.Initialise();

            _vertexArray.Load(_shaderProgram, _vertexBuffer);
            _vertexArray.UnBind();
        }
Пример #24
0
        public override void Setup()
        {
            GL.Enable(EnableCap.DepthTest);
            GL.ClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            var vertexAttributes = new VertexAttribute[] {
                new VertexAttribute("aPosition", 3, VertexAttribPointerType.Float, ColoredTexturedVertex.Size, 0)
            };
            var vbo = VertexBuffer.CreateVertexBuffer();

            vbo.LoadData(CubeVertices());
            _modelVao = VertexArray.CreateVertexArray();
            _modelVao.Bind();

            _modelShader = ShaderProgram.CreateShaderProgram("./Assets/Shaders/vertex.vert", "./Assets/Shaders/fragment.frag", vertexAttributes);
            _modelShader.Use();
            _modelShader.SetVertexAttributes();

            var lamp = Light.CreateLight();

            lamp.Bind();
            var lampShader = ShaderProgram.CreateShaderProgram("./Assets/Shaders/vertex.vert", "./Assets/Shaders/lighting.frag", vertexAttributes);

            lampShader.Use();
            lampShader.SetVertexAttributes();
            lamp.BindBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer, vbo.Id);
            lamp.Position     = new Vector3(1.2f, 1.0f, 2.0f);
            lamp.Shader       = lampShader;
            lamp.VertexBuffer = vbo;
            Lamp = lamp;
        }
Пример #25
0
 public void Draw(VertexArray VAO, int first, int count)
 {
     if (!VAO.IsBinded)
     {
         VAO.Bind();
     }
     OpenGL.DrawArrays(PrimitiveType.Triangles, first, count);
 }
Пример #26
0
    public void Draw(VertexArray va, IndexBuffer ib, Shader shader)
    {
        va.Bind();
        ib.Bind();
        shader.Bind();

        GL.DrawElements(PrimitiveType.Triangles, ib.GetCount(), DrawElementsType.UnsignedInt, IntPtr.Zero);
    }
Пример #27
0
 public Mesh(float[] b)
 {
     Count = b.Length;
     vbo   = b;
     vao.Bind(vbo, OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer);
     vao.AttributePointer(0, 3, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 6, 0);
     vao.AttributePointer(1, 3, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Float, false, sizeof(float) * 6, sizeof(float) * 3);
 }
Пример #28
0
 public static void InitializeBuffers()
 {
     VAO = new VertexArray();
     VBO = new Buffer <VertVT>();
     VAO.Bind();
     VAO.BindAttribute(UIShader.Position, VBO);
     VAO.BindAttribute(UIShader.TexCoord, VBO, 12);
 }
Пример #29
0
        public void DrawElements(VertexArray VAO, int count, int offset = 0)
        {
            if (!VAO.IsBinded)
            {
                VAO.Bind();
            }

            OpenGL.DrawElements(PrimitiveType.Triangles, count, DrawElementsType.UnsignedInt, offset);
        }
Пример #30
0
 public DeferredRenderer()
 {
     _directionalProgram = ProgramFactory.Create <DirectionalLightProgram>();
     _pointProgram       = ProgramFactory.Create <PointLightProgram>();
     _quad = new Quad();
     _quad.UpdateBuffers();
     _vaoFullScreenQuad = new VertexArray();
     _vaoFullScreenQuad.Bind();
     _vaoFullScreenQuad.BindAttribute(_directionalProgram.Position, _quad.VertexBuffer);
 }
Пример #31
0
        public void Draw()
        {
            _shader.Enable();

            _vertexArray.Bind();
            GL.DrawArrays(PrimitiveType.Quads, 0, Constants.VERTICES_PER_OBJECT * _renderablesToDraw.Count);
            _vertexArray.Unbind();

            _shader.Disable();
        }
Пример #32
0
        public static void Submit(ShaderProgram shader, VertexArray vertexArray, Matrix4 transform)
        {
            shader.Bind();
            shader.UploadUniformMatrix("u_ViewProjection", _viewProjectionMatrix);
            shader.UploadUniformMatrix("u_Transform", transform);
            shader.UploadUniformFloat4("u_color", new Vector4(1.0f));

            vertexArray.Bind();
            RenderCommand.DrawIndexed(vertexArray);
        }
Пример #33
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize and bind framebuffer
            _framebuffer = new Framebuffer();
            _framebuffer.Bind(FramebufferTarget.Framebuffer);

            // initialize a renderbuffer and bind it to the depth attachment
            // to support depth testing while rendering to the texture
            _depthBuffer = new Renderbuffer();
            _depthBuffer.Init(RenderbufferStorage.DepthComponent, FramebufferWidth, FramebufferHeight);
            _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, _depthBuffer);

            // initialize texture and bind it to the color attachment
            _texture = new Texture2D(SizedInternalFormat.Rgba8, FramebufferWidth, FramebufferHeight, 1);
            _framebuffer.Attach(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, _texture);
            Framebuffer.Unbind(FramebufferTarget.Framebuffer);

            // initialize demonstration geometry
            _cube = new ColorCube();
            _cube.UpdateBuffers();
            _quad = new TexturedQuad();
            _quad.UpdateBuffers();

            // initialize shaders
            _colorProgram = ProgramFactory.Create<SimpleColorProgram>();
            _textureProgram = ProgramFactory.Create<SimpleTextureProgram>();

            // set up vertex attributes for the cube
            _cubeVao = new VertexArray();
            _cubeVao.Bind();
            _cubeVao.BindAttribute(_colorProgram.InPosition, _cube.VertexBuffer);
            _cubeVao.BindAttribute(_colorProgram.InColor, _cube.ColorBuffer);
            _cubeVao.BindElementBuffer(_cube.IndexBuffer);

            // set up vertex attributes for the quad
            _quadVao = new VertexArray();
            _quadVao.Bind();
            _quadVao.BindAttribute(_textureProgram.InPosition, _quad.VertexBuffer);
            _quadVao.BindAttribute(_textureProgram.InTexCoord, _quad.TexCoordBuffer);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0,0,3);
            Camera.ResetToDefault();

            // enable depth testing
            GL.Enable(EnableCap.DepthTest);
        }
Пример #34
0
 protected void OnLoad(object sender, EventArgs e)
 {
     // load textures into array
     for (var i = 0; i < _stateTextures.Length; i++)
     {
         using (var bitmap = new Bitmap(Path.Combine("Data/Textures/", _stateTextures[i])))
         {
             bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
             if (_textureArray == null) BitmapTexture.CreateCompatible(bitmap, out _textureArray, _stateTextures.Length, 1);
             _textureArray.LoadBitmap(bitmap, i);
         }
     }
     // initialize buffer
     var field = new Minefield[FieldWidth*FieldHeight];
     for (var i = 0; i < field.Length; i++)
     {
         field[i] = new Minefield(i%FieldWidth, i/FieldHeight, i%_stateTextures.Length);
     }
     _buffer = new Buffer<Minefield>();
     _buffer.Init(BufferTarget.ArrayBuffer, field);
     // load program
     _gridProgram = ProgramFactory.Create<TextureGridProgram>();
     _gridProgram.Use();
     // bind the texture and set uniform
     _gridProgram.TextureData.BindTexture(TextureUnit.Texture0, _textureArray);
     // set up vertex array and attributes
     _vao = new VertexArray();
     _vao.Bind();
     _vao.BindAttribute(_gridProgram.InPosition, _buffer);
     _vao.BindAttribute(_gridProgram.InTexture, _buffer, 8);
     // set nice clear color
     GL.ClearColor(Color.MidnightBlue);
     // initialize camera position
     Camera.DefaultState.Position = new Vector3(0, 5, 15);
     Camera.ResetToDefault();
 }
        private void OnLoad(object sender, EventArgs e)
        {
            // load texture from file
            using (var bitmap = new Bitmap("Data/Textures/checker.jpg"))
            {
                BitmapTexture.CreateCompatible(bitmap, out _texture);
                _texture.LoadBitmap(bitmap);
            }
            _texture.GenerateMipMaps();

            // initialize sampler
            _sampler = new Sampler();
            _sampler.SetWrapMode(TextureWrapMode.Repeat);

            // create vertex data for a big plane
            const int a = 10;
            const int b = 10;
            var vertices = new[]
            {
                new Vertex(-a, 0,-a, 0, 0),
                new Vertex( a, 0,-a, b, 0),
                new Vertex(-a, 0, a, 0, b),
                new Vertex( a, 0, a, b, b)
            };

            // create buffer object and upload vertex data
            _vbo = new Buffer<Vertex>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // initialize shader
            _program = ProgramFactory.Create<SimpleTextureProgram>();
            // activate shader program
            _program.Use();
            // bind sampler
            _sampler.Bind(TextureUnit.Texture0);
            // bind texture
            _program.Texture.BindTexture(TextureUnit.Texture0, _texture);
            // which is equivalent to
            //_program.Texture.Set(TextureUnit.Texture0);
            //_texture.Bind(TextureUnit.Texture0);

            // set up vertex array and attributes
            _vao = new VertexArray();
            _vao.Bind();
            // memory layout of our data is XYZUVXYZUV...
            // the buffer abstraction knows the total size of one "pack" of vertex data
            // and if a vertex attribute is bound without further arguments the first N elements are taken from each pack
            // where N is provided via the VertexAttribAttribute on the program property:
            _vao.BindAttribute(_program.InPosition, _vbo);
            // if data should not be taken from the start of each pack, the offset must be given in bytes
            // to reach the texture coordinates UV the XYZ coordinates must be skipped, that is 3 floats, i.e. an offset of 12 bytes is needed
            _vao.BindAttribute(_program.InTexCoord, _vbo, 12);
            // if needed all the available arguments can be specified manually, e.g.
            //_vao.BindAttribute(_program.InTexCoord, _vbo, 2, VertexAttribPointerType.Float, Marshal.SizeOf(typeof(Vertex)), 12, false);

            // set default camera
            Camera.DefaultState.Position = new Vector3(0, 0.5f, 3);
            Camera.ResetToDefault();

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
Пример #36
0
        protected void OnLoad(object sender, EventArgs eventArgs)
        {
            VSync = VSyncMode.Off;

            // Check for necessary capabilities:
            var extensions = GL.GetString(StringName.Extensions);
            if (!GL.GetString(StringName.Extensions).Contains("GL_ARB_shading_language"))
            {
                throw new NotSupportedException(String.Format("This example requires OpenGL 2.0. Found {0}. Aborting.",
                    GL.GetString(StringName.Version).Substring(0, 3)));
            }

            if (!extensions.Contains("GL_ARB_texture_compression") ||
                 !extensions.Contains("GL_EXT_texture_compression_s3tc"))
            {
                throw new NotSupportedException("This example requires support for texture compression. Aborting.");
            }

            var temp = new int[1];
            GL.GetInteger(GetPName.MaxTextureImageUnits, out temp[0]);
            Trace.WriteLine(temp[0] + " TMU's for Fragment Shaders found. (2 required)");

            GL.GetInteger(GetPName.MaxVaryingFloats, out temp[0]);
            Trace.WriteLine(temp[0] + " varying floats between VS and FS allowed. (6 required)");

            GL.GetInteger(GetPName.MaxVertexUniformComponents, out temp[0]);
            Trace.WriteLine(temp[0] + " uniform components allowed in Vertex Shader. (6 required)");

            GL.GetInteger(GetPName.MaxFragmentUniformComponents, out temp[0]);
            Trace.WriteLine(temp[0] + " uniform components allowed in Fragment Shader. (11 required)");
            Trace.WriteLine("");

            // load textures
            TextureLoaderParameters.MagnificationFilter = TextureMagFilter.Linear;
            TextureLoaderParameters.MinificationFilter = TextureMinFilter.LinearMipmapLinear;
            TextureLoaderParameters.WrapModeS = TextureWrapMode.ClampToBorder;
            TextureLoaderParameters.WrapModeT = TextureWrapMode.ClampToBorder;
            TextureLoaderParameters.EnvMode = TextureEnvMode.Modulate;

            uint handle;
            TextureTarget target;
            ImageDDS.LoadFromDisk(TextureDiffuseHeightFilename, out handle, out target);
            _textureDiffuseHeight = TextureFactory.AquireTexture2D((int) handle);
            Trace.WriteLine("Loaded " + TextureDiffuseHeightFilename + " with handle " + handle + " as " + target);

            ImageDDS.LoadFromDisk(TextureNormalGlossFilename, out handle, out target);
            _textureNormalGloss = TextureFactory.AquireTexture2D((int) handle);
            Trace.WriteLine("Loaded " + TextureNormalGlossFilename + " with handle " + handle + " as " + target);

            Trace.WriteLine("End of Texture Loading. GL Error: " + GL.GetError());
            Trace.WriteLine("");

            // initialize buffer
            var normal = Vector3.UnitZ;
            var tangent = Vector3.UnitX;
            var vertices = new[]
            {
                new Vertex
                {
                    Position = new Vector3(-1,-1,0),
                    TexCoord = new Vector2(0,0),
                    Normal = normal,
                    Tangent = tangent
                },
                new Vertex
                {
                    Position = new Vector3(1,-1,0),
                    TexCoord = new Vector2(1,0),
                    Normal = normal,
                    Tangent = tangent
                },
                new Vertex
                {
                    Position = new Vector3(-1,1,0),
                    TexCoord = new Vector2(0,1),
                    Normal = normal,
                    Tangent = tangent
                },
                new Vertex
                {
                    Position = new Vector3(1,1,0),
                    TexCoord = new Vector2(1,1),
                    Normal = normal,
                    Tangent = tangent
                }
            };
            _buffer = new Buffer<Vertex>();
            _buffer.Init(BufferTarget.ArrayBuffer, vertices);

            // load shader
            _program = ProgramFactory.Create<ParallaxProgram>();
            _program.Use();

            // set up vertex array
            _vao = new VertexArray();
            _vao.Bind();
            // bind vertex attributes
            // the buffer layout is defined by the Vertex struct:
            //   data X Y Z NX NY NZ TX TY TZ  U  V *next vertex*
            // offset 0 4 8 12 16 20 24 28 32 36 40      44
            // having to work with offsets could be prevented by using seperate buffer objects for each attribute,
            // but that might reduce performance and can get annoying as well.
            // performance increase could also be achieved by improving coherent read access
            // by padding the struct so that each attribute begins at a multiple of 16 bytes, i.e. 4-floats
            // because the GPU can then read all 4 floats at once. I did not do that here to keep it simple.
            _vao.BindAttribute(_program.InPosition, _buffer);
            _vao.BindAttribute(_program.InNormal, _buffer, 12);
            _vao.BindAttribute(_program.InTangent, _buffer, 24);
            _vao.BindAttribute(_program.InTexCoord, _buffer, 36);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0,0,3);
            Camera.ResetToDefault();

            // set state
            GL.ClearColor(0.2f, 0f, 0.4f, 0f);
            GL.PointSize(10f);
            GL.Disable(EnableCap.Dither);
            GL.FrontFace(FrontFaceDirection.Ccw);
            GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill);
            GL.PolygonMode(MaterialFace.Back, PolygonMode.Line);
        }
Пример #37
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create<GravityProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();

            // create and bind transform feedback object
            _feedback = new TransformFeedback();
            _feedback.Bind();

            // Writing to a buffer while reading from it is not allowed
            // so we need two buffer objects here, which can be achieved by using the BufferPod<T> type.
            // It contains two buffers, Ping and Pong, to simplify this process.
            _buffers = new BufferPod<Particle>();
            InitializeParticles(_particleCount);

            // enable point sprite rendering
            GL.Enable(EnableCap.PointSprite);
            // enable modification of the point sprite size from the program (vertex shader in this case)
            GL.Enable(EnableCap.ProgramPointSize);
            // enable depth testing
            GL.Enable(EnableCap.DepthTest);
            // set a nice clear color
            GL.ClearColor(Color.Black);

            // set a nice camera angle
            Camera.DefaultState.Position = new Vector3(0,2,-8);
            Camera.ResetToDefault();
        }