Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //=============================================================================================
- // Triangle with smooth color and interactive polyline
- //=============================================================================================
- #define _USE_MATH_DEFINES
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <vector>
- #if defined(__APPLE__)
- #include <GLUT/GLUT.h>
- #include <OpenGL/gl3.h>
- #include <OpenGL/glu.h>
- #else
- #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
- #include <windows.h>
- #endif
- #include <GL/glew.h> // must be downloaded
- #include <GL/freeglut.h> // must be downloaded unless you have an Apple
- #endif
- const unsigned int windowWidth = 600, windowHeight = 600;
- // OpenGL major and minor versions
- int majorVersion = 3, minorVersion = 3;
- void getErrorInfo(unsigned int handle) {
- int logLen;
- glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logLen);
- if (logLen > 0) {
- char * log = new char[logLen];
- int written;
- glGetShaderInfoLog(handle, logLen, &written, log);
- printf("Shader log:\n%s", log);
- delete log;
- }
- }
- // check if shader could be compiled
- void checkShader(unsigned int shader, const char * message) {
- int OK;
- glGetShaderiv(shader, GL_COMPILE_STATUS, &OK);
- if (!OK) { printf("%s!\n", message); getErrorInfo(shader); }
- }
- void gl_log_call(const char* stmt, const char* file, int line) {
- if (GLenum err = glGetError()) {
- printf("OpenGL error: %d in file '%s', at line %s, statement '%d'",
- int(err), file, line, stmt);
- }
- }
- #define GLCall(x) \
- do { \
- while (glGetError() != GL_NO_ERROR); \
- x; \
- gl_log_call(#x, __FILE__, __LINE__); \
- } while (0)
- // check if shader could be linked
- void checkLinking(unsigned int program) {
- int OK;
- glGetProgramiv(program, GL_LINK_STATUS, &OK);
- if (!OK) { printf("Failed to link shader program!\n"); getErrorInfo(program); }
- }
- // vertex shader in GLSL
- const char * vertexSource = R"(
- #version 330
- precision highp float;
- uniform mat4 MVP; // Model-View-Projection matrix in row-major format
- layout(location = 0) in vec2 vertexPosition; // Attrib Array 0
- layout(location = 1) in vec3 vertexColor; // Attrib Array 1
- out vec3 color; // output attribute
- void main() {
- color = vertexColor; // copy color from input to output
- gl_Position = vec4(vertexPosition.x, vertexPosition.y, 0, 1) * MVP; // transform to clipping space
- }
- )";
- // fragment shader in GLSL
- const char * fragmentSource = R"(
- #version 330
- precision highp float;
- in vec3 color; // variable input: interpolated color of vertex shader
- out vec4 fragmentColor; // output that goes to the raster memory as told by glBindFragDataLocation
- void main() {
- fragmentColor = vec4(color, 1); // extend RGB to RGBA
- }
- )";
- // row-major matrix 4x4
- struct mat4 {
- float m[4][4];
- public:
- mat4() {}
- mat4(float m00, float m01, float m02, float m03,
- float m10, float m11, float m12, float m13,
- float m20, float m21, float m22, float m23,
- float m30, float m31, float m32, float m33) {
- m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[0][3] = m03;
- m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[1][3] = m13;
- m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; m[2][3] = m23;
- m[3][0] = m30; m[3][1] = m31; m[3][2] = m32; m[3][3] = m33;
- }
- mat4 operator*(const mat4& right) {
- mat4 result;
- for (int i = 0; i < 4; i++) {
- for (int j = 0; j < 4; j++) {
- result.m[i][j] = 0;
- for (int k = 0; k < 4; k++) result.m[i][j] += m[i][k] * right.m[k][j];
- }
- }
- return result;
- }
- operator float*() { return &m[0][0]; }
- };
- // 3D point in homogeneous coordinates
- struct vec4 {
- float x, y, z, w;
- vec4(float _x = 0, float _y = 0, float _z = 0, float _w = 1) { x = _x; y = _y; z = _z; w = _w; }
- vec4 operator*(const mat4& mat) {
- return vec4(x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0] + w * mat.m[3][0],
- x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1] + w * mat.m[3][1],
- x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] + w * mat.m[3][2],
- x * mat.m[0][3] + y * mat.m[1][3] + z * mat.m[2][3] + w * mat.m[3][3]);
- }
- vec4 operator* (float f) {
- vec4 ret = *this;
- ret.x *= f;
- ret.y *= f;
- ret.z *= f;
- ret.w *= f;
- return ret;
- }
- vec4 const& operator+= (vec4 vec) {
- x += vec.x;
- y += vec.y;
- z += vec.z;
- w += vec.w;
- return *this;
- }
- vec4 operator-(vec4 const& right) {
- vec4 res(x- right.x, y - right.y, z - right.y);
- return res;
- }
- vec4 operator+(vec4 const& right) {
- vec4 res(x + right.x, y + right.y, z + right.y);
- return res;
- }
- };
- struct vec3 {
- float v[3];
- vec3(float x = 0, float y = 0, float z = 0)
- { v[0] = x; v[1] = y; v[2] = z; }
- vec3(const vec4& hom) { v[0] = hom.x / hom.w; v[1] = hom.y / hom.w; v[2] = hom.z / hom.w; }
- vec3 operator*(float s) {
- vec3 res(v[0] * s, v[1] * s, v[2] * s);
- return res;
- }
- };
- // 2D point in Cartesian coordinates
- struct vec2 {
- float v[2];
- vec2(float x = 0, float y = 0) { v[0] = x; v[1] = y; }
- vec2(const vec4& hom) { v[0] = hom.x / hom.w; v[1] = hom.y / hom.w; }
- vec2 operator-(vec2& right) {
- vec2 res(v[0] - right.v[0], v[1] - right.v[1]);
- return res;
- }
- float Length() { return sqrtf(v[0] * v[0] + v[1] * v[1]); }
- };
- float dot(const vec4& left, const vec4& right) {
- return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
- }
- // 2D camera
- struct Camera {
- float wCx, wCy; // center in world coordinates
- float wWx, wWy; // width and height in world coordinates
- float n = -500;
- float p = 500;
- public:
- Camera() {
- Animate(0);
- }
- mat4 V() { // view matrix: translates the center to the origin
- return
- mat4(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);//-wCx, -wCy, 0, 1);
- }
- mat4 P() { // projection matrix: scales it to be a square of edge length 2
- return mat4(2 / wWx, 0, 0, 0,
- 0, 2 / wWy, 0, 0,
- 0, 0, 1/(n-p), 0,
- 0, 0, (p+n)/(p-n), 1);
- }
- mat4 Vinv() { // inverse view matrix
- return mat4(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- wCx, wCy, 0, 1);
- }
- mat4 Pinv() { // inverse projection matrix
- return mat4(wWx / 2, 0, 0, 0,
- 0, wWy / 2, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- }
- void Animate(float t) {
- wCx = 0; // 10 * cosf(t);
- wCy = 0;
- wWx = 20;
- wWy = 20;
- }
- };
- struct Texture {
- unsigned int textureId;
- int width, height;
- vec3 *image;
- Texture(int w, int h, vec3* i) {
- width = w;
- height = h;
- image = i;
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, image); //Texture -> GPU
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glGenTextures(1, &textureId);
- glBindTexture(GL_TEXTURE_2D, textureId); // binding
- }
- };
- // 2D camera
- Camera camera;
- // handle of the shader program
- unsigned int shaderProgram;
- class Triangle {
- unsigned int vao; // vertex array object id
- float sx, sy; // scaling
- float wTx, wTy; // translation
- float phi;
- public:
- Triangle() { Animate(0); }
- void Create() {
- glGenVertexArrays(1, &vao); // create 1 vertex array object
- glBindVertexArray(vao); // make it active
- unsigned int vbo[2]; // vertex buffer objects
- glGenBuffers(2, &vbo[0]); // Generate 2 vertex buffer objects
- // vertex coordinates: vbo[0] -> Attrib Array 0 -> vertexPosition of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); // make it active, it is an array
- float vertexCoords[] = { -8, -8, -6, 10, 8, -2 }; // vertex data on the CPU
- glBufferData(GL_ARRAY_BUFFER, // copy to the GPU
- sizeof(vertexCoords), // number of the vbo in bytes
- vertexCoords, // address of the data array on the CPU
- GL_STATIC_DRAW); // copy to that part of the memory which is not modified
- // Map Attribute Array 0 to the current bound vertex buffer (vbo[0])
- glEnableVertexAttribArray(0);
- // Data organization of Attribute Array 0
- glVertexAttribPointer(0, // Attribute Array 0
- 2, GL_FLOAT, // components/attribute, component type
- GL_FALSE, // not in fixed point format, do not normalized
- 0, NULL); // stride and offset: it is tightly packed
- // vertex colors: vbo[1] -> Attrib Array 1 -> vertexColor of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); // make it active, it is an array
- float vertexColors[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; // vertex data on the CPU
- glBufferData(GL_ARRAY_BUFFER, sizeof(vertexColors), vertexColors, GL_STATIC_DRAW); // copy to the GPU
- // Map Attribute Array 1 to the current bound vertex buffer (vbo[1])
- glEnableVertexAttribArray(1); // Vertex position
- // Data organization of Attribute Array 1
- glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL); // Attribute Array 1, components/attribute, component type, normalize?, tightly packed
- }
- void Animate(float t) {
- sx = 1; // sinf(t);
- sy = 1; // cosf(t);
- wTx = 1; // 4 * cosf(t / 2);
- wTy = 0; // 4 * sinf(t / 2);
- phi = t;
- }
- void Draw() {
- mat4 Mscale(sx, 0, 0, 0,
- 0, sy, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 1); // model matrix
- mat4 Mtranslate(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 0, 0,
- wTx, wTy, 0, 1); // model matrix
- mat4 Mrotate(cosf(phi), sinf(phi), 0, 0,
- -sinf(phi), cosf(phi), 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1); // model matrix
- //mat4 Mshift(1, 0, 0, 0,
- // 0, 1, 0, 0,
- // X, Y, 0, 0,
- // 0, 0, 0, 1);
- mat4 MVPTransform = Mscale * Mtranslate * Mrotate * camera.V() * camera.P();
- // set GPU uniform matrix variable MVP with the content of CPU variable MVPTransform
- int location = glGetUniformLocation(shaderProgram, "MVP");
- if (location >= 0) glUniformMatrix4fv(location, 1, GL_TRUE, MVPTransform); // set uniform variable MVP to the MVPTransform
- else printf("uniform MVP cannot be set\n");
- glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
- glDrawArrays(GL_TRIANGLES, 0, 3); // draw a single triangle with vertices defined in vao
- }
- };
- //##########################################################################################################
- class Circle {
- unsigned int vao; // vertex array object id
- float sx, sy; // scaling
- float wTx, wTy; // translation
- float density = 0.1; //kör pontjainak sűrűsége
- int dotCount;
- vec4 origo;
- float size;
- float rot;
- vec4 speed;
- vec4 movement;
- public:
- Circle(float siz = 4, vec4 o = (0, 0)) {
- size = siz;
- origo = o;
- Animate(0, 0);
- }
- vec4 getOrigo() {
- return origo;
- }
- void setOrigo(vec4 o) {
- origo = o;
- }
- void Create() {
- glGenVertexArrays(1, &vao); // create 1 vertex array object
- glBindVertexArray(vao); // make it active
- unsigned int vbo[2]; // vertex buffer objects
- glGenBuffers(2, &vbo[0]); // Generate 2 vertex buffer objects
- // vertex coordinates: vbo[0] -> Attrib Array 0 -> vertexPosition of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); // make it active, it is an array
- std::vector<vec4> points;
- vec4 pre(0, 0);
- for (float i = 0; i <= 2*M_PI; i=i+density) {
- vec4 point(origo);
- point.x += cosf(i)*size;
- point.y += sinf(i)*size;
- if (i > 0) {
- points.push_back(point);
- points.push_back(origo);
- points.push_back(pre);
- }
- pre = point;
- }
- points.push_back(pre);
- points.push_back(origo);
- points.push_back(points[0]);
- dotCount = points.size();
- for (int i = 0; i < points.size(); i++) {
- //printf("%f %f\n", points[i].x, points[i].y);
- }
- //printf("\n%d ", dotCount);
- glBufferData(GL_ARRAY_BUFFER, // copy to the GPU
- points.size()*sizeof(vec4), // number of the vbo in bytes
- &points[0], // address of the data array on the CPU
- GL_STATIC_DRAW); // copy to that part of the memory which is not modified
- // Map Attribute Array 0 to the current bound vertex buffer (vbo[0])
- glEnableVertexAttribArray(0);
- // Data organization of Attribute Array 0
- glVertexAttribPointer(0, // Attribute Array 0
- 4, GL_FLOAT, // components/attribute, component type vec4
- GL_FALSE, // not in fixed point format, do not normalized
- 0, NULL); // stride and offset: it is tightly packed
- // vertex colors: vbo[1] -> Attrib Array 1 -> vertexColor of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); // make it active, it is an array
- std::vector<vec4> colors;
- vec4 color(0, 0, 0);
- for (int i = 0; i < dotCount; i++) {
- colors.push_back(color);
- } // vertex data on the CPU
- glBufferData(GL_ARRAY_BUFFER, sizeof(vec4)*colors.size(), &colors[0], GL_STATIC_DRAW); // copy to the GPU
- // Map Attribute Array 1 to the current bound vertex buffer (vbo[1])
- glEnableVertexAttribArray(1); // Vertex position
- // Data organization of Attribute Array 1
- glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL); // Attribute Array 1, components/attribute, component type, normalize?, tightly packed
- }
- void Animate(float t, vec4 sp) {
- sx = 1; //sinf(t);
- sy = 1; // cosf(t);
- wTx = 0; // 4 * cosf(t / 2);
- wTy = 0; // 4 * sinf(t / 2
- speed = sp;
- }
- void Draw(float rate){
- rot = atan2f(speed.x, speed.y);
- mat4 Mscale(rate, 0, 0, 0,
- 0, sy, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 1); // model matrix
- mat4 Mtranslate(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 0, 0,
- wTx, wTy, 0, 1); // model matrix
- mat4 MrotateY(
- cosf(atan2f(speed.x, speed.y)), 0, sinf(atan2f(speed.x, speed.y)), 0,
- 0, 1, 0, 0,
- -sinf(atan2f(speed.x, speed.y)), 0, cosf(atan2f(speed.x, speed.y)), 0,
- 0, 0, 0, 1);
- mat4 MrotateZ(
- cosf(rot), -sin(rot), 0, 0,
- sinf(rot), cosf(rot), 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- mat4 MVPTransform = Mscale * Mtranslate * MrotateZ * camera.V() * camera.P();
- // set GPU uniform matrix variable MVP with the content of CPU variable MVPTransform
- int location = glGetUniformLocation(shaderProgram, "MVP");
- if (location >= 0) glUniformMatrix4fv(location, 1, GL_TRUE, MVPTransform); // set uniform variable MVP to the MVPTransform
- else printf("uniform MVP cannot be set\n");
- glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
- glDrawArrays(GL_TRIANGLES, 0, dotCount); // draw a single triangle with vertices defined in vao dotCount szamu haromszog,
- }
- };
- //##########################################################################################################
- vec4 mouse_pos;
- class Wing {
- unsigned int vao; // vertex array object id
- float sx, sy; // scaling
- float wTx, wTy; // translation
- int dotCount;
- float phi;
- float rot;
- vec4 speed;
- vec4 movement;
- std::vector<vec4> cps; // control pts
- float B(int i, float t) {
- int n = cps.size() - 1; // n deg polynomial = n+1 pts!
- float choose = 1;
- for (int j = 1; j <= i; j++) choose *= (float)(n - j + 1) / j;
- return choose * pow(t, i) * pow(1 - t, n - i);
- }
- public:
- void Add(vec4 cp) { cps.push_back(cp); }
- vec4 r(float t) {
- vec4 rr(0, 0, 0);
- for (int i = 0; i < cps.size(); i++) {
- rr += cps[i] * B(i, t);
- }
- return rr;
- }
- void Create() {
- glGenVertexArrays(1, &vao); // create 1 vertex array object
- glBindVertexArray(vao); // make it active
- unsigned int vbo[2]; // vertex buffer objects
- glGenBuffers(2, &vbo[0]); // Generate 2 vertex buffer objects
- // vertex coordinates: vbo[0] -> Attrib Array 0 -> vertexPosition of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); // make it active, it is an array
- vec4 root(0.0, 0.0);
- vec4 point(root);
- Add(point); //Add(point);
- Add(point += vec4(1.3, 1.4)); //Add(vec4(1.8, 4.2));
- Add(point += vec4(1.2, -1.4)); //Add(vec4(3.0, 2.8));
- Add(point += vec4(1.2, -1.4)); //Add(vec4(4.2, 1.4));
- Add(point += vec4(1.4, -1.4)); //Add(vec4(5.6, 0.0));
- Add(point += vec4(-1.2, -0.4)); //Add(vec4(4.4, -1.6));
- Add(point += vec4(-3.0, -0.4)); //Add(vec4(1.4, -0.8));
- Add(point += vec4(0.5, -0.4)); //Add(vec4(1.9, -1.2));
- Add(point += vec4(1.2, -1.4)); //Add(vec4(3.1, -2.6));
- Add(point += vec4(-1.0, -1.4)); //Add(vec4(2.1, -4.0));
- Add(point += vec4(-0.2, -1.2)); //Add(vec4(1.9, -5.2));
- //Add(vec4(2.8, -4.2));
- Add(point += vec4(2.4, 1.4)); //Add(vec4(4.3, -3.8));
- Add(point += vec4(-1.2, -0.4)); //Add(vec4(3.1, -4.2));
- Add(point += vec4(-0.6, -0.4)); //Add(vec4(2.5, -4.6));
- Add(point += vec4(-1.3, -0.4)); //Add(vec4(1.2, -5.0));
- Add(point += vec4(0.4, -0, 4)); // Add(vec4(1.6, -6.4));
- Add(point += vec4(0.4, 0.6)); //Add(vec4(2.0, -5.8));
- Add(point += vec4(-2.0, -0.8)); //Add(vec4(0, -6.6));
- Add(root);
- //float width = 0.05;
- std::vector<vec4> line;
- std::vector<vec4> tex;
- vec4 pre(0, 0);
- float max = 0;
- float min = 0;
- for (float i = 0; i < 1; i = i + 0.01) {
- //vec4 temp(i, i);
- vec4 temp(r(i));
- if (r(i).y > max)
- max = r(i).y;
- if (r(i).y < min)
- min = r(i).y;
- //float cosA = (temp.x - pre.x) / sqrt((temp.y - pre.y)*(temp.y - pre.y) + (temp.x - pre.x)*(temp.x - pre.x));
- //float sinA = (temp.y - pre.y) / sqrt((temp.y - pre.y)*(temp.y - pre.y) + (temp.x - pre.x)*(temp.x - pre.x));
- if (i > 0) {
- line.push_back(r(0));
- line.push_back(pre);
- line.push_back(temp);
- /*vec4 dot1, dot2, dot3, dot4;
- dot1.y = temp.y + (width / 2) * cosA;
- dot1.x = temp.x - (width / 2) * sinA;
- dot2.y = temp.y - (width / 2) * cosA;
- dot2.x = temp.x + (width / 2) * sinA;
- dot3.y = pre.y - (width / 2) * cosA;
- dot3.x = pre.x + (width / 2) * sinA;
- dot4.y = pre.y + (width / 2) * cosA;
- dot4.x = pre.x - (width / 2) * sinA;
- line.push_back(dot1);
- line.push_back(dot2);
- line.push_back(dot3);
- line.push_back(dot1);
- line.push_back(dot3);
- line.push_back(dot4);*/
- }
- pre = temp;
- }
- int width = 128;
- int height = 128;
- vec3 * image = new vec3[width * height];
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- float luminance = ((x / 16) % 2) ^ ((y / 16) % 2);
- int temp = y * width;
- image[temp + x] = vec3(luminance, luminance, luminance);
- }
- }
- Texture texture(width, height, image);
- for (int i = 0; i < line.size(); i++) {
- tex.push_back(vec4(line[i].x / ((0-min) + max), (line[i].y + (0-min)) / ((0-min) + max)));
- }
- //for (int i = 0; i < line.size(); i++) {
- // printf("%f %f\n", tex[i].x, tex[i].y);
- //}
- /*
- int sampler = 0;
- int location = glGetUniformLocation(shaderProg, "samplerUnit");
- glUniform1i(location, sampler);
- glActiveTexture(GL_TEXTURE0 + sampler);
- glBindTexture(GL_TEXTURE_2D, texture.textureId);
- glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, tex.size());
- */
- dotCount = line.size();
- //float vertexCoords[] = { -8, -8, -6, 10, 8, -2 }; // vertex data on the CPU
- GLCall(glBufferData(GL_ARRAY_BUFFER, // copy to the GPU
- line.size() * sizeof(vec4), // number of the vbo in bytes
- &line[0], // address of the data array on the CPU
- GL_STATIC_DRAW)); // copy to that part of the memory which is not modified
- // Map Attribute Array 0 to the current bound vertex buffer (vbo[0])
- glEnableVertexAttribArray(0);
- // Data organization of Attribute Array 0
- glVertexAttribPointer(0, // Attribute Array 0
- 4, GL_FLOAT, // components/attribute, component type vec4
- GL_FALSE, // not in fixed point format, do not normalized
- 0, NULL); // stride and offset: it is tightly packed
- // vertex colors: vbo[1] -> Attrib Array 1 -> vertexColor of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); // make it active, it is an array
- std::vector<vec4> colors;
- vec4 color(0.6, 0.3, 0.4);
- for (int i = 0; i < dotCount; i++) {
- colors.push_back(color);
- } // vertex data on the CPU
- GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(vec4)*colors.size(), &colors[0], GL_STATIC_DRAW)); // copy to the GPU
- // Map Attribute Array 1 to the current bound vertex buffer (vbo[1])
- glEnableVertexAttribArray(1); // Vertex position
- // Data organization of Attribute Array 1
- glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL); // Attribute Array 1, components/attribute, component type, normalize?, tightly packed
- }
- // NOTE: FORCE APPLY
- void Animate(float t, float dt) {
- sx = 1; //sinf(2*t);
- sy = 1; // cosf(t);
- wTx = 0.2; // 4 * cosf(t / 2);
- wTy = 3; // 4 * sinf(t / 2);
- phi = sin(3*t);
- // Body movement
- }
- void Draw() {
- rot = atan2f(speed.x, speed.y);
- mat4 Mscale(sx, 0, 0, 0,
- 0, sy, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 1); // model matrix
- mat4 Mtranslate(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 0, 0,
- wTx, wTy, 0, 1); // model matrix
- mat4 Mtranslate2(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 0, 0,
- speed.x, speed.y, 0, 1); // model matrix
- mat4 MrotateY(
- cosf(phi), 0, sinf(phi), 0,
- 0, 1, 0, 0,
- -sinf(phi), 0, cosf(phi), 0,
- 0, 0, 0, 1);
- mat4 MrotateZ(
- cosf(rot), -sinf(rot), 0, 0,
- sinf(rot), cosf(rot), 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1);
- mat4 Mmirror(-1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1); // model matrix
- mat4 MVPTransform = Mscale * Mtranslate * MrotateY * MrotateZ*Mtranslate2 * camera.V() * camera.P();
- mat4 MVPTransform2 = Mscale * Mtranslate * Mmirror * MrotateY * MrotateZ *Mtranslate2* camera.V() * camera.P();
- // set GPU uniform matrix variable MVP with the content of CPU variable MVPTransform
- int location = glGetUniformLocation(shaderProgram, "MVP");
- if (location >= 0) glUniformMatrix4fv(location, 1, GL_TRUE, MVPTransform); // set uniform variable MVP to the MVPTransform
- else printf("uniform MVP cannot be set\n");
- glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
- GLCall(glDrawArrays(GL_TRIANGLES, 0, dotCount)); // draw a single triangle with vertices defined in vao dotCount szamu haromszog,
- if (location >= 0) glUniformMatrix4fv(location, 1, GL_TRUE, MVPTransform2); // set uniform variable MVP to the MVPTransform
- else printf("uniform MVP cannot be set\n");
- glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
- GLCall(glDrawArrays(GL_TRIANGLES, 0, dotCount)); // draw a single triangle with vertices defined in vao dotCount szamu haromszog,
- }
- };
- class Butterfly {
- unsigned int vao; // vertex array object id
- float sx, sy; // scaling
- float wTx, wTy; // translation
- float phi;
- Wing wing;
- Circle circle;
- vec4 speed;
- vec4 accel;
- float weight;
- vec4 springForce;
- float windResistance;
- float SpringConstant;
- public:
- Butterfly() {
- weight = 1;
- springForce = vec4(0, 0);
- SpringConstant = 20;
- windResistance = 0.0005;
- speed = vec4(0, 0);
- accel = vec4(0, 0);
- circle = Circle(3.5);
- Animate(0);
- }
- float getWindResistance() {
- return windResistance;
- }
- void setAccel(vec4 acc) {
- accel = acc;
- }
- vec4 getAccel() {
- return accel;
- }
- float getWeight() {
- return weight;
- }
- float getSpringConstant() {
- return SpringConstant;
- }
- vec4 getSpringForce() {
- return springForce;
- }
- void setSpringForce(vec4 force) {
- springForce = force;
- }
- vec4 getSpeed() {
- return speed;
- }
- void setSpeed(vec4 sp) {
- speed = sp;
- printf("%f %f\n", speed.x, speed.y);
- }
- vec4 getPosition() {
- return circle.getOrigo();
- }
- void Create() {
- circle.Create();
- wing.Create();
- }
- void Animate(float t) {
- circle.Animate(t, speed);
- wing.Animate(t, speed);
- }
- void Draw() {
- circle.Draw(0.15);
- wing.Draw();
- }
- };
- bool isGPUProcedural = false;
- class Leaf {
- unsigned int vao; // vertex array object id
- float sx, sy; // scaling
- float wTx, wTy; // translation
- float density = 0.1; //kör pontjainak sűrűsége
- int dotCount;
- vec4 origo;
- float phi;
- vec4 circleOrigo;
- public:
- Leaf(float angle, vec4 circleo){
- phi = angle;
- circleOrigo = circleo;
- origo = vec4(0, 1);
- Animate(0);
- }
- void Create() {
- glGenVertexArrays(1, &vao); // create 1 vertex array object
- glBindVertexArray(vao); // make it active
- unsigned int vbo[2]; // vertex buffer objects
- glGenBuffers(2, &vbo[0]); // Generate 2 vertex buffer objects
- // vertex coordinates: vbo[0] -> Attrib Array 0 -> vertexPosition of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); // make it active, it is an array
- std::vector<vec4> points;
- vec4 pre(origo);
- for (float i = 0; i <= 2 * M_PI; i = i + density) {
- vec4 point(origo);
- point.x += cosf(i);
- point.y += sinf(i);
- if (i > 0) {
- points.push_back(point);
- points.push_back(origo);
- points.push_back(pre);
- }
- pre = point;
- }
- points.push_back(pre);
- points.push_back(origo);
- points.push_back(points[0]);
- dotCount = points.size();
- glBufferData(GL_ARRAY_BUFFER, // copy to the GPU
- points.size() * sizeof(vec4), // number of the vbo in bytes
- &points[0], // address of the data array on the CPU
- GL_STATIC_DRAW); // copy to that part of the memory which is not modified
- // Map Attribute Array 0 to the current bound vertex buffer (vbo[0])
- glEnableVertexAttribArray(0);
- // Data organization of Attribute Array 0
- glVertexAttribPointer(0, // Attribute Array 0
- 4, GL_FLOAT, // components/attribute, component type vec4
- GL_FALSE, // not in fixed point format, do not normalized
- 0, NULL); // stride and offset: it is tightly packed
- // vertex colors: vbo[1] -> Attrib Array 1 -> vertexColor of the vertex shader
- glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); // make it active, it is an array
- std::vector<vec4> colors;
- vec4 color(1, 1, 0);
- for (int i = 0; i < dotCount; i++) {
- colors.push_back(color);
- } // vertex data on the CPU
- glBufferData(GL_ARRAY_BUFFER, sizeof(vec4)*colors.size(), &colors[0], GL_STATIC_DRAW); // copy to the GPU
- // Map Attribute Array 1 to the current bound vertex buffer (vbo[1])
- glEnableVertexAttribArray(1); // Vertex position
- // Data organization of Attribute Array 1
- glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL); // Attribute Array 1, components/attribute, component type, normalize?, tightly packed
- }
- void Animate(float t) {
- sx = 0.25; //sinf(t);
- sy = 1; // cosf(t);
- wTx = 0; // 4 * cosf(t / 2);
- wTy = 0; // 4 * sinf(t / 2);
- }
- void Draw() {
- mat4 Mscale(sx, 0, 0, 0,
- 0, sy, 0, 0,
- 0, 0, 0, 0,
- 0, 0, 0, 1); // model matrix
- mat4 Mtranslate(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 0, 0,
- wTx, wTy, 0, 1); // model matrix
- mat4 Mrotate(cosf(phi), sinf(phi), 0, 0,
- -sinf(phi), cosf(phi), 0, 0,
- 0, 0, 1, 0,
- circleOrigo.x, circleOrigo.y, 0, 1); // model matrix
- mat4 MVPTransform = Mscale * Mtranslate * Mrotate * camera.V() * camera.P();
- // set GPU uniform matrix variable MVP with the content of CPU variable MVPTransform
- int location = glGetUniformLocation(shaderProgram, "MVP");
- if (location >= 0) glUniformMatrix4fv(location, 1, GL_TRUE, MVPTransform); // set uniform variable MVP to the MVPTransform
- else printf("uniform MVP cannot be set\n");
- glBindVertexArray(vao); // make the vao and its vbos active playing the role of the data source
- glDrawArrays(GL_TRIANGLES, 0, dotCount); // draw a single triangle with vertices defined in vao dotCount szamu haromszog,
- }
- };
- class Flower {
- unsigned int vao; // vertex array object id
- float sx, sy; // scaling
- float wTx, wTy; // translation
- vec4 origo;
- std::vector<Leaf> leafs;
- int petalCount;
- Circle circle;
- public:
- Flower(vec4 o, int pc) {
- origo = o;
- Circle c(1, o);
- circle = c;
- petalCount = pc;
- printf("circle origo: %f %f\n", origo.x, origo.y);
- for (int i = 0; i < petalCount; i++) {
- vec4 temp(1, 1);
- temp.y += sinf(i * 2 * M_PI / petalCount);
- temp.x += cosf(i * 2 * M_PI / petalCount);
- Leaf leaf(i * 2 * M_PI / petalCount, origo);
- leafs.push_back(leaf);
- //printf("petal origo: %f %f angle: %f\n", temp.x, temp.y, i * 2 * M_PI / petalCount);
- }
- Animate(0);
- }
- void Create() {
- for (int i = 0; i < petalCount; i++) {
- leafs[i].Create();
- }
- circle.Create();
- }
- void Animate(float t) {
- for (int i = 0; i < petalCount; i++) {
- leafs[i].Animate(t);
- }
- circle.Animate(t, 0);
- }
- void Draw() {
- for (int i = 0; i < petalCount; i++) {
- leafs[i].Draw();
- }
- circle.Draw(1);
- }
- };
- class LineStrip {
- GLuint vao, vbo; // vertex array object, vertex buffer object
- float vertexData[100]; // interleaved data of coordinates and colors
- int nVertices; // number of vertices
- public:
- LineStrip() {
- nVertices = 0;
- }
- void Create() {
- glGenVertexArrays(1, &vao);
- glBindVertexArray(vao);
- glGenBuffers(1, &vbo); // Generate 1 vertex buffer object
- glBindBuffer(GL_ARRAY_BUFFER, vbo);
- // Enable the vertex attribute arrays
- glEnableVertexAttribArray(0); // attribute array 0
- glEnableVertexAttribArray(1); // attribute array 1
- // Map attribute array 0 to the vertex data of the interleaved vbo
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(0)); // attribute array, components/attribute, component type, normalize?, stride, offset
- // Map attribute array 1 to the color data of the interleaved vbo
- glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(2 * sizeof(float)));
- }
- void AddPoint(float cX, float cY) {
- glBindBuffer(GL_ARRAY_BUFFER, vbo);
- if (nVertices >= 20) return;
- vec4 wVertex = vec4(cX, cY, 0, 1) * camera.Pinv() * camera.Vinv();
- // fill interleaved data
- vertexData[5 * nVertices] = wVertex.x;
- vertexData[5 * nVertices + 1] = wVertex.y;
- vertexData[5 * nVertices + 2] = 1; // red
- vertexData[5 * nVertices + 3] = 1; // green
- vertexData[5 * nVertices + 4] = 0; // blue
- nVertices++;
- // copy data to the GPU
- glBufferData(GL_ARRAY_BUFFER, nVertices * 5 * sizeof(float), vertexData, GL_DYNAMIC_DRAW);
- }
- void Draw() {
- if (nVertices > 0) {
- mat4 VPTransform = camera.V() * camera.P();
- int location = glGetUniformLocation(shaderProgram, "MVP");
- if (location >= 0) glUniformMatrix4fv(location, 1, GL_TRUE, VPTransform);
- else printf("uniform MVP cannot be set\n");
- glBindVertexArray(vao);
- glDrawArrays(GL_LINE_STRIP, 0, nVertices);
- }
- }
- };
- // The virtual world: collection of two objects
- Triangle triangle;
- LineStrip lineStrip;
- Circle circle(4, vec4(6, 0));
- Wing wing, wing1;
- //TexturedQuad quad;
- Flower flower1(vec4(8, 8), 30);
- Flower flower2(vec4(4, 6), 10);
- Flower flower3(vec4(3, 1), 12);
- Flower flower4(vec4(-3, -2), 3);
- Butterfly butt;
- // Initialization, create an OpenGL context
- void onInitialization() {
- glViewport(0, 0, windowWidth, windowHeight);
- // Create objects by setting up their vertex data on the GPU
- flower1.Create();
- flower2.Create();
- flower3.Create();
- flower4.Create();
- butt.Create();
- //quad.Create();
- // Create vertex shader from string
- unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
- if (!vertexShader) {
- printf("Error in vertex shader creation\n");
- exit(1);
- }
- glShaderSource(vertexShader, 1, &vertexSource, NULL);
- glCompileShader(vertexShader);
- checkShader(vertexShader, "Vertex shader error");
- // Create fragment shader from string
- unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
- if (!fragmentShader) {
- printf("Error in fragment shader creation\n");
- exit(1);
- }
- glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
- glCompileShader(fragmentShader);
- checkShader(fragmentShader, "Fragment shader error");
- // Attach shaders to a single program
- shaderProgram = glCreateProgram();
- if (!shaderProgram) {
- printf("Error in shader program creation\n");
- exit(1);
- }
- glAttachShader(shaderProgram, vertexShader);
- glAttachShader(shaderProgram, fragmentShader);
- // Connect the fragmentColor to the frame buffer memory
- glBindFragDataLocation(shaderProgram, 0, "fragmentColor"); // fragmentColor goes to the frame buffer memory
- // program packaging
- glLinkProgram(shaderProgram);
- checkLinking(shaderProgram);
- // make this program run
- glUseProgram(shaderProgram);
- }
- void onExit() {
- glDeleteProgram(shaderProgram);
- printf("exit");
- }
- // Window has become invalid: Redraw
- void onDisplay() {
- glClearColor(0.02, 1, 0.01, 1.0); // background color
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the screen
- flower1.Draw();
- //flower2.Draw();
- //flower3.Draw();
- //flower4.Draw();
- butt.Draw();
- //quad.Draw();
- glutSwapBuffers(); // exchange the two buffers
- }
- // Key of ASCII code pressed
- void onKeyboard(unsigned char key, int pX, int pY) {
- if (key == 'd') glutPostRedisplay(); // if d, invalidate display, i.e. redraw
- if (key == ' ') {
- isGPUProcedural = !isGPUProcedural;
- glutPostRedisplay(); // if d, invalidate display, i.e. redraw
- }
- }
- // Key of ASCII code released
- void onKeyboardUp(unsigned char key, int pX, int pY) {
- }
- bool mouseLeftPressed = false;
- bool mouseRightPressed = false;
- // Move mouse with key pressed
- void onMouseMotion(int pX, int pY) {
- float cX = 2.0f * pX / windowWidth - 1; // flip y axis
- float cY = 1.0f - 2.0f * pY / windowHeight;
- if (mouseLeftPressed) { // GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON and GLUT_DOWN / GLUT_UP
- }
- if (mouseRightPressed) { // GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON and GLUT_DOWN / GLUT_UP
- }
- glutPostRedisplay(); // redraw
- }
- // Mouse click event
- void onMouse(int button, int state, int pX, int pY) {
- float cX = 2.0f * pX / windowWidth - 1; // flip y axis
- float cY = 1.0f - 2.0f * pY / windowHeight;
- if (button == GLUT_LEFT_BUTTON) {
- if (state == GLUT_DOWN){
- cX = 2.0f * pX / windowWidth - 1; // flip y axis
- cY = 1.0f - 2.0f * pY / windowHeight;
- mouseLeftPressed = true;
- mouse_pos = vec4(cX, cY);
- }
- else{
- mouseLeftPressed = false;
- //butt.setAccel(vec4(0, 0));}
- }
- if (button == GLUT_RIGHT_BUTTON) {
- if (state == GLUT_DOWN) mouseRightPressed = true;
- else mouseRightPressed = false;
- }
- onMouseMotion(pX, pY);
- }
- // Idle event indicating that some time elapsed: do animation here
- float timeSinceUpdate;
- void onIdle() {
- long time = glutGet(GLUT_ELAPSED_TIME); // elapsed time since the start of the program
- float sec = time / 1000.0f; // convert msec to sec
- camera.Animate(sec); // animate the camera
- flower1.Animate(sec);
- flower2.Animate(sec);
- flower3.Animate(sec);
- flower4.Animate(sec);
- //butt.Animate(sec);
- //butt.setSpeed(( butt.getSpeed() + butt.getAccel() * (sec-timeSinceUpdate)) * (1 - butt.getWindResistance()));
- timeSinceUpdate = sec;
- glutPostRedisplay(); // redraw the scene
- }
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // Do not touch the code below this line
- int main(int argc, char * argv[]) {
- glutInit(&argc, argv);
- #if !defined(__APPLE__)
- glutInitContextVersion(majorVersion, minorVersion);
- #endif
- glutInitWindowSize(windowWidth, windowHeight); // Application window is initially of resolution 600x600
- glutInitWindowPosition(100, 100); // Relative location of the application window
- #if defined(__APPLE__)
- glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_3_3_CORE_PROFILE); // 8 bit R,G,B,A + double buffer + depth buffer
- #else
- glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
- #endif
- glutCreateWindow(argv[0]);
- #if !defined(__APPLE__)
- glewExperimental = true; // magic
- glewInit();
- #endif
- printf("GL Vendor : %s\n", glGetString(GL_VENDOR));
- printf("GL Renderer : %s\n", glGetString(GL_RENDERER));
- printf("GL Version (string) : %s\n", glGetString(GL_VERSION));
- glGetIntegerv(GL_MAJOR_VERSION, &majorVersion);
- glGetIntegerv(GL_MINOR_VERSION, &minorVersion);
- printf("GL Version (integer) : %d.%d\n", majorVersion, minorVersion);
- printf("GLSL Version : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
- onInitialization();
- glutDisplayFunc(onDisplay); // Register event handlers
- glutMouseFunc(onMouse);
- glutIdleFunc(onIdle);
- glutKeyboardFunc(onKeyboard);
- glutKeyboardUpFunc(onKeyboardUp);
- glutMotionFunc(onMouseMotion);
- glutMainLoop();
- onExit();
- return 1;}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement