CS116b/CS216
Chris Pollett
Jan 29, 2014
GLuint vs=glCreateShader(GL_VERTEX_SHADER); GLuint fs=glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vs, 1, ptrs, lens); /* ptrs is char pointer to the shader code lens is its length */ glCompileShader(vs); // now check if compiled GLint compiled = 0; glGetShaderiv(vs, GL_COMPILE_STATUS, &compiled); if (!compiled) throw runtime_error("fails to compile GL shader");
GlProgram programHandle; glAttachShader(programHandle, vs); glAttachShader(programHandle, fs); glLinkProgram(programHandle); glDetachShader(programHandle, vs); glDetachShader(programHandle, fs); GLint linked = 0; glGetProgramiv(programHandle, GL_LINK_STATUS, &linked); if (!linked) throw runtime_error("fails to link shaders");
glUseProgram(programHandle);
h_uModelViewMatrix = glGetUniformLocation( programHandle, "uModelViewMatrix"); //h_uModelViewMatrix is now a handle to the shader // variable uModelViewMatrix. // The book's code uses the call // safe_glGetUniformLocation which is a thin wrapper // to avoid null pointer issues.
GLfloat glmatrix[16]; // set up matrix for MVM = invEyeRbt * groundRbt; glUniformMatrix4fv(h_uModelViewMatrix, glmatrix); //or use the book safe_ version
#version 130 uniform mat4 uProjMatrix; uniform mat4 uModelViewMatrix; uniform mat4 uNormalMatrix; in vec3 aPosition; in vec3 aNormal; out vec3 vNormal; out vec3 vPosition; void main() { vNormal = vec3(uNormalMatrix * vec4(aNormal, 0.0)); // send position (eye coordinates) to fragment shader vec4 tPosition = uModelViewMatrix * vec4(aPosition, 1.0); vPosition = vec3(tPosition); gl_Position = uProjMatrix * tPosition; }
h_aPosition = glGetAttribLocation(programHandle, "aPosition"); h_aNormal = glGetAttribLocation(programHandle, "aNormal");
GLuint vbo; glGenBuffers(1, &vbo); GLuint ibo; glGenBuffers(1, &ibo); int vboLen, iboLen;
glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexPN) * vboLen, vtx, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short) * iboLen, idx, GL_STATIC_DRAW);
glEnableVertexAttribArray(h_aPosition); glEnableVertexAttribArray(h_aNormal);
glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(h_aPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPN), FIELD_OFFSET(VertexPN, p)); glVertexAttribPointer(h_aNormal, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPN), FIELD_OFFSET(VertexPN, n));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glDrawElements(GL_TRIANGLES, iboLen, GL_UNSIGNED_SHORT, 0);
glDisableVertexAttribArray(h_aPosition); glDisableVertexAttribArray(h_aNormal);