static void Main(string[] args)
        {
            // create an OpenGL window
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            // provide the Glut callbacks that are necessary for running this tutorial
            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);
            Glut.glutCloseFunc(OnClose);

            // compile the shader program
            program = new ShaderProgram(VertexShader, FragmentShader);

            // set the view and projection matrix, which are static throughout this tutorial
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up));

            // create a triangle
            triangle = new VBO<Vector3>(new Vector3[] { new Vector3(0, 1, 0), new Vector3(-1, -1, 0), new Vector3(1, -1, 0) });
            triangleElements = new VBO<int>(new int[] { 0, 1, 2 }, BufferTarget.ElementArrayBuffer);

            // create a square
            square = new VBO<Vector3>(new Vector3[] { new Vector3(-1, 1, 0), new Vector3(1, 1, 0), new Vector3(1, -1, 0), new Vector3(-1, -1, 0) });
            squareElements = new VBO<int>(new int[] { 0, 1, 2, 3 }, BufferTarget.ElementArrayBuffer);

            Glut.glutMainLoop();
        }
Beispiel #2
0
 public FontVAO(ShaderProgram program, VBO<Vector3> vertices, VBO<Vector2> uvs, VBO<int> triangles)
 {
     this.program = program;
     this.vertices = vertices;
     this.uvs = uvs;
     this.triangles = triangles;
 }
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            Gl.Disable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            program = new ShaderProgram(VertexShader, FragmentShader);

            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up));

            program["light_direction"].SetValue(new Vector3(0, 0, 1));
            program["enable_lighting"].SetValue(lighting);

            glassTexture = new Texture("glass.bmp");

            cube = new VBO<Vector3>(new Vector3[] {
                new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1),         // top
                new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(1, -1, -1),     // bottom
                new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),         // front face
                new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1),     // back face
                new Vector3(-1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1),     // left
                new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(1, -1, -1) });      // right
            cubeNormals = new VBO<Vector3>(new Vector3[] {
                new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), 
                new Vector3(0, -1, 0), new Vector3(0, -1, 0), new Vector3(0, -1, 0), new Vector3(0, -1, 0), 
                new Vector3(0, 0, 1), new Vector3(0, 0, 1), new Vector3(0, 0, 1), new Vector3(0, 0, 1), 
                new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1), new Vector3(0, 0, -1), 
                new Vector3(-1, 0, 0), new Vector3(-1, 0, 0), new Vector3(-1, 0, 0), new Vector3(-1, 0, 0), 
                new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0) });
            cubeUV = new VBO<Vector2>(new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) });

            cubeQuads = new VBO<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }, BufferTarget.ElementArrayBuffer);


            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
		/// <summary>
		/// Draw the attributes of this vertex array.
		/// </summary>
		/// <param name="ctx">
		/// The <see cref="GraphicsContext"/> used for rendering.
		/// </param>
		/// <param name="shader">
		/// The <see cref="ShaderProgram"/> used for drawing the vertex arrays.
		/// </param>
		public virtual void Draw(GraphicsContext ctx, ShaderProgram shader)
		{
			CheckThisExistence(ctx);

			if (shader != null && shader.Exists(ctx) == false)
				throw new ArgumentException("not existing", "shader");

			// If vertex was modified after creation, don't miss to create array buffers
			if (_VertexArrayDirty) CreateObject(ctx);

			// Set vertex arrays
			SetVertexArrayState(ctx, shader);
			
			// Fixed or programmable pipeline?
			if     ((shader == null) && (ctx.Caps.GlExtensions.VertexShader_ARB == true))
				ShaderProgram.Unbind(ctx);
			else if (shader != null)
				shader.Bind(ctx);

			// Issue rendering using shader
			foreach (Element attributeElement in DrawElements) {
				if (_FeedbackBuffer != null)
					_FeedbackBuffer.Begin(ctx, attributeElement.ElementsMode);

				attributeElement.Draw(ctx);
				
				if (_FeedbackBuffer != null)
					_FeedbackBuffer.End(ctx);
			}
		}
        public VAO CreateString(ShaderProgram Program, string Text)
        {
            Vector3[] vertices = new Vector3[Text.Length * 4];
            Vector2[] uvs = new Vector2[Text.Length * 4];
            int[] indices = new int[Text.Length * 6];

            for (int i = 0; i < Text.Length; i++)
            {
                // Note: These are fixed width fonts so just use 2x2 quads (-1..1)
                vertices[i * 4 + 0] = new Vector3(-1 + i * 2, 1, 0);
                vertices[i * 4 + 1] = new Vector3(-1 + i * 2, -1, 0);
                vertices[i * 4 + 2] = new Vector3(1 + i * 2, 1, 0);
                vertices[i * 4 + 3] = new Vector3(1 + i * 2, -1, 0);

                UVPair ch = Character[Text[i] > 256 ? ' ' : Text[i]];
                uvs[i * 4 + 0] = new Vector2(ch.Topleft.x, ch.BottomRight.y);
                uvs[i * 4 + 1] = ch.Topleft;
                uvs[i * 4 + 2] = ch.BottomRight;
                uvs[i * 4 + 3] = new Vector2(ch.BottomRight.x, ch.Topleft.y);

                indices[i * 6 + 0] = i * 4 + 1;
                indices[i * 6 + 1] = i * 4 + 0;
                indices[i * 6 + 2] = i * 4 + 2;
                indices[i * 6 + 3] = i * 4 + 1;
                indices[i * 6 + 4] = i * 4 + 2;
                indices[i * 6 + 5] = i * 4 + 3;
            }

            // Create the vertex buffer objects and then create the array object
            VBO<Vector3> vertexArray = new VBO<Vector3>(vertices, BufferTarget.ArrayBuffer, BufferUsageHint.StaticRead);
            VBO<Vector2> uvArray = new VBO<Vector2>(uvs, BufferTarget.ArrayBuffer, BufferUsageHint.StaticRead);
            VBO<int> elementArray = new VBO<int>(indices, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead);

            return new VAO(Program, vertexArray, uvArray, elementArray);
        }
Beispiel #6
0
        private static ShaderProgram LoadShader(string vertex, string fragment)
        {
            bool abort = false;
            if (!File.Exists("shaders/" + vertex + ".glsl"))
            {
                Console.WriteLine("vertex shader '{0}' not found.", vertex);
                abort = true;
            }
            if (!File.Exists("shaders/" + fragment + ".glsl"))
            {
                Console.WriteLine("fragment shader '{0}' not found.", fragment);
                abort = true;
            }
            if (abort)
                return null;

            ShaderProgram prog = new ShaderProgram(File.ReadAllText("shaders/" + vertex + ".glsl"), File.ReadAllText("shaders/" + fragment + ".glsl"));
            if (!string.IsNullOrWhiteSpace(prog.VertexShader.ShaderLog))
            {
                Console.WriteLine("vertex shader log:\r\n{0}", prog.VertexShader.ShaderLog);
                abort = true;
            }
            if (!string.IsNullOrWhiteSpace(prog.FragmentShader.ShaderLog))
            {
                Console.WriteLine("fragment shader log:\r\n{0}", prog.FragmentShader.ShaderLog);
                abort = true;
            }
            if (abort)
                return null;
            return prog;
        }
        static void Main(string[] args)
        {
            // create an OpenGL window
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            // provide the Glut callbacks that are necessary for running this tutorial
            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);
            Glut.glutCloseFunc(OnClose);

            // enable depth testing to ensure correct z-ordering of our fragments
            Gl.Enable(EnableCap.DepthTest);

            // compile the shader program
            program = new ShaderProgram(VertexShader, FragmentShader);

            // set the view and projection matrix, which are static throughout this tutorial
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up));

            // create a pyramid with vertices and colors
            pyramid = new VBO<Vector3>(new Vector3[] {
                new Vector3(0, 1, 0), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),        // front face
                new Vector3(0, 1, 0), new Vector3(1, -1, 1), new Vector3(1, -1, -1),        // right face
                new Vector3(0, 1, 0), new Vector3(1, -1, -1), new Vector3(-1, -1, -1),      // back face
                new Vector3(0, 1, 0), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1) });   // left face
            pyramidColor = new VBO<Vector3>(new Vector3[] {
                new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1),
                new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0),
                new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1),
                new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0) });
            pyramidTriangles = new VBO<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, BufferTarget.ElementArrayBuffer);

            // create a cube with vertices and colors
            cube = new VBO<Vector3>(new Vector3[] {
                new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1),
                new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(1, -1, -1),
                new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),
                new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1),
                new Vector3(-1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1),
                new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(1, -1, -1) });
            cubeColor = new VBO<Vector3>(new Vector3[] {
                new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0),
                new Vector3(1, 0.5, 0), new Vector3(1, 0.5, 0), new Vector3(1, 0.5, 0), new Vector3(1, 0.5, 0),
                new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 0, 0),
                new Vector3(1, 1, 0), new Vector3(1, 1, 0), new Vector3(1, 1, 0), new Vector3(1, 1, 0),
                new Vector3(0, 0, 1), new Vector3(0, 0, 1), new Vector3(0, 0, 1), new Vector3(0, 0, 1),
                new Vector3(1, 0, 1), new Vector3(1, 0, 1), new Vector3(1, 0, 1), new Vector3(1, 0, 1) });
            cubeQuads = new VBO<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }, BufferTarget.ElementArrayBuffer);

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
        /// <summary>
        /// Create a basic quad by storing two triangles into a VAO.
        /// This quad includes UV co-ordinates from uvloc to uvloc+uvsize.
        /// </summary>
        /// <param name="program">The ShaderProgram assigned to this quad.</param>
        /// <param name="location">The location of the VAO (assigned to the vertices).</param>
        /// <param name="size">The size of the VAO (assigned to the vertices).</param>
        /// <param name="uvloc">The origin of the UV co-ordinates.</param>
        /// <param name="uvsize">The size of the UV co-ordinates.</param>
        /// <returns>The VAO object representing this quad.</returns>
        public static VAO CreateQuad(ShaderProgram program, Vector2 location, Vector2 size, Vector2 uvloc, Vector2 uvsize)
        {
            Vector3[] vertices = new Vector3[] { new Vector3(location.x, location.y, 0), new Vector3(location.x + size.x, location.y, 0), 
                new Vector3(location.x + size.x, location.y + size.y, 0), new Vector3(location.x, location.y + size.y, 0) };
            Vector2[] uvs = new Vector2[] { uvloc, new Vector2(uvloc.x + uvsize.x, uvloc.y), new Vector2(uvloc.x + uvsize.x, uvloc.y + uvsize.y), new Vector2(uvloc.x, uvloc.y + uvsize.y) };
            int[] indices = new int[] { 0, 1, 2, 2, 3, 0 };

            return new VAO(program, new VBO<Vector3>(vertices), new VBO<Vector2>(uvs), new VBO<int>(indices, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead));
        }
Beispiel #9
0
        public Gizmo()
        {
            shader = new ShaderProgram(VertexShaderSource, FragmentShaderSource);
            shader["modelMatrix"].SetValue(Matrix4.Identity);
            shader["projectionMatrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.6f, 1280f / 720f, 0.1f, 1000f));
            shader["viewMatrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 4), Vector3.Zero, Vector3.Up));

            double size = 0.05;

            Vector3[] verts = new Vector3[] {
                // cube in the middle
                new Vector3(-size, -size, -size), new Vector3(size, -size, -size), new Vector3(size, -size, size), new Vector3(-size, -size, size),
                new Vector3(-size, size, -size), new Vector3(size, size, -size), new Vector3(size, size, size), new Vector3(-size, size, size),
                // unit x
                new Vector3(1 + size, size, size), new Vector3(1 + size, size, -size), new Vector3(1 + size, -size, -size),new Vector3(1 + size, -size, size),
                // unit z
                new Vector3(-size, size, 1+ size), new Vector3(size, size, 1+ size), new Vector3(size, -size, 1+size), new Vector3(-size, -size, 1+ size),
                // unit y
                new Vector3(-size, 1 + size, -size), new Vector3(size, 1 + size, -size),new Vector3(size, 1 + size, size),new Vector3(-size, 1 + size, size)
            };

            vertices = new VBO<Vector3>(verts);

            Vector3[] cols = new Vector3[] {
                new Vector3(1, 1, 1),new Vector3(1, 1, 1),new Vector3(1, 1, 1),new Vector3(1, 1, 1),
                new Vector3(1, 1, 1),new Vector3(1, 1, 1),new Vector3(1, 1, 1),new Vector3(1, 1, 1),
                new Vector3(1, 0, 0),new Vector3(1, 0, 0),new Vector3(1, 0, 0),new Vector3(1, 0, 0),
                new Vector3(0, 0, 1),new Vector3(0, 0, 1),new Vector3(0, 0, 1),new Vector3(0, 0, 1),
                new Vector3(0, 1, 0),new Vector3(0, 1, 0),new Vector3(0, 1, 0),new Vector3(0, 1, 0)
            };

            colors = new VBO<Vector3>(cols);
            indices = new VBO<int>(new int[] {
                // center cube
                0, 2, 1, 0, 3, 2,
                4, 7, 3, 4, 3, 0,
                5, 4, 0, 5, 0, 1,
                // unit x
                6, 5, 9, 6, 9, 8,
                6, 8, 11, 6, 11, 2,
                9, 5, 1, 9, 1, 10,
                2, 11, 10, 2, 10, 1,
                8, 9, 10, 8, 10, 11,
                // unit z
                7, 6, 13, 7, 13, 12,
                7, 12, 15, 7, 15, 3,
                13, 6, 2, 13, 2, 14,
                3, 15, 14, 3, 14, 2,
                12, 13, 14, 12, 14, 15,
                // unit y
                19, 18, 6, 19, 6, 7,
                18, 17, 5, 18, 5, 6,
                17, 16, 4, 17, 4, 5,
                16, 19, 7, 16, 7, 4,
                16, 17, 18, 16, 18, 19
            }, BufferTarget.ElementArrayBuffer);
        }
Beispiel #10
0
 /// <summary>
 /// Gets the location of the parameter in a compiled OpenGL program.
 /// </summary>
 /// <param name="Program">Specifies the shader program that contains this parameter.</param>
 public void GetLocation(ShaderProgram Program)
 {
     Program.Use();
     if (programid == 0)
     {
         programid = Program.ProgramID;
         location = (ptype == OpenGL.ParamType.Uniform ? Program.GetUniformLocation(name) : Program.GetAttributeLocation(name));
     }
 }
Beispiel #11
0
        /// <summary>
        /// Create a basic quad by storing two triangles into a VAO.
        /// This quad includes normals, and does not include UV co-ordinates.
        /// </summary>
        /// <param name="program">The ShaderProgram assigned to this quad.</param>
        /// <param name="location">The location of the VAO (assigned to the vertices).</param>
        /// <param name="size">The size of the VAO (assigned to the vertices).</param>
        /// <returns>The VAO object representing this quad.</returns>
        public static VAO CreateQuadWithNormals(ShaderProgram program, Vector2 location, Vector2 size)
        {
            Vector3[] vertex = new Vector3[] { new Vector3(location.x, location.y, 0), new Vector3(location.x + size.x, location.y, 0), 
                new Vector3(location.x + size.x, location.y + size.y, 0), new Vector3(location.x, location.y + size.y, 0) };
            int[] element = new int[] { 0, 1, 2, 2, 3, 0 };
            Vector3[] normal = CalculateNormals(vertex, element);

            return new VAO(program, new VBO<Vector3>(vertex), new VBO<Vector3>(normal), new VBO<int>(element, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead));
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            // enable blending and set to accumulate the star colors
            Gl.Disable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);

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

            // set up the projection and view matrix
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 20), Vector3.Zero, Vector3.Up));

            // load the star texture
            starTexture = new Texture("star.bmp");

            // each star is simply a quad
            star = new VBO<Vector3>(new Vector3[] { new Vector3(-1, -1, 0), new Vector3(1, -1, 0), new Vector3(1, 1, 0), new Vector3(-1, 1, 0) });
            starUV = new VBO<Vector2>(new Vector2[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) });
            starQuads = new VBO<int>(new int[] { 0, 1, 2, 0, 2, 3 }, BufferTarget.ElementArrayBuffer);

            // create 50 stars for this tutorial
            int numStars = 50;
            for (int i = 0; i < numStars; i++)
            {
                stars.Add(new Star(0, (float)i / numStars * 4f, new Vector3(generator.NextDouble(), generator.NextDouble(), generator.NextDouble())));
            }

            font = new BMFont("font24.fnt", "font24.png");
            fontProgram = new ShaderProgram(BMFont.FontVertexSource, BMFont.FontFragmentSource);

            fontProgram.Use();
            fontProgram["ortho_matrix"].SetValue(Matrix4.CreateOrthographic(width, height, 0, 1000));
            fontProgram["color"].SetValue(new Vector3(1, 1, 1));

            information = font.CreateString(fontProgram, "OpenGL  C#  Tutorial  10");

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
        private VoxelChunkManager()
        {
            chunks = new Dictionary<Tuple<int, int>, VoxelChunk>();
            chunksToMesh = new Dictionary<Tuple<int, int>, VoxelChunk>();
            chunkLoadQueue = new Queue<Tuple<int, int>>();
            noise = new OpenSimplexNoise(2);
            frustum = new Frustum();
            chunkScalingMatrix = Matrix4.CreateScaling(new Vector3(ChunkWidth, ChunkHeight, ChunkDepth));

            chunkShader = new ShaderProgram(chunkvertexshader, chunkfragmentshader);
            chunkShader["lightDirection"].SetValue(new Vector3(-0.75, -0.5, -1).Normalize());
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH | Glut.GLUT_ALPHA | Glut.GLUT_STENCIL | Glut.GLUT_MULTISAMPLE);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            // add our mouse callbacks for this tutorial
            Glut.glutMouseFunc(OnMouse);
            Glut.glutMotionFunc(OnMove);

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

            // create our camera
            camera = new Camera(new Vector3(0, 0, 50), Quaternion.Identity);
            camera.SetDirection(new Vector3(0, 0, -1));

            // set up the projection and view matrix
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            program["model_matrix"].SetValue(Matrix4.Identity);

            objectFile = new ObjLoader("enterprise/enterprise.obj", program);

            // load the bitmap font for this tutorial
            font = new BMFont("font24.fnt", "font24.png");
            fontProgram = new ShaderProgram(BMFont.FontVertexSource, BMFont.FontFragmentSource);

            fontProgram.Use();
            fontProgram["ortho_matrix"].SetValue(Matrix4.CreateOrthographic(width, height, 0, 1000));
            fontProgram["color"].SetValue(new Vector3(1, 1, 1));

            information = font.CreateString(fontProgram, "OpenGL  C#  Tutorial  16");

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
        public Billboard(ShaderProgram program, Texture texture, Vector3[] locations, Vector3[] colors)
        {
            this.Program = program;
            this.Texture = texture;

            int[] elements = new int[locations.Length];
            for (int i = 0; i < elements.Length; i++) elements[i] = i;

            this.billboard = new VAO(program, new VBO<Vector3>(locations), new VBO<Vector3>(colors), new VBO<int>(elements));
            this.billboard.DrawMode = BeginMode.Points;
            this.billboard.DisposeChildren = true;
            this.Color = new Vector4(1, 1, 1, 1);
        }
Beispiel #16
0
        public ObjLoader(string filename, ShaderProgram program)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            this.defaultProgram = program;

            System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
            ObjMaterial defaultMaterial = new ObjMaterial(program);

            using (StreamReader stream = new StreamReader(filename))
            {
                List<string> lines = new List<string>();
                int vertexOffset = 1, vertexCount = 0;
                int uvOffset = 1, uvCount = 0;

                // read the entire file
                while (!stream.EndOfStream)
                {
                    string line = stream.ReadLine();
                    if (line.Trim().Length == 0) continue;

                    if ((line[0] == 'o' || line[0] == 'g') && lines.Count != 0)
                    {
                        ObjObject newObject = new ObjObject(lines, materials, vertexOffset, uvOffset);
                        if (vertexCount != 0) objects.Add(newObject);

                        if (newObject.Material == null) newObject.Material = defaultMaterial;

                        lines.Clear();
                        vertexOffset += vertexCount;
                        uvOffset += uvCount;
                        vertexCount = 0;
                        uvCount = 0;
                    }
                    if (line[0] != '#') lines.Add(line);
                    if (line[0] == 'v')
                    {
                        if (line[1] == ' ') vertexCount++;
                        else uvCount++;
                    }

                    // check if a material file is being used
                    if (line[0] == 'm' && line[1] == 't') LoadMaterials(CreateFixedPath(filename, line.Split(' ')[1]));
                }

                // make sure we grab any remaining objects that occured before the EOF
                if (lines != null) objects.Add(new ObjObject(lines, materials, vertexOffset, uvOffset));
            }

            watch.Stop();
            Console.WriteLine("Took {0}ms", watch.ElapsedMilliseconds);
        }
Beispiel #17
0
        public FontVAO CreateString(ShaderProgram program, string text, Justification justification = Justification.Left)
        {
            Vector3[] vertices = new Vector3[text.Length * 4];
            Vector2[] uvs = new Vector2[text.Length * 4];
            int[] indices = new int[text.Length * 6];

            int xpos = 0, width = 0;

            // calculate the initial x position depending on the justification
            if (justification != Justification.Left)
            {
                for (int i = 0; i < text.Length; i++)
                    width += (int)characters[characters.ContainsKey(text[i]) ? text[i] : ' '].width;
                if (justification == Justification.Right) xpos = -width;
                else xpos = -width / 2;
            }

            for (int i = 0; i < text.Length; i++)
            {
                // grab the character, replacing with ' ' if the character isn't loaded
                Character ch = characters[characters.ContainsKey(text[i]) ? text[i] : ' '];

                vertices[i * 4 + 0] = new Vector3(xpos, ch.height, 0);
                vertices[i * 4 + 1] = new Vector3(xpos, 0, 0);
                vertices[i * 4 + 2] = new Vector3(xpos + ch.width, ch.height, 0);
                vertices[i * 4 + 3] = new Vector3(xpos + ch.width, 0, 0);
                xpos += (int)ch.width;

                uvs[i * 4 + 0] = new Vector2(ch.x1, ch.y1);
                uvs[i * 4 + 1] = new Vector2(ch.x1, ch.y2);
                uvs[i * 4 + 2] = new Vector2(ch.x2, ch.y1);
                uvs[i * 4 + 3] = new Vector2(ch.x2, ch.y2);

                indices[i * 6 + 0] = i * 4 + 2;
                indices[i * 6 + 1] = i * 4 + 0;
                indices[i * 6 + 2] = i * 4 + 1;
                indices[i * 6 + 3] = i * 4 + 3;
                indices[i * 6 + 4] = i * 4 + 2;
                indices[i * 6 + 5] = i * 4 + 1;
            }

            // Create the vertex buffer objects and then create the array object
            return new FontVAO(program, new VBO<Vector3>(vertices), new VBO<Vector2>(uvs), new VBO<int>(indices, BufferTarget.ElementArrayBuffer));
        }
Beispiel #18
0
        /// <summary>
        /// Builds a simple dome suitable for creating a smooth gradient to the horizon.
        /// </summary>
        /// <param name="program">The shader program that will be used with this dome.</param>
        /// <param name="segments">The number of segments in the dome.</param>
        /// <returns>A VAO that contains the vertices, uv co-ordinates and elements to draw the dome.</returns>
        public static VAO GradientDome(ShaderProgram program, int segments)
        {
            // allocate our vertex, uv and element arrays
            Vector3[] vertices = new Vector3[segments * (segments - 1) + 2];
            Vector2[] uvs = new Vector2[segments * (segments - 1) + 2];
            int[] elements = new int[2 * segments * (segments - 1) * 3];

            double deltaLatitude = Math.PI / segments;
            double deltaLongitude = Math.PI * 2.0 / segments;
            int index = 0;

            // create the rings of the dome using polar coordinates
            for (int i = 1; i < segments; i++)
            {
                double r0 = Math.Sin(i * deltaLatitude);
                double y0 = Math.Cos(i * deltaLatitude);

                for (int j = 0; j < segments; j++)
                {
                    double x0 = r0 * Math.Sin(j * deltaLongitude);
                    double z0 = r0 * Math.Cos(j * deltaLongitude);

                    vertices[index] = new Vector3(x0, y0, z0);
                    uvs[index++] = new Vector2(0, 1.0f - (float)y0);
                }
            }

            // create the top of the dome
            vertices[index] = new Vector3(0, 1, 0);
            uvs[index++] = new Vector2(0, 0);

            // create the bottom of the dome
            vertices[index] = new Vector3(0, -1, 0);
            uvs[index] = new Vector2(0, 2);

            // create the faces of the rings
            index = 0;
            for (int i = 0; i < segments - 2; i++)
            {
                for (int j = 0; j < segments; j++)
                {
                    elements[index++] = segments * i + j;
                    elements[index++] = segments * i + (j + 1) % segments;
                    elements[index++] = segments * (i + 1) + (j + 1) % segments;
                    elements[index++] = segments * i + j;
                    elements[index++] = segments * (i + 1) + (j + 1) % segments;
                    elements[index++] = segments * (i + 1) + j;
                }
            }

            // create the faces of the top of the dome
            for (int i = 0; i < segments; i++)
            {
                elements[index++] = segments * (segments - 1);
                elements[index++] = (i + 1) % segments;
                elements[index++] = i;
            }

            // create the faces of the bottom of the dome
            for (int i = 0; i < segments; i++)
            {
                elements[index++] = segments * (segments - 1) + 1;
                elements[index++] = segments * (segments - 2) + i;
                elements[index++] = segments * (segments - 2) + (i + 1) % segments;
            }

            Vector3[] normals = Geometry.CalculateNormals(vertices, elements);
            return new VAO(program, new VBO<Vector3>(vertices), new VBO<Vector3>(normals), new VBO<Vector2>(uvs), new VBO<int>(elements));
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            timefromstart = System.Diagnostics.Stopwatch.StartNew();
            Console.WriteLine("Initializing GLUT - {0}s", getTimeFromStart().ToString());
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("kVoxGame");
            Console.WriteLine("GLUT window created - {0}s", getTimeFromStart().ToString());

            //Callbacks
            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            //Mouse
            Glut.glutMouseFunc(OnMouse);
            Glut.glutMotionFunc(OnMove);

            //Keyboard
            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Console.WriteLine("GLUT callbacks binded - {0}s", getTimeFromStart().ToString());

            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.Enable(EnableCap.Multisample);
            Gl.Enable(EnableCap.SampleAlphaToCoverage);
            Gl.Enable(EnableCap.FragmentLightingSgix);
            Gl.Enable(EnableCap.CullFace);

            Console.WriteLine("GL Enables enabled :D - {0}s", getTimeFromStart().ToString());

            skydomeTexture = new Texture("skydome.jpg");

            //Gl.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            // create main shader program
            terrainSP = new ShaderProgram(terrainVS, terrainFS);
            terrainSP.Use();
            terrainSP["color"].SetValue(new Vector3(0, 0.8, 0));
            projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f);
            terrainSP["projection_matrix"].SetValue(projectionMatrix);
            terrainSP["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)) * Matrix4.CreateRotation(new Vector3(0, 0, 0), 0.0f));
            Console.WriteLine("Shader program (main) compiled and data injected - {0}s", getTimeFromStart().ToString());

            // create main skybox program
            skyboxSP = new ShaderProgram(skyboxVS, skyboxFS);
            skyboxSP.Use();
            skyboxSP["color"].SetValue(new Vector3(0.2, 1.0, 1.0));
            skyboxSP["resolution"].SetValue(new Vector2(width, height));
            projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f);
            skyboxSP["projection_matrix"].SetValue(projectionMatrix);
            skyboxSP["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(0, 0, 0)) * Matrix4.CreateRotation(new Vector3(0, 0, 0), 0.0f));
            Console.WriteLine("Shader program (skybox) compiled and data injected - {0}s", getTimeFromStart().ToString());

            //Setup camera
            camera = new Camera(new Vector3(0, 0, 10), Quaternion.Identity);
            camera.SetDirection(new Vector3(0, 0, -1));

            Console.WriteLine("Cam setup complete - {0}s", getTimeFromStart().ToString());

            watch = System.Diagnostics.Stopwatch.StartNew();
            chunks = new VoxelChunk[4];
            //instance few voxel chunks
            chunks[0] = new VoxelChunk(0,0);
            chunks[1] = new VoxelChunk(0, 32);
            chunks[2] = new VoxelChunk(32, 0);
            chunks[3] = new VoxelChunk(32, 32);
            Console.WriteLine("Chunks added to array - {0}s", getTimeFromStart().ToString());

            //init frustum
            frustum = new Frustum();
            frustum.UpdateFrustum(projectionMatrix, camera.ViewMatrix);
            Console.WriteLine("starting main GLUT loop - {0}s", getTimeFromStart().ToString());

            Glut.glutMainLoop();
        }
Beispiel #20
0
 public Billboard(ShaderProgram program, Texture texture, Vector3 location, float size)
     : this(program, texture, new Vector3[] { location }, new Vector3[] { new Vector3(1, 1, 1) })
 {
 }
Beispiel #21
0
 /// <summary>
 /// Get the index of a uniform block in the provided shader program.
 /// Note:  This method will use the provided shader program, so make sure to
 /// store which program is currently active and reload it if required.
 /// </summary>
 /// <param name="program">The shader program that contains the uniform block.</param>
 /// <param name="uniformBlockName">The uniform block name.</param>
 /// <returns>The index of the uniform block.</returns>
 public static uint GetUniformBlockIndex(ShaderProgram program, string uniformBlockName)
 {
     return(Gl.GetUniformBlockIndex(program.ProgramID, uniformBlockName));
 }
Beispiel #22
0
        public static void InitShaders(ShaderVersion version = ShaderVersion.GLSL140)
        {
            Version = version;

            try
            {
                SimpleTexturedShader = InitShader(SimpleTexturedVertexShader, SimpleTexturedFragmentShader);
                SimpleColoredShader = InitShader(SimpleColoredVertexShader, SimpleColoredFragmentShader);
                SineShader = InitShader(SineVertexShader, SimpleColoredFragmentShader);

                FontShader = InitShader(FontVertexSource, FontFragmentSource);
                Font3DShader = InitShader(Font3DVertexSource, FontFragmentSource);
            }
            catch (Exception e)
            {
                Console.WriteLine("Your GPU does not support programmable shaders.");
            }
        }
Beispiel #23
0
 /// <summary>
 /// Get the index of a uniform block in the provided shader program.
 /// Note:  This method will use the provided shader program, so make sure to
 /// store which program is currently active and reload it if required.
 /// </summary>
 /// <param name="program">The shader program that contains the uniform block.</param>
 /// <param name="uniformBlockName">The uniform block name.</param>
 /// <returns>The index of the uniform block.</returns>
 public static uint GetUniformBlockIndex(ShaderProgram program, string uniformBlockName)
 {
     program.Use();  // take care of a crash that can occur on NVIDIA drivers by using the program first
     return(GetUniformBlockIndex(program.ProgramID, uniformBlockName));
 }
 public ObjMaterial(ShaderProgram program)
 {
     this.Name = "opengl-default-project";
     this.Transparency = 1f;
     this.Ambient = Vector3.UnitScale;
     this.Diffuse = Vector3.UnitScale;
     this.Program = program;
 }
			/// <summary>
			/// Create a program from this Program.
			/// </summary>
			/// <returns></returns>
			public ShaderProgram Create()
			{
				if (String.IsNullOrEmpty(Id))
					throw new InvalidOperationException("invalid program identifier");

				ShaderProgram shaderProgram = new ShaderProgram(Id);
				ShaderCompilerContext shaderCompilerParams = new ShaderCompilerContext();

				// Attach required objects
				foreach (Object shaderProgramObject in Objects) {
					ShaderObject shaderObject = new ShaderObject(shaderProgramObject.Stage);

					// Load source
					shaderObject.LoadSource(shaderProgramObject.Path);
					// Attach object
					shaderProgram.AttachShader(shaderObject);

					// Take into account required preprocessor symbols
					foreach (string preprocessorSymbol in shaderProgramObject.Symbols)
						shaderCompilerParams.Defines.Add(preprocessorSymbol);
				}

				// Set compiler parameters
				shaderProgram.CompilationParams = shaderCompilerParams;

				// Register attributes semantic
				foreach (Attribute attribute in Attributes)
					shaderProgram.SetAttributeSemantic(attribute.Name, attribute.Semantic);

				return (shaderProgram);
			}
Beispiel #26
0
 /// <summary>
 /// Installs a program object as part of current rendering state.
 /// </summary>
 /// <param name="Program">Specifies the handle of the program object whose executables are to be used as part of current rendering state.</param>
 public static void UseProgram(ShaderProgram Program)
 {
     Gl.UseProgram(Program.ProgramID);
 }
        public ObjMaterial(List<string> lines, ShaderProgram program)
        {
            if (!lines[0].StartsWith("newmtl")) return;

            this.Name = lines[0].Substring(7);
            this.Transparency = 1f;

            for (int i = 1; i < lines.Count; i++)
            {
                string[] split = lines[i].Split(' ');

                // Some object exporters export the material with a tab character in front, so I am removing it
                if (split[0].Contains("\t"))
                {
                    split[0] = split[0].Replace("\t", string.Empty);
                }

                switch (split[0])
                {
                    case "Ns": this.SpecularCoefficient = float.Parse(split[1]);
                        break;
                    case "Ka": this.Ambient = new Vector3(float.Parse(split[1]), float.Parse(split[2]), float.Parse(split[3]));
                        break;
                    case "Kd": this.Diffuse = new Vector3(float.Parse(split[1]), float.Parse(split[2]), float.Parse(split[3]));
                        break;
                    case "Ks": this.Specular = new Vector3(float.Parse(split[1]), float.Parse(split[2]), float.Parse(split[3]));
                        break;
                    case "d": this.Transparency = float.Parse(split[1]);
                        break;
                    case "illum": this.Illumination = (IlluminationMode)int.Parse(split[1]);
                        break;
                    case "map_Kd": if (File.Exists(lines[i].Split(new char[] { ' ' }, 2)[1])) this.DiffuseMap = new Texture(lines[i].Split(new char[] { ' ' }, 2)[1]);
                        break;
                }
            }

            this.Program = program;
        }
Beispiel #28
0
 /// <summary>
 /// Installs a program object as part of current rendering state.
 /// </summary>
 /// <param name="Program">Specifies the handle of the program object whose executables are to be used as part of current rendering state.</param>
 public static void UseProgram(ShaderProgram Program)
 {
     currentProgram = Program.ProgramID;
     Gl.UseProgram(currentProgram);
 }
		/// <summary>
		/// Render this vertex array.
		/// </summary>
		/// <param name="ctx">
		/// The <see cref="GraphicsContext"/> used for rendering.
		/// </param>
		/// <param name="shaderProgram">
		/// The <see cref="ShaderProgram"/> used for drawing this vertex array.
		/// </param>
		public override void Draw(GraphicsContext ctx, ShaderProgram shaderProgram)
		{
			if (ctx == null)
				throw new ArgumentNullException("ctx");
			if (ctx.IsCurrent == false)
				throw new ArgumentException("not current", "ctx");
			if (shaderProgram == null)
				throw new ArgumentNullException("shaderProgram");
			if (shaderProgram.Exists(ctx) == false)
				throw new ArgumentException("not existing", "shaderProgram");
			if (Exists(ctx) == false)
				throw new InvalidOperationException("not existing");
			if (_Elements.Count == 0 && _PatchElement == null)
				throw new InvalidOperationException("no elements defined");

			if (_PatchElement != null) {
				// Setup patch vertices
				Gl.PatchParameter(Gl.PATCH_VERTICES, (int)_PatchElement.PatchCount);

				// GL_PATCH_DEFAULT_OUTER_LEVEL | GL_PATCH_DEFAULT_INNER_LEVEL

				// Set vertex arrays
				SetVertexArrayState(ctx, shaderProgram);
				// Uses shader
				shaderProgram.Bind(ctx);
				// Draw patches
				_PatchElement.Draw(ctx);
			}

			// Based implementation
			if (_Elements.Count > 0)
				base.Draw(ctx, shaderProgram);
		}
Beispiel #30
0
        public Scene(InputPanel ip)
        {
            //Stops GLUT trying to re-initialise if it has already been initialised.
            int glutTime = Glut.glutGet(Glut.GLUT_ELAPSED_TIME);
            if (glutTime <= 0)
            {
                Glut.glutInit();
            }

            //Initialises GLUT
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("Scene");

            Glut.glutSetOption(Glut.GLUT_ACTION_ON_WINDOW_CLOSE, 1);
            Glut.glutCloseFunc(closeFunc);

            Glut.glutIdleFunc(OnRenderFrame);

            Gl.Enable(EnableCap.Blend);

            //Creates the rendering ShaderProgram
            program = new ShaderProgram(VertexShader, FragmentShader);

            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            resetCamera();

            //Initialises colors
            colors[0] = new Vector3(1, 0.5f, 0);
            colors[1] = new Vector3(1, 1, 0);
            colors[2] = new Vector3(0.5f, 1, 0);
            colors[3] = new Vector3(0, 1, 0);
            colors[4] = new Vector3(0, 1, 0.5f);
            colors[5] = new Vector3(0, 0.5f, 1);
            colors[6] = new Vector3(0, 0, 1);
            colors[7] = new Vector3(0.5f, 0, 1);
            colors[8] = new Vector3(1, 0, 1);
            colors[9] = new Vector3(1, 0, 0.5f);

            //Starts the Stopwatch
            watch = System.Diagnostics.Stopwatch.StartNew();

            inputPanel = ip;

            //Enters the main loop
            Glut.glutMainLoop();
        }
Beispiel #31
0
        public static ShaderProgram InitShader(string vertexSource, string fragmentSource)
        {
            if (Version == ShaderVersion.GLSL120)
            {
                vertexSource = ConvertShader(vertexSource, true);
                fragmentSource = ConvertShader(fragmentSource, false);
            }

            ShaderProgram program = new ShaderProgram(vertexSource, fragmentSource);

            return program;
        }
Beispiel #32
0
        public void RenderWithVAOSimple(ShaderProgram program)
        {
            if (chunkVAO == null)
            {
                List<Vector3> vertices = new List<Vector3>();
                List<int> elements = new List<int>();
                for (int x = 0 + offsetX; x < 32 + offsetX; x++)
                {
                    for (int y = 0 + offsetZ; y < 32 + offsetZ; y++)
                    {
                        float h = Noise.Generate((x + 32) / 32f, (y + 32) / 45f);
                        h = (float)Math.Round(h * 8);
                        if(h < 0)
                        {
                            h = -h;
                        }
                        //for(float test = -10; test <= h; h--)
                        AddCube(new Vector3(x, 0, y), new Vector3(x + 1, h + 1, y + 1), vertices, elements);

                    }
                }

                Vector3[] vertex = vertices.ToArray();
                int[] element = elements.ToArray();
                Vector3[] normals = OpenGL.Geometry.CalculateNormals(vertex, element);
                vertCount = vertex.Length;
                chunkVAO = new VAO(program, new VBO<Vector3>(vertex), new VBO<Vector3>(normals), new VBO<int>(element, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead));
            }

            program["model_matrix"].SetValue(ModelMatrix);

            chunkVAO.Draw();
        }
Beispiel #33
0
        public void RenderWithVAOGreedy(ShaderProgram program, bool draw = true)
        {
            if (chunkVAO == null)
            {
                List<Vector3> vertices = new List<Vector3>();
                List<int> elements = new List<int>();

                for (int d = 0; d < 3; d++)
                {
                    int i, j, k, l, w, h, u = (d + 1) % 3, v = (d + 2) % 3;
                    int[] x = new int[3];
                    int[] q = new int[3];
                    bool[] mask = new bool[32 * 32];

                    q[d] = 1;

                    for (x[d] = -1; x[d] < 32; )
                    {
                        // Compute the mask
                        int n = 0;
                        for (x[v] = 0; x[v] < 32; ++x[v])
                        {
                            for (x[u] = 0; x[u] < 32; ++x[u])
                            {
                                mask[n++] = (0 <= x[d] ? data(x[0], x[1], x[2]) : false) !=
                                    (x[d] < 32 - 1 ? data(x[0] + q[0], x[1] + q[1], x[2] + q[2]) : false);
                            }
                        }

                        // Increment x[d]
                        ++x[d];

                        // Generate mesh for mask using lexicographic ordering
                        n = 0;
                        for (j = 0; j < 32; ++j)
                        {
                            for (i = 0; i < 32; )
                            {
                                if (mask[n])
                                {
                                    // Compute width
                                    for (w = 1; i + w < 32 && mask[n + w]; ++w) ;

                                    // Compute height (this is slightly awkward
                                    var done = false;
                                    for (h = 1; j + h < 32; ++h)
                                    {
                                        for (k = 0; k < w; ++k)
                                        {
                                            if (!mask[n + k + h * 32])
                                            {
                                                done = true;
                                                break;
                                            }
                                        }
                                        if (done) break;
                                    }

                                    // Add quad
                                    x[u] = i; x[v] = j;
                                    int[] du = new int[3];
                                    int[] dv = new int[3];
                                    du[u] = w;
                                    dv[v] = h;

                                    AddFace(new Vector3(x[0], x[1], x[2]),
                                            new Vector3(x[0] + du[0], x[1] + du[1], x[2] + du[2]),
                                            new Vector3(x[0] + du[0] + dv[0], x[1] + du[1] + dv[1], x[2] + du[2] + dv[2]),
                                            new Vector3(x[0] + dv[0], x[1] + dv[1], x[2] + dv[2]), vertices, elements);

                                    // Zero-out mask
                                    for (l = 0; l < h; ++l)
                                    {
                                        for (k = 0; k < w; ++k)
                                        {
                                            mask[n + k + l * 32] = false;
                                        }
                                    }

                                    // Increment counters and continue
                                    i += w; n += w;
                                }
                                else
                                {
                                    ++i; ++n;
                                }
                            }
                        }
                    }
                }

                Vector3[] vertex = vertices.ToArray();
                int[] element = elements.ToArray();
                Vector3[] normals = OpenGL.Geometry.CalculateNormals(vertex, element);

                chunkVAO = new VAO(program, new VBO<Vector3>(vertex), new VBO<Vector3>(normals), new VBO<int>(element, BufferTarget.ElementArrayBuffer, BufferUsageHint.StaticRead));
            }

            if (draw)
            {
                program["model_matrix"].SetValue(ModelMatrix);

                chunkVAO.Draw();
            }
        }
Beispiel #34
0
        /// <summary>
        /// Set the vertex arrays state for the shader program.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> on which the shader program is bound.
        /// </param>
        /// <param name="shaderProgram">
        /// A <see cref="ShaderProgram"/> on which the vertex arrays shall be bound.
        /// </param>
        protected void SetVertexArrayState(GraphicsContext ctx, ShaderProgram shaderProgram)
        {
            if (Exists(ctx) == false)
            {
                throw new InvalidOperationException("not existing");
            }

            if (ctx.Caps.GlExtensions.VertexArrayObject_ARB)
            {
                // Bind this vertex array
                Gl.BindVertexArray(ObjectName);
                // Short path?
                if (!_VertexArrayDirty)
                {
                    // CheckVertexAttributes(ctx, shaderProgram);
                    return;
                }
            }

            if (shaderProgram != null)
            {
                uint attributesSet = 0;

                // Set vertex array state
                foreach (string attributeName in shaderProgram.ActiveAttributes)
                {
                    IVertexArray shaderVertexArray = GetVertexArray(attributeName, shaderProgram);
                    if (shaderVertexArray == null)
                    {
                        continue;
                    }

                    // Set array attribute
                    shaderVertexArray.SetVertexAttribute(ctx, shaderProgram, attributeName); attributesSet++;
                }

                if (attributesSet == 0)
                {
                    throw new InvalidOperationException("no attribute is set");
                }
            }
            else
            {
                IVertexArray attributeArray;

                // No shader program: using fixed pipeline program. ATM enable all attributes having a semantic
                if ((attributeArray = GetVertexArray(VertexArraySemantic.Position)) == null)
                {
                    throw new InvalidOperationException("no position semantic array defined");
                }
                attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.Position);

                // Optional attributes
                if ((attributeArray = GetVertexArray(VertexArraySemantic.Color)) != null)
                {
                    attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.Color);
                }
                if ((attributeArray = GetVertexArray(VertexArraySemantic.Normal)) != null)
                {
                    attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.Normal);
                }
                if ((attributeArray = GetVertexArray(VertexArraySemantic.TexCoord)) != null)
                {
                    attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.TexCoord);
                }
            }

            // Next time do not set inputs if GL_ARB_vertex_array_object is supported
            _VertexArrayDirty = false;
        }
Beispiel #35
0
        static void Main(string[] args)
        {
            Glut.glutInit();
            Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH | Glut.GLUT_MULTISAMPLE);   // multisampling makes things beautiful!
            Glut.glutInitWindowSize(width, height);
            Glut.glutCreateWindow("OpenGL Tutorial");

            Glut.glutIdleFunc(OnRenderFrame);
            Glut.glutDisplayFunc(OnDisplay);

            Glut.glutKeyboardFunc(OnKeyboardDown);
            Glut.glutKeyboardUpFunc(OnKeyboardUp);

            Glut.glutCloseFunc(OnClose);
            Glut.glutReshapeFunc(OnReshape);

            // add our mouse callbacks for this tutorial
            Glut.glutMouseFunc(OnMouse);
            Glut.glutMotionFunc(OnMove);

            Gl.Enable(EnableCap.DepthTest);
            Gl.Enable(EnableCap.Blend);
            Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

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

            // create our camera
            camera = new Camera(new Vector3(0, 0, 10), Quaternion.Identity);
            camera.SetDirection(new Vector3(0, 0, -1));

            // set up the projection and view matrix
            program.Use();
            program["projection_matrix"].SetValue(Matrix4.CreatePerspectiveFieldOfView(0.45f, (float)width / height, 0.1f, 1000f));
            //program["view_matrix"].SetValue(Matrix4.LookAt(new Vector3(0, 0, 10), Vector3.Zero, Vector3.Up));

            program["light_direction"].SetValue(new Vector3(0, 0, 1));
            program["enable_lighting"].SetValue(lighting);
            program["normalTexture"].SetValue(1);
            program["enable_mapping"].SetValue(normalMapping);

            brickDiffuse = new Texture("AlternatingBrick-ColorMap.png");
            brickNormals = new Texture("AlternatingBrick-NormalMap.png");

            Vector3[] vertices = new Vector3[] {
                new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1),         // top
                new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(1, -1, -1),     // bottom
                new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1),         // front face
                new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1),     // back face
                new Vector3(-1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, -1, -1), new Vector3(-1, -1, 1),     // left
                new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(1, -1, -1) };
            cube = new VBO<Vector3>(vertices);

            Vector2[] uvs = new Vector2[] {
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1),
                new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) };
            cubeUV = new VBO<Vector2>(uvs);

            List<int> triangles = new List<int>();
            for (int i = 0; i < 6; i++)
            {
                triangles.Add(i * 4);
                triangles.Add(i * 4 + 1);
                triangles.Add(i * 4 + 2);
                triangles.Add(i * 4);
                triangles.Add(i * 4 + 2);
                triangles.Add(i * 4 + 3);
            }
            cubeTriangles = new VBO<int>(triangles.ToArray(), BufferTarget.ElementArrayBuffer);

            Vector3[] normals = Geometry.CalculateNormals(vertices, triangles.ToArray());
            cubeNormals = new VBO<Vector3>(normals);

            Vector3[] tangents = CalculateTangents(vertices, normals, triangles.ToArray(), uvs);
            cubeTangents = new VBO<Vector3>(tangents);

            // load the bitmap font for this tutorial
            font = new BMFont("font24.fnt", "font24.png");
            fontProgram = new ShaderProgram(BMFont.FontVertexSource, BMFont.FontFragmentSource);

            fontProgram.Use();
            fontProgram["ortho_matrix"].SetValue(Matrix4.CreateOrthographic(width, height, 0, 1000));
            fontProgram["color"].SetValue(new Vector3(1, 1, 1));

            information = font.CreateString(fontProgram, "OpenGL  C#  Tutorial  15");

            watch = System.Diagnostics.Stopwatch.StartNew();

            Glut.glutMainLoop();
        }
Beispiel #36
0
 /** Constructs the effect from a shader program (references the shader) */
 public Effect(OpenGL.ShaderProgram shader)
 {
     program = shader;
 }