Lab07 Completed.

This commit is contained in:
Alex 2017-02-28 14:06:03 -06:00
parent d97e700c59
commit dd28af188a
14 changed files with 1138 additions and 0 deletions

BIN
L07.zip Normal file

Binary file not shown.

1
L07/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
build/

127
L07/CMakeLists.txt Normal file
View file

@ -0,0 +1,127 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
# Name of the project
PROJECT(L07)
# FOR LAB MACHINES ONLY!
# DO NOT EDIT
SET(DEF_DIR_GLM "C:\\c++\\glm")
SET(DEF_DIR_GLFW "C:\\c++\\glfw-3.2.1")
SET(DEF_DIR_GLEW "C:\\c++\\glew-2.0.0")
# Is this the solution?
# Override with `cmake -DSOL=ON ..`
OPTION(SOL "Solution" OFF)
# Use glob to get the list of all source files.
# We don't really need to include header and resource files to build, but it's
# nice to have them also show up in IDEs.
IF(${SOL})
FILE(GLOB_RECURSE SOURCES "src0/*.cpp")
FILE(GLOB_RECURSE HEADERS "src0/*.h")
FILE(GLOB_RECURSE GLSL "resources0/*.glsl")
ELSE()
FILE(GLOB_RECURSE SOURCES "src/*.cpp")
FILE(GLOB_RECURSE HEADERS "src/*.h")
FILE(GLOB_RECURSE GLSL "resources/*.glsl")
ENDIF()
# Set the executable.
ADD_EXECUTABLE(${CMAKE_PROJECT_NAME} ${SOURCES} ${HEADERS} ${GLSL})
# Get the GLM environment variable. Since GLM is a header-only library, we
# just need to add it to the include directory.
SET(GLM_INCLUDE_DIR "$ENV{GLM_INCLUDE_DIR}")
IF(NOT GLM_INCLUDE_DIR)
# The environment variable was not set
SET(ERR_MSG "Please point the environment variable GLM_INCLUDE_DIR to the root directory of your GLM installation.")
IF(WIN32)
# On Windows, try the default location
MESSAGE(STATUS "Looking for GLM in ${DEF_DIR_GLM}")
IF(IS_DIRECTORY ${DEF_DIR_GLM})
MESSAGE(STATUS "Found!")
SET(GLM_INCLUDE_DIR ${DEF_DIR_GLM})
ELSE()
MESSAGE(FATAL_ERROR ${ERR_MSG})
ENDIF()
ELSE()
MESSAGE(FATAL_ERROR ${ERR_MSG})
ENDIF()
ENDIF()
INCLUDE_DIRECTORIES(${GLM_INCLUDE_DIR})
# Get the GLFW environment variable. There should be a CMakeLists.txt in the
# specified directory.
SET(GLFW_DIR "$ENV{GLFW_DIR}")
IF(NOT GLFW_DIR)
# The environment variable was not set
SET(ERR_MSG "Please point the environment variable GLFW_DIR to the root directory of your GLFW installation.")
IF(WIN32)
# On Windows, try the default location
MESSAGE(STATUS "Looking for GLFW in ${DEF_DIR_GLFW}")
IF(IS_DIRECTORY ${DEF_DIR_GLFW})
MESSAGE(STATUS "Found!")
SET(GLFW_DIR ${DEF_DIR_GLFW})
ELSE()
MESSAGE(FATAL_ERROR ${ERR_MSG})
ENDIF()
ELSE()
MESSAGE(FATAL_ERROR ${ERR_MSG})
ENDIF()
ENDIF()
OPTION(GLFW_BUILD_EXAMPLES "GLFW_BUILD_EXAMPLES" OFF)
OPTION(GLFW_BUILD_TESTS "GLFW_BUILD_TESTS" OFF)
OPTION(GLFW_BUILD_DOCS "GLFW_BUILD_DOCS" OFF)
IF(CMAKE_BUILD_TYPE MATCHES Release)
ADD_SUBDIRECTORY(${GLFW_DIR} ${GLFW_DIR}/release)
ELSE()
ADD_SUBDIRECTORY(${GLFW_DIR} ${GLFW_DIR}/debug)
ENDIF()
INCLUDE_DIRECTORIES(${GLFW_DIR}/include)
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} glfw ${GLFW_LIBRARIES})
# Get the GLEW environment variable.
SET(GLEW_DIR "$ENV{GLEW_DIR}")
IF(NOT GLEW_DIR)
# The environment variable was not set
SET(ERR_MSG "Please point the environment variable GLEW_DIR to the root directory of your GLEW installation.")
IF(WIN32)
# On Windows, try the default location
MESSAGE(STATUS "Looking for GLEW in ${DEF_DIR_GLEW}")
IF(IS_DIRECTORY ${DEF_DIR_GLEW})
MESSAGE(STATUS "Found!")
SET(GLEW_DIR ${DEF_DIR_GLEW})
ELSE()
MESSAGE(FATAL_ERROR ${ERR_MSG})
ENDIF()
ELSE()
MESSAGE(FATAL_ERROR ${ERR_MSG})
ENDIF()
ENDIF()
INCLUDE_DIRECTORIES(${GLEW_DIR}/include)
IF(WIN32)
# With prebuilt binaries
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} ${GLEW_DIR}/lib/Release/Win32/glew32s.lib)
ELSE()
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} ${GLEW_DIR}/lib/libGLEW.a)
ENDIF()
# OS specific options and libraries
IF(WIN32)
# c++11 is enabled by default.
# -Wall produces way too many warnings.
# -pedantic is not supported.
# Disable warning 4996.
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4996")
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} opengl32.lib)
ELSE()
# Enable all pedantic warnings.
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -pedantic")
IF(APPLE)
# Add required frameworks for GLFW.
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} "-framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo")
ELSE()
#Link the Linux OpenGL library
TARGET_LINK_LIBRARIES(${CMAKE_PROJECT_NAME} "GL")
ENDIF()
ENDIF()

9
L07/resources/frag.glsl Normal file
View file

@ -0,0 +1,9 @@
#version 120
varying vec3 color;
void main()
{
// Just pass the color through from vertex to pixel
gl_FragColor = vec4(color.r, color.g, color.b, 1.0);
}

15
L07/resources/vert.glsl Normal file
View file

@ -0,0 +1,15 @@
#version 120
uniform mat4 P;
uniform mat4 MV;
attribute vec4 aPos; // In object space
attribute vec3 aNor; // In object space
varying vec3 color;
void main()
{
gl_Position = P * MV * aPos;
vec3 l = vec3(0.0, 0.0, 1.0); // In camera space
vec4 n = MV * vec4(aNor, 0.0);
color = vec3((n.x*l.x + n.y*l.y + n.z*l.z), (n.x*l.x + n.y*l.y + n.z*l.z), (n.x*l.x + n.y*l.y + n.z*l.z));
}

66
L07/src/Camera.cpp Normal file
View file

@ -0,0 +1,66 @@
#include "Camera.h"
#include "MatrixStack.h"
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
Camera::Camera() :
aspect(1.0f),
fovy(45.0f),
znear(0.1f),
zfar(1000.0f),
rotations(0.0, 0.0),
translations(0.0f, 0.0f, -5.0f),
rfactor(0.01f),
tfactor(0.001f),
sfactor(0.005f)
{
}
Camera::~Camera()
{
}
void Camera::mouseClicked(float x, float y, bool shift, bool ctrl, bool alt)
{
mousePrev.x = x;
mousePrev.y = y;
if(shift) {
state = Camera::TRANSLATE;
} else if(ctrl) {
state = Camera::SCALE;
} else {
state = Camera::ROTATE;
}
}
void Camera::mouseMoved(float x, float y)
{
glm::vec2 mouseCurr(x, y);
glm::vec2 dv = mouseCurr - mousePrev;
switch(state) {
case Camera::ROTATE:
rotations += rfactor * dv;
break;
case Camera::TRANSLATE:
translations.x -= translations.z * tfactor * dv.x;
translations.y += translations.z * tfactor * dv.y;
break;
case Camera::SCALE:
translations.z *= (1.0f - sfactor * dv.y);
break;
}
mousePrev = mouseCurr;
}
void Camera::applyProjectionMatrix(std::shared_ptr<MatrixStack> P) const
{
// Modify provided MatrixStack
P->multMatrix(glm::perspective(fovy, aspect, znear, zfar));
}
void Camera::applyViewMatrix(std::shared_ptr<MatrixStack> MV) const
{
MV->translate(translations);
MV->rotate(rotations.y, glm::vec3(1.0f, 0.0f, 0.0f));
MV->rotate(rotations.x, glm::vec3(0.0f, 1.0f, 0.0f));
}

47
L07/src/Camera.h Normal file
View file

@ -0,0 +1,47 @@
#pragma once
#ifndef __Camera__
#define __Camera__
#include <memory>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
class MatrixStack;
class Camera
{
public:
enum {
ROTATE = 0,
TRANSLATE,
SCALE
};
Camera();
virtual ~Camera();
void setInitDistance(float z) { translations.z = -std::abs(z); }
void setAspect(float a) { aspect = a; };
void setRotationFactor(float f) { rfactor = f; };
void setTranslationFactor(float f) { tfactor = f; };
void setScaleFactor(float f) { sfactor = f; };
void mouseClicked(float x, float y, bool shift, bool ctrl, bool alt);
void mouseMoved(float x, float y);
void applyProjectionMatrix(std::shared_ptr<MatrixStack> P) const;
void applyViewMatrix(std::shared_ptr<MatrixStack> MV) const;
private:
float aspect;
float fovy;
float znear;
float zfar;
glm::vec2 rotations;
glm::vec3 translations;
glm::vec2 mousePrev;
int state;
float rfactor;
float tfactor;
float sfactor;
};
#endif

152
L07/src/GLSL.cpp Normal file
View file

@ -0,0 +1,152 @@
//
// Many useful helper functions for GLSL shaders - gleaned from various sources including orange book
// Created by zwood on 2/21/10.
// Modified by sueda 10/15/15.
//
#include "GLSL.h"
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#include <cstring>
using namespace std;
namespace GLSL {
const char * errorString(GLenum err)
{
switch(err) {
case GL_NO_ERROR:
return "No error";
case GL_INVALID_ENUM:
return "Invalid enum";
case GL_INVALID_VALUE:
return "Invalid value";
case GL_INVALID_OPERATION:
return "Invalid operation";
case GL_STACK_OVERFLOW:
return "Stack overflow";
case GL_STACK_UNDERFLOW:
return "Stack underflow";
case GL_OUT_OF_MEMORY:
return "Out of memory";
default:
return "No error";
}
}
void checkVersion()
{
int major, minor;
major = minor = 0;
const char *verstr = (const char *)glGetString(GL_VERSION);
if((verstr == NULL) || (sscanf(verstr, "%d.%d", &major, &minor) != 2)) {
printf("Invalid GL_VERSION format %d.%d\n", major, minor);
}
if(major < 2) {
printf("This shader example will not work due to the installed Opengl version, which is %d.%d.\n", major, minor);
exit(0);
}
}
void checkError(const char *str)
{
GLenum glErr = glGetError();
if(glErr != GL_NO_ERROR) {
if(str) {
printf("%s: ", str);
}
printf("GL_ERROR = %s.\n", errorString(glErr));
assert(false);
}
}
void printShaderInfoLog(GLuint shader)
{
GLint infologLength = 0;
GLint charsWritten = 0;
GLchar *infoLog = 0;
checkError(GET_FILE_LINE);
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infologLength);
checkError(GET_FILE_LINE);
if(infologLength > 0) {
infoLog = (GLchar *)malloc(infologLength);
if(infoLog == NULL) {
puts("ERROR: Could not allocate InfoLog buffer");
exit(1);
}
glGetShaderInfoLog(shader, infologLength, &charsWritten, infoLog);
checkError(GET_FILE_LINE);
printf("Shader InfoLog:\n%s\n\n", infoLog);
free(infoLog);
}
}
void printProgramInfoLog(GLuint program)
{
GLint infologLength = 0;
GLint charsWritten = 0;
GLchar *infoLog = 0;
checkError(GET_FILE_LINE);
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infologLength);
checkError(GET_FILE_LINE);
if(infologLength > 0) {
infoLog = (GLchar *)malloc(infologLength);
if(infoLog == NULL) {
puts("ERROR: Could not allocate InfoLog buffer");
exit(1);
}
glGetProgramInfoLog(program, infologLength, &charsWritten, infoLog);
checkError(GET_FILE_LINE);
printf("Program InfoLog:\n%s\n\n", infoLog);
free(infoLog);
}
}
char *textFileRead(const char *fn)
{
FILE *fp;
char *content = NULL;
int count = 0;
if(fn != NULL) {
fp = fopen(fn,"rt");
if(fp != NULL) {
fseek(fp, 0, SEEK_END);
count = (int)ftell(fp);
rewind(fp);
if(count > 0) {
content = (char *)malloc(sizeof(char) * (count+1));
count = (int)fread(content,sizeof(char),count,fp);
content[count] = '\0';
}
fclose(fp);
} else {
printf("error loading %s\n", fn);
}
}
return content;
}
int textFileWrite(const char *fn, const char *s)
{
FILE *fp;
int status = 0;
if(fn != NULL) {
fp = fopen(fn,"w");
if(fp != NULL) {
if(fwrite(s,sizeof(char),strlen(s),fp) == strlen(s)) {
status = 1;
}
fclose(fp);
}
}
return(status);
}
}

40
L07/src/GLSL.h Normal file
View file

@ -0,0 +1,40 @@
//
// Many useful helper functions for GLSL shaders - gleaned from various sources including orange book
// Created by zwood on 2/21/10.
// Modified by sueda 10/15/15.
//
#pragma once
#ifndef __GLSL__
#define __GLSL__
#define GLEW_STATIC
#include <GL/glew.h>
///////////////////////////////////////////////////////////////////////////////
// For printing out the current file and line number //
///////////////////////////////////////////////////////////////////////////////
#include <sstream>
template <typename T>
std::string NumberToString(T x)
{
std::ostringstream ss;
ss << x;
return ss.str();
}
#define GET_FILE_LINE (std::string(__FILE__) + ":" + NumberToString(__LINE__)).c_str()
///////////////////////////////////////////////////////////////////////////////
namespace GLSL {
void checkVersion();
void checkError(const char *str = 0);
void printProgramInfoLog(GLuint program);
void printShaderInfoLog(GLuint shader);
int textFileWrite(const char *filename, const char *s);
char *textFileRead(const char *filename);
}
#endif

114
L07/src/MatrixStack.cpp Normal file
View file

@ -0,0 +1,114 @@
#include "MatrixStack.h"
#include <stdio.h>
#include <cassert>
#include <vector>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
using namespace std;
MatrixStack::MatrixStack()
{
mstack = make_shared< stack<glm::mat4> >();
mstack->push(glm::mat4(1.0));
}
MatrixStack::~MatrixStack()
{
}
void MatrixStack::pushMatrix()
{
const glm::mat4 &top = mstack->top();
mstack->push(top);
assert(mstack->size() < 100);
}
void MatrixStack::popMatrix()
{
assert(!mstack->empty());
mstack->pop();
// There should always be one matrix left.
assert(!mstack->empty());
}
void MatrixStack::loadIdentity()
{
glm::mat4 &top = mstack->top();
top = glm::mat4(1.0);
}
void MatrixStack::translate(const glm::vec3 &t)
{
glm::mat4 &top = mstack->top();
top *= glm::translate(t);
}
void MatrixStack::translate(float x, float y, float z)
{
translate(glm::vec3(x, y, z));
}
void MatrixStack::scale(const glm::vec3 &s)
{
glm::mat4 &top = mstack->top();
top *= glm::scale(s);
}
void MatrixStack::scale(float x, float y, float z)
{
scale(glm::vec3(x, y, z));
}
void MatrixStack::scale(float s)
{
scale(glm::vec3(s, s, s));
}
void MatrixStack::rotate(float angle, const glm::vec3 &axis)
{
glm::mat4 &top = mstack->top();
top *= glm::rotate(angle, axis);
}
void MatrixStack::rotate(float angle, float x, float y, float z)
{
rotate(angle, glm::vec3(x, y, z));
}
void MatrixStack::multMatrix(const glm::mat4 &matrix)
{
glm::mat4 &top = mstack->top();
top *= matrix;
}
const glm::mat4 &MatrixStack::topMatrix() const
{
return mstack->top();
}
void MatrixStack::print(const glm::mat4 &mat, const char *name)
{
if(name) {
printf("%s = [\n", name);
}
for(int i = 0; i < 4; ++i) {
for(int j = 0; j < 4; ++j) {
// mat[j] returns the jth column
printf("%- 5.2f ", mat[j][i]);
}
printf("\n");
}
if(name) {
printf("];");
}
printf("\n");
}
void MatrixStack::print(const char *name) const
{
print(mstack->top(), name);
}

50
L07/src/MatrixStack.h Normal file
View file

@ -0,0 +1,50 @@
#pragma once
#ifndef _MatrixStack_H_
#define _MatrixStack_H_
#include <stack>
#include <memory>
#include <glm/fwd.hpp>
class MatrixStack
{
public:
MatrixStack();
virtual ~MatrixStack();
// glPushMatrix(): Copies the current matrix and adds it to the top of the stack
void pushMatrix();
// glPopMatrix(): Removes the top of the stack and sets the current matrix to be the matrix that is now on top
void popMatrix();
// glLoadIdentity(): Sets the top matrix to be the identity
void loadIdentity();
// glMultMatrix(): Right multiplies the top matrix
void multMatrix(const glm::mat4 &matrix);
// glTranslate(): Right multiplies the top matrix by a translation matrix
void translate(const glm::vec3 &trans);
void translate(float x, float y, float z);
// glScale(): Right multiplies the top matrix by a scaling matrix
void scale(const glm::vec3 &scale);
void scale(float x, float y, float z);
// glScale(): Right multiplies the top matrix by a scaling matrix
void scale(float size);
// glRotate(): Right multiplies the top matrix by a rotation matrix (angle in radians)
void rotate(float angle, const glm::vec3 &axis);
void rotate(float angle, float x, float y, float z);
// glGet(GL_MODELVIEW_MATRIX): Gets the top matrix
const glm::mat4 &topMatrix() const;
// Prints out the specified matrix
static void print(const glm::mat4 &mat, const char *name = 0);
// Prints out the top matrix
void print(const char *name = 0) const;
private:
std::shared_ptr< std::stack<glm::mat4> > mstack;
};
#endif

126
L07/src/Program.cpp Normal file
View file

@ -0,0 +1,126 @@
#include "Program.h"
#include <iostream>
#include <cassert>
#include "GLSL.h"
using namespace std;
Program::Program() :
vShaderName(""),
fShaderName(""),
pid(0),
verbose(true)
{
}
Program::~Program()
{
}
void Program::setShaderNames(const string &v, const string &f)
{
vShaderName = v;
fShaderName = f;
}
bool Program::init()
{
GLint rc;
// Create shader handles
GLuint VS = glCreateShader(GL_VERTEX_SHADER);
GLuint FS = glCreateShader(GL_FRAGMENT_SHADER);
// Read shader sources
const char *vshader = GLSL::textFileRead(vShaderName.c_str());
const char *fshader = GLSL::textFileRead(fShaderName.c_str());
glShaderSource(VS, 1, &vshader, NULL);
glShaderSource(FS, 1, &fshader, NULL);
// Compile vertex shader
glCompileShader(VS);
glGetShaderiv(VS, GL_COMPILE_STATUS, &rc);
if(!rc) {
if(isVerbose()) {
GLSL::printShaderInfoLog(VS);
cout << "Error compiling vertex shader " << vShaderName << endl;
}
return false;
}
// Compile fragment shader
glCompileShader(FS);
glGetShaderiv(FS, GL_COMPILE_STATUS, &rc);
if(!rc) {
if(isVerbose()) {
GLSL::printShaderInfoLog(FS);
cout << "Error compiling fragment shader " << fShaderName << endl;
}
return false;
}
// Create the program and link
pid = glCreateProgram();
glAttachShader(pid, VS);
glAttachShader(pid, FS);
glLinkProgram(pid);
glGetProgramiv(pid, GL_LINK_STATUS, &rc);
if(!rc) {
if(isVerbose()) {
GLSL::printProgramInfoLog(pid);
cout << "Error linking shaders " << vShaderName << " and " << fShaderName << endl;
}
return false;
}
GLSL::checkError(GET_FILE_LINE);
return true;
}
void Program::bind()
{
glUseProgram(pid);
}
void Program::unbind()
{
glUseProgram(0);
}
void Program::addAttribute(const string &name)
{
attributes[name] = glGetAttribLocation(pid, name.c_str());
}
void Program::addUniform(const string &name)
{
uniforms[name] = glGetUniformLocation(pid, name.c_str());
}
GLint Program::getAttribute(const string &name) const
{
map<string,GLint>::const_iterator attribute = attributes.find(name.c_str());
if(attribute == attributes.end()) {
if(isVerbose()) {
cout << name << " is not an attribute variable" << endl;
}
return -1;
}
return attribute->second;
}
GLint Program::getUniform(const string &name) const
{
map<string,GLint>::const_iterator uniform = uniforms.find(name.c_str());
if(uniform == uniforms.end()) {
if(isVerbose()) {
cout << name << " is not a uniform variable" << endl;
}
return -1;
}
return uniform->second;
}

44
L07/src/Program.h Normal file
View file

@ -0,0 +1,44 @@
#pragma once
#ifndef __Program__
#define __Program__
#include <map>
#include <string>
#define GLEW_STATIC
#include <GL/glew.h>
/**
* An OpenGL Program (vertex and fragment shaders)
*/
class Program
{
public:
Program();
virtual ~Program();
void setVerbose(bool v) { verbose = v; }
bool isVerbose() const { return verbose; }
void setShaderNames(const std::string &v, const std::string &f);
virtual bool init();
virtual void bind();
virtual void unbind();
void addAttribute(const std::string &name);
void addUniform(const std::string &name);
GLint getAttribute(const std::string &name) const;
GLint getUniform(const std::string &name) const;
protected:
std::string vShaderName;
std::string fShaderName;
private:
GLuint pid;
std::map<std::string,GLint> attributes;
std::map<std::string,GLint> uniforms;
bool verbose;
};
#endif

347
L07/src/main.cpp Normal file
View file

@ -0,0 +1,347 @@
#include <cassert>
#include <cstring>
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <vector>
#include <map>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Camera.h"
#include "GLSL.h"
#include "MatrixStack.h"
#include "Program.h"
using namespace std;
GLFWwindow *window; // Main application window
string RESOURCE_DIR = "./"; // Where the resources are loaded from
shared_ptr<Camera> camera;
shared_ptr<Program> prog;
map<string,GLuint> bufIDs;
int indCount;
bool keyToggles[256] = {false}; // only for English keyboards!
// This function is called when a GLFW error occurs
static void error_callback(int error, const char *description)
{
cerr << description << endl;
}
// This function is called when a key is pressed
static void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
// This function is called when the mouse is clicked
static void mouse_button_callback(GLFWwindow *window, int button, int action, int mods)
{
// Get the current mouse position.
double xmouse, ymouse;
glfwGetCursorPos(window, &xmouse, &ymouse);
// Get current window size.
int width, height;
glfwGetWindowSize(window, &width, &height);
if(action == GLFW_PRESS) {
bool shift = (mods & GLFW_MOD_SHIFT) != 0;
bool ctrl = (mods & GLFW_MOD_CONTROL) != 0;
bool alt = (mods & GLFW_MOD_ALT) != 0;
camera->mouseClicked((float)xmouse, (float)ymouse, shift, ctrl, alt);
}
}
// This function is called when the mouse moves
static void cursor_position_callback(GLFWwindow* window, double xmouse, double ymouse)
{
int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);
if(state == GLFW_PRESS) {
camera->mouseMoved((float)xmouse, (float)ymouse);
}
}
static void char_callback(GLFWwindow *window, unsigned int key)
{
keyToggles[key] = !keyToggles[key];
}
// If the window is resized, capture the new size and reset the viewport
static void resize_callback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
// This function is called once to initialize the scene and OpenGL
static void init()
{
//
// General setup
//
// Initialize time.
glfwSetTime(0.0);
// Set background color.
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
// Enable z-buffer test.
glEnable(GL_DEPTH_TEST);
prog = make_shared<Program>();
prog->setShaderNames(RESOURCE_DIR + "vert.glsl", RESOURCE_DIR + "frag.glsl");
prog->init();
prog->addAttribute("aPos");
prog->addAttribute("aNor");
prog->addUniform("MV");
prog->addUniform("P");
camera = make_shared<Camera>();
camera->setInitDistance(2.0f);
//
// Vertex buffer setup
//
vector<float> posBuf;
vector<float> norBuf;
vector<unsigned int> indBuf;
//
// IMPLEMENT ME
//
// Instead of the hard coded square below, you need to draw a height field.
// You need to use one or more for-loops to fill in the position buffer,
// normal buffer, and the index buffer.
//
/*
// Vert 0
posBuf.push_back(-0.5f);
posBuf.push_back(-0.5f);
posBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(1.0f);
// Vert 1
posBuf.push_back(0.5f);
posBuf.push_back(-0.5f);
posBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(1.0f);
// Vert 2
posBuf.push_back(-0.5f);
posBuf.push_back(0.5f);
posBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(1.0f);
// Vert 3
posBuf.push_back(0.5f);
posBuf.push_back(0.5f);
posBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(0.0f);
norBuf.push_back(1.0f);
// indices
indBuf.push_back(0);
indBuf.push_back(1);
indBuf.push_back(3);
indBuf.push_back(0);
indBuf.push_back(3);
indBuf.push_back(2);
*/
//
// END IMPLEMENT ME
//
int rows = 100;
int cols = 100;
int index = 0;
float dpdx = 0.0f;
float dpdy = 0.0f;
float magnitude = 0.0f;
for(int r = 0; r <= rows; r++)
{
for(int c = 0; c <= cols; c++)
{
posBuf.push_back(((float)c/cols) - 0.5); // x
posBuf.push_back(((float)r/rows) - 0.5); // y
posBuf.push_back((1.0/20)*(cos(20*((float)r/rows)) + sin(20*((float)c/cols)))); // z
dpdx = -sin(20*((float)c/cols));
dpdy = -cos(20*((float)r/rows));
magnitude = sqrt((dpdx*dpdx)+(dpdy*dpdy)+(1));
norBuf.push_back(-dpdx/magnitude); // x
norBuf.push_back(dpdy/magnitude); // y
norBuf.push_back(1/magnitude); // z
if(c != cols && r != rows)
{
indBuf.push_back(index);
indBuf.push_back(index + 1);
indBuf.push_back(index + cols + 2);
indBuf.push_back(index);
indBuf.push_back(index + cols + 2);
indBuf.push_back(index + cols + 1);
index++;
}
else
{
index ++;
}
}
}
// Total number of indices
indCount = (int)indBuf.size();
// Generate 3 buffer IDs and put them in the bufIDs map.
GLuint tmp[3];
glGenBuffers(3, tmp);
bufIDs["bPos"] = tmp[0];
bufIDs["bNor"] = tmp[1];
bufIDs["bInd"] = tmp[2];
glBindBuffer(GL_ARRAY_BUFFER, bufIDs["bPos"]);
glBufferData(GL_ARRAY_BUFFER, posBuf.size()*sizeof(float), &posBuf[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, bufIDs["bNor"]);
glBufferData(GL_ARRAY_BUFFER, norBuf.size()*sizeof(float), &norBuf[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufIDs["bInd"]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indBuf.size()*sizeof(unsigned int), &indBuf[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
assert(norBuf.size() == posBuf.size());
GLSL::checkError(GET_FILE_LINE);
}
// This function is called every frame to draw the scene.
static void render()
{
// Clear framebuffer.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(keyToggles[(unsigned)'c']) {
glEnable(GL_CULL_FACE);
} else {
glDisable(GL_CULL_FACE);
}
if(keyToggles[(unsigned)'l']) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} else {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
// Get current frame buffer size.
int width, height;
glfwGetFramebufferSize(window, &width, &height);
camera->setAspect((float)width/(float)height);
// Matrix stacks
auto P = make_shared<MatrixStack>();
auto MV = make_shared<MatrixStack>();
// Apply camera transforms
P->pushMatrix();
camera->applyProjectionMatrix(P);
MV->pushMatrix();
camera->applyViewMatrix(MV);
prog->bind();
glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, value_ptr(P->topMatrix()));
glEnableVertexAttribArray(prog->getAttribute("aPos"));
glEnableVertexAttribArray(prog->getAttribute("aNor"));
glBindBuffer(GL_ARRAY_BUFFER, bufIDs["bPos"]);
glVertexAttribPointer(prog->getAttribute("aPos"), 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glBindBuffer(GL_ARRAY_BUFFER, bufIDs["bNor"]);
glVertexAttribPointer(prog->getAttribute("aNor"), 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufIDs["bInd"]);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE, value_ptr(MV->topMatrix()));
glDrawElements(GL_TRIANGLES, indCount, GL_UNSIGNED_INT, (void *)0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(prog->getAttribute("aNor"));
glDisableVertexAttribArray(prog->getAttribute("aPos"));
prog->unbind();
MV->popMatrix();
P->popMatrix();
GLSL::checkError(GET_FILE_LINE);
}
int main(int argc, char **argv)
{
if(argc < 2) {
cout << "Please specify the resource directory." << endl;
return 0;
}
RESOURCE_DIR = argv[1] + string("/");
// Set error callback.
glfwSetErrorCallback(error_callback);
// Initialize the library.
if(!glfwInit()) {
return -1;
}
// Create a windowed mode window and its OpenGL context.
window = glfwCreateWindow(640, 480, "YOUR NAME", NULL, NULL);
if(!window) {
glfwTerminate();
return -1;
}
// Make the window's context current.
glfwMakeContextCurrent(window);
// Initialize GLEW.
glewExperimental = true;
if(glewInit() != GLEW_OK) {
cerr << "Failed to initialize GLEW" << endl;
return -1;
}
glGetError(); // A bug in glewInit() causes an error that we can safely ignore.
cout << "OpenGL version: " << glGetString(GL_VERSION) << endl;
cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;
GLSL::checkVersion();
// Set vsync.
glfwSwapInterval(1);
// Set keyboard callback.
glfwSetKeyCallback(window, key_callback);
// Set char callback.
glfwSetCharCallback(window, char_callback);
// Set cursor position callback.
glfwSetCursorPosCallback(window, cursor_position_callback);
// Set mouse button callback.
glfwSetMouseButtonCallback(window, mouse_button_callback);
// Set the window resize call back.
glfwSetFramebufferSizeCallback(window, resize_callback);
// Initialize scene.
init();
// Loop until the user closes the window.
while(!glfwWindowShouldClose(window)) {
// Render scene.
render();
// Swap front and back buffers.
glfwSwapBuffers(window);
// Poll for and process events.
glfwPollEvents();
}
// Quit program.
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}