| 120 | |
| 121 | |
| 122 | == Modern OpenGL == |
| 123 | Create {{{triangle.c}}} and update {{{Makefile}}} |
| 124 | {{{ |
| 125 | #!sh |
| 126 | #include <stdio.h> |
| 127 | #include <stdlib.h> |
| 128 | #include <GL/glew.h> |
| 129 | #include <GL/glut.h> |
| 130 | |
| 131 | static const GLchar * vertex_shader[] = |
| 132 | {"void main()" |
| 133 | "{" |
| 134 | " gl_Position = ftransform();" |
| 135 | "}" |
| 136 | }; |
| 137 | static const GLchar * fragment_shader[] = |
| 138 | {"void main()" |
| 139 | "{" |
| 140 | " gl_FragColor = vec4(0.4,0.4,0.8,1.0);" |
| 141 | "}" |
| 142 | }; |
| 143 | |
| 144 | void setShaders() |
| 145 | { |
| 146 | GLuint v, f, p; |
| 147 | |
| 148 | v = glCreateShader(GL_VERTEX_SHADER); |
| 149 | f = glCreateShader(GL_FRAGMENT_SHADER); |
| 150 | glShaderSource(v, 1, vertex_shader, NULL); |
| 151 | glShaderSource(f, 1, fragment_shader, NULL); |
| 152 | glCompileShader(v); |
| 153 | glCompileShader(f); |
| 154 | p = glCreateProgram(); |
| 155 | glAttachShader(p,f); |
| 156 | glAttachShader(p,v); |
| 157 | glLinkProgram(p); |
| 158 | glUseProgram(p); |
| 159 | } |
| 160 | |
| 161 | |
| 162 | enum VAO_IDs { Triangles, NumVAOs }; |
| 163 | enum Buffer_IDs {ArrayBuffer,NumBuffers}; |
| 164 | enum Attrib_IDs { vPosition = 0 }; |
| 165 | GLuint VAOs[NumVAOs]; |
| 166 | GLuint Buffers[NumBuffers]; |
| 167 | #define NumVertices 6 |
| 168 | |
| 169 | void init(void) |
| 170 | { |
| 171 | glGenVertexArrays(NumVAOs, VAOs); |
| 172 | glBindVertexArray(VAOs[Triangles]); |
| 173 | GLfloat vertices[NumVertices][2] = { |
| 174 | { -0.90, -0.90 }, // Triangle 1 |
| 175 | { 0.85, -0.90 }, |
| 176 | { -0.90, 0.85 }, |
| 177 | { 0.90, -0.85 }, // Triangle 2 |
| 178 | { 0.90, 0.90 }, |
| 179 | { -0.85, 0.90 } |
| 180 | }; |
| 181 | glGenBuffers(NumBuffers, Buffers); |
| 182 | glBindBuffer( GL_ARRAY_BUFFER, Buffers[ArrayBuffer]); |
| 183 | glBufferData( GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); |
| 184 | glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, (const void*)0); |
| 185 | glEnableVertexAttribArray(vPosition); |
| 186 | } |
| 187 | |
| 188 | |
| 189 | void display(void) |
| 190 | { |
| 191 | glClear(GL_COLOR_BUFFER_BIT); |
| 192 | glBindVertexArray(VAOs[Triangles]); |
| 193 | glDrawArrays(GL_TRIANGLES, 0, NumVertices); |
| 194 | glutSwapBuffers(); |
| 195 | } |
| 196 | |
| 197 | int main(int argc, char **argv) |
| 198 | { |
| 199 | glutInit(&argc, argv); |
| 200 | glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); |
| 201 | glutCreateWindow("GLSL Intro"); |
| 202 | glutDisplayFunc(display); |
| 203 | glewInit(); |
| 204 | if (!glewIsSupported("GL_VERSION_2_0")) |
| 205 | { |
| 206 | printf("GLSL not supported\n"); |
| 207 | exit(EXIT_FAILURE); |
| 208 | } |
| 209 | glClearColor(0.9,1.0,1.0,1.0); |
| 210 | init(); |
| 211 | setShaders(); |
| 212 | glutMainLoop(); |
| 213 | return 0; |
| 214 | } |
| 215 | }}} |