Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 47

Importante: Para tener una mejor comprension y entendimiento de los siguientes programas primero hay

que leer un poco sobre que es VBO y VAO.

With the vertex data defined we’d like to send it as input to the first process of the graphics pipeline: the vertex
shader. This is done by creating memory on the GPU where we store the vertex data, configure how OpenGL
should interpret the memory and specify how to send the data to the graphics card. The vertex shader then
processes as much vertices as we tell it to from its memory. We manage this memory via so called vertex
buffer objects (VBO) that can store a large number of vertices in the GPU’s memory. The advantage of using
those buffer objects is that we can send large batches of data all at once to the graphics card, and keep it there
if there’s enough memory left, without having to send data one vertex at a time. Sending data to the graphics
card from the CPU is relatively slow, so wherever we can we try to send as much data as possible at once. Once
the data is in the graphics card’s memory the vertex shader has almost instant access to the vertices making it
extremely fast.

A vertex array object (also known as VAO) can be bound just like a vertex buffer object and any subsequent
vertex attribute calls from that point on will be stored inside the VAO. This has the advantage that when
configuring vertex attribute pointers you only have to make those calls once and whenever we want to draw
the object, we can just bind the corresponding VAO. This makes switching between different vertex data and
attribute configurations as easy as binding a different VAO. All the state we just set is stored inside the VAO.

/*CODIGO FUENTE A EVALUAR*/

#include <glad/glad.h>

#include <GLFW/glfw3.h>

#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);

void processInput(GLFWwindow* window);

// settings

const unsigned int SCR_WIDTH = 800;

const unsigned int SCR_HEIGHT = 600;


const char* vertexShaderSource = "#version 330 core\n"

"layout (location = 0) in vec3 aPos;\n"

"layout (location = 1) in vec3 aColor;\n"

"out vec3 ourColor;\n"

"void main()\n"

"{\n"

" gl_Position = vec4(aPos, 1.0);\n" //Podemos usar interpolacion de sombreado poniendo los
siguientes valores:aPos.x, -aPos.y, aPos.z, 1.0

" ourColor = aColor;\n"

"}\0";

const char* fragmentShaderSource = "#version 330 core\n"

"out vec4 FragColor;\n"

"in vec3 ourColor;\n"

"void main()\n"

"{\n"

" FragColor = vec4(ourColor, 1.0f);\n"

"}\n\0";

int main()

// glfw: initialize and configure

// ------------------------------

glfwInit();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);

glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__

glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

#endif

// glfw window creation

// --------------------

GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Interpolacion de Colores en


OpenGL", NULL, NULL);

if (window == NULL)

std::cout << "Fallo al Crear la Ventana" << std::endl;

glfwTerminate();

return -1;

glfwMakeContextCurrent(window);

glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

// glad: load all OpenGL function pointers

// ---------------------------------------

if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))

std::cout << "Fallo al Inicializar la libreria GLAD" << std::endl;

return -1;

// Ejecuta y Compila el programa para el proceso de las sombras

// ------------------------------------

// vertex shader

unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);


glCompileShader(vertexShader);

// check for shader compile errors

int success;

char infoLog[512];

glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

if (!success)

glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);

std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;

// fragment shader

unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);

glCompileShader(fragmentShader);

// check for shader compile errors

glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);

if (!success)

glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);

std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;

// link shaders

unsigned int shaderProgram = glCreateProgram();

glAttachShader(shaderProgram, vertexShader);

glAttachShader(shaderProgram, fragmentShader);

glLinkProgram(shaderProgram);

// check for linking errors

glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);

if (!success) {

glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);


std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;

glDeleteShader(vertexShader);

glDeleteShader(fragmentShader);

// set up vertex data (and buffer(s)) and configure vertex attributes

// ------------------------------------------------------------------

float vertices[] = {

// posiciones // colores

0.5f, -0.5f, 0.0f, 1.1f, 0.6f, 0.3f, // esquina inferior derecha

-0.5f, -0.5f, 0.0f, 0.5f, 1.0f, 0.0f, // esquina inferior izquierda

0.0f, 0.5f, 0.0f, 0.9f, 0.8f, 1.0f // cúspide

};

unsigned int VBO, VAO;

glGenVertexArrays(1, &VAO);

glGenBuffers(1, &VBO);

// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then
configure vertex attributes(s).

glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

// position attribute

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);

glEnableVertexAttribArray(0);

// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 *
sizeof(float)));

glEnableVertexAttribArray(1);

// as we only have a single shader, we could also just activate our shader once beforehand
if we want to

glUseProgram(shaderProgram);

// render loop

// -----------

while (!glfwWindowShouldClose(window))

// input

// -----

processInput(window);

// render

// ------

glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

glClear(GL_COLOR_BUFFER_BIT);

// render the triangle

glBindVertexArray(VAO);

glDrawArrays(GL_TRIANGLES, 0, 3);

// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)

// -------------------------------------------------------------------------------

glfwSwapBuffers(window);

glfwPollEvents();

}
// optional: de-allocate all resources once they've outlived their purpose:

// ------------------------------------------------------------------------

glDeleteVertexArrays(1, &VAO);

glDeleteBuffers(1, &VBO);

glDeleteProgram(shaderProgram);

// glfw: terminate, clearing all previously allocated GLFW resources.

// ------------------------------------------------------------------

glfwTerminate();

return 0;

// process all input: query GLFW whether relevant keys are pressed/released this frame and
react accordingly

//
-----------------------------------------------------------------------------------------------
----------

void processInput(GLFWwindow* window)

if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)

glfwSetWindowShouldClose(window, true);

// glfw: whenever the window size changed (by OS or user resize) this callback function
executes

//
---------------------------------------------------------------------------------------------

void framebuffer_size_callback(GLFWwindow* window, int width, int height)

// make sure the viewport matches the new window dimensions; note that width and

// height will be significantly larger than specified on retina displays.


glViewport(0, 0, width, height);

/*TRIANGULOS ANIDADOS*/

#include <glad/glad.h>

#include <GLFW/glfw3.h>

#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);

void processInput(GLFWwindow* window);

// settings

const unsigned int SCR_WIDTH = 800;

const unsigned int SCR_HEIGHT = 600;

const char* vertexShaderSource = "#version 330 core\n"

"layout (location = 0) in vec3 aPos;\n"

"void main()\n"

"{\n"

" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"

"}\0";

const char* fragmentShaderSource = "#version 330 core\n"

"out vec4 FragColor;\n"

"void main()\n"

"{\n"

" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"

"}\n\0";
int main()

// glfw: initialize and configure

// ------------------------------

glfwInit();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);

glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__

glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

#endif

// glfw window creation

// --------------------

GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);

if (window == NULL)

std::cout << "Failed to create GLFW window" << std::endl;

glfwTerminate();

return -1;

glfwMakeContextCurrent(window);

glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

// glad: load all OpenGL function pointers

// ---------------------------------------

if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))

{
std::cout << "Failed to initialize GLAD" << std::endl;

return -1;

// build and compile our shader program

// ------------------------------------

// vertex shader

unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);

glCompileShader(vertexShader);

// check for shader compile errors

int success;

char infoLog[512];

glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);

if (!success)

glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);

std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;

// fragment shader

unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);

glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);

glCompileShader(fragmentShader);

// check for shader compile errors

glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);

if (!success)

glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);

std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;


}

// link shaders

unsigned int shaderProgram = glCreateProgram();

glAttachShader(shaderProgram, vertexShader);

glAttachShader(shaderProgram, fragmentShader);

glLinkProgram(shaderProgram);

// check for linking errors

glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);

if (!success) {

glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);

std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;

glDeleteShader(vertexShader);

glDeleteShader(fragmentShader);

// set up vertex data (and buffer(s)) and configure vertex attributes

// ------------------------------------------------------------------

// add a new set of vertices to form a second triangle (a total of 6 vertices); the vertex
attribute configuration remains the same (still one 3-float position vector per vertex)

float vertices[] = {

// first triangle

-0.9f, -0.5f, 0.0f, // left

-0.0f, -0.5f, 0.0f, // right

-0.45f, 0.5f, 0.0f, // top

// second triangle

0.0f, -0.5f, 0.0f, // left

0.9f, -0.5f, 0.0f, // right

0.45f, 0.5f, 0.0f // top

};
unsigned int VBO, VAO;

glGenVertexArrays(1, &VAO);

glGenBuffers(1, &VBO);

// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then
configure vertex attributes(s).

glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);

glEnableVertexAttribArray(0);

// note that this is allowed, the call to glVertexAttribPointer registered VBO as the
vertex attribute's bound vertex buffer object so afterwards we can safely unbind

glBindBuffer(GL_ARRAY_BUFFER, 0);

// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO,
but this rarely happens. Modifying other

// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor
VBOs) when it's not directly necessary.

glBindVertexArray(0);

// uncomment this call to draw in wireframe polygons.

//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

// render loop

// -----------

while (!glfwWindowShouldClose(window))

{
// input

// -----

processInput(window);

// render

// ------

glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

glClear(GL_COLOR_BUFFER_BIT);

// draw our first triangle

glUseProgram(shaderProgram);

glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind


it every time, but we'll do so to keep things a bit more organized

glDrawArrays(GL_TRIANGLES, 0, 6); // set the count to 6 since we're drawing 6 vertices


now (2 triangles); not 3!

// glBindVertexArray(0); // no need to unbind it every time

// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)

// -------------------------------------------------------------------------------

glfwSwapBuffers(window);

glfwPollEvents();

// optional: de-allocate all resources once they've outlived their purpose:

// ------------------------------------------------------------------------

glDeleteVertexArrays(1, &VAO);

glDeleteBuffers(1, &VBO);

glDeleteProgram(shaderProgram);

// glfw: terminate, clearing all previously allocated GLFW resources.


// ------------------------------------------------------------------

glfwTerminate();

return 0;

// process all input: query GLFW whether relevant keys are pressed/released this frame and
react accordingly

//
-----------------------------------------------------------------------------------------------
----------

void processInput(GLFWwindow* window)

if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)

glfwSetWindowShouldClose(window, true);

// glfw: whenever the window size changed (by OS or user resize) this callback function
executes

//
---------------------------------------------------------------------------------------------

void framebuffer_size_callback(GLFWwindow* window, int width, int height)

// make sure the viewport matches the new window dimensions; note that width and

// height will be significantly larger than specified on retina displays.

glViewport(0, 0, width, height);

/*DOS TRIANGULOS ANIDADOS CON SUS COLORES INDEPENDIENTES*/

#include <glad/glad.h>

#include <GLFW/glfw3.h>

#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);

void processInput(GLFWwindow* window);

// settings

const unsigned int SCR_WIDTH = 800;

const unsigned int SCR_HEIGHT = 600;

const char* vertexShaderSource = "#version 330 core\n"

"layout (location = 0) in vec3 aPos;\n"

"void main()\n"

"{\n"

" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"

"}\0";

const char* fragmentShader1Source = "#version 330 core\n"

"out vec4 FragColor;\n"

"void main()\n"

"{\n"

" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"

"}\n\0";

const char* fragmentShader2Source = "#version 330 core\n"

"out vec4 FragColor;\n"

"void main()\n"

"{\n"

" FragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f);\n"

"}\n\0";

int main()
{

// glfw: initialize and configure

// ------------------------------

glfwInit();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);

glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__

glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

#endif

// glfw window creation

// --------------------

GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);

if (window == NULL)

std::cout << "Failed to create GLFW window" << std::endl;

glfwTerminate();

return -1;

glfwMakeContextCurrent(window);

glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

// glad: load all OpenGL function pointers

// ---------------------------------------

if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))

std::cout << "Failed to initialize GLAD" << std::endl;


return -1;

// build and compile our shader program

// ------------------------------------

// we skipped compile log checks this time for readability (if you do encounter issues, add
the compile-checks! see previous code samples)

unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);

unsigned int fragmentShaderOrange = glCreateShader(GL_FRAGMENT_SHADER); // the first


fragment shader that outputs the color orange

unsigned int fragmentShaderYellow = glCreateShader(GL_FRAGMENT_SHADER); // the second


fragment shader that outputs the color yellow

unsigned int shaderProgramOrange = glCreateProgram();

unsigned int shaderProgramYellow = glCreateProgram(); // the second shader program

glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);

glCompileShader(vertexShader);

glShaderSource(fragmentShaderOrange, 1, &fragmentShader1Source, NULL);

glCompileShader(fragmentShaderOrange);

glShaderSource(fragmentShaderYellow, 1, &fragmentShader2Source, NULL);

glCompileShader(fragmentShaderYellow);

// link the first program object

glAttachShader(shaderProgramOrange, vertexShader);

glAttachShader(shaderProgramOrange, fragmentShaderOrange);

glLinkProgram(shaderProgramOrange);

// then link the second program object using a different fragment shader (but same vertex
shader)

// this is perfectly allowed since the inputs and outputs of both the vertex and fragment
shaders are equally matched.

glAttachShader(shaderProgramYellow, vertexShader);

glAttachShader(shaderProgramYellow, fragmentShaderYellow);

glLinkProgram(shaderProgramYellow);
// set up vertex data (and buffer(s)) and configure vertex attributes

// ------------------------------------------------------------------

float firstTriangle[] = {

-0.9f, -0.5f, 0.0f, // left

-0.0f, -0.5f, 0.0f, // right

-0.45f, 0.5f, 0.0f, // top

};

float secondTriangle[] = {

0.0f, -0.5f, 0.0f, // left

0.9f, -0.5f, 0.0f, // right

0.45f, 0.5f, 0.0f // top

};

unsigned int VBOs[2], VAOs[2];

glGenVertexArrays(2, VAOs); // we can also generate multiple VAOs or buffers at the same
time

glGenBuffers(2, VBOs);

// first triangle setup

// --------------------

glBindVertexArray(VAOs[0]);

glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);

glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); //


Vertex attributes stay the same

glEnableVertexAttribArray(0);

// glBindVertexArray(0); // no need to unbind at all as we directly bind a different VAO


the next few lines

// second triangle setup

// ---------------------

glBindVertexArray(VAOs[1]); // note that we bind to a different VAO now

glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]); // and a different VBO


glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); // because the vertex data is


tightly packed we can also specify 0 as the vertex attribute's stride to let OpenGL figure it
out

glEnableVertexAttribArray(0);

// uncomment this call to draw in wireframe polygons.

//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

// render loop

// -----------

while (!glfwWindowShouldClose(window))

// input

// -----

processInput(window);

// render

// ------

glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

glClear(GL_COLOR_BUFFER_BIT);

// now when we draw the triangle we first use the vertex and orange fragment shader
from the first program

glUseProgram(shaderProgramOrange);

// draw the first triangle using the data from our first VAO

glBindVertexArray(VAOs[0]);

glDrawArrays(GL_TRIANGLES, 0, 3); // this call should output an orange triangle

// then we draw the second triangle using the data from the second VAO

// when we draw the second triangle we want to use a different shader program so we
switch to the shader program with our yellow fragment shader.
glUseProgram(shaderProgramYellow);

glBindVertexArray(VAOs[1]);

glDrawArrays(GL_TRIANGLES, 0, 3); // this call should output a yellow triangle

// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)

// -------------------------------------------------------------------------------

glfwSwapBuffers(window);

glfwPollEvents();

// optional: de-allocate all resources once they've outlived their purpose:

// ------------------------------------------------------------------------

glDeleteVertexArrays(2, VAOs);

glDeleteBuffers(2, VBOs);

glDeleteProgram(shaderProgramOrange);

glDeleteProgram(shaderProgramYellow);

// glfw: terminate, clearing all previously allocated GLFW resources.

// ------------------------------------------------------------------

glfwTerminate();

return 0;

// process all input: query GLFW whether relevant keys are pressed/released this frame and
react accordingly

//
-----------------------------------------------------------------------------------------------
----------

void processInput(GLFWwindow* window)

if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)


glfwSetWindowShouldClose(window, true);

// glfw: whenever the window size changed (by OS or user resize) this callback function
executes

//
---------------------------------------------------------------------------------------------

void framebuffer_size_callback(GLFWwindow* window, int width, int height)

// make sure the viewport matches the new window dimensions; note that width and

// height will be significantly larger than specified on retina displays.

glViewport(0, 0, width, height);

/*VARIOS POLIGONOS CON DIFERENTES COLORES*/

/*

* GL02Primitive.cpp: Vertex, Primitive and Color

* Draw Simple 2D colored Shapes: quad, triangle and polygon.

*/

#include <windows.h> // for MS Windows

#include <GL/glut.h> // GLUT, include glu.h and gl.h

/* Initialize OpenGL Graphics */

void initGL() {

// Set "clearing" or background color

glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black and opaque

/* Handler for window-repaint event. Call back when the window first appears and

whenever the window needs to be re-painted. */


void display() {

glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer with current clearing color

// Define shapes enclosed within a pair of glBegin and glEnd

glBegin(GL_QUADS); // Each set of 4 vertices form a quad

glColor3f(1.0f, 0.0f, 0.0f); // Red

glVertex2f(-0.8f, 0.1f); // Define vertices in counter-clockwise (CCW) order

glVertex2f(-0.2f, 0.1f); // so that the normal (front-face) is facing you

glVertex2f(-0.2f, 0.7f);

glVertex2f(-0.8f, 0.7f);

glColor3f(0.0f, 1.0f, 0.0f); // Green

glVertex2f(-0.7f, -0.6f);

glVertex2f(-0.1f, -0.6f);

glVertex2f(-0.1f, 0.0f);

glVertex2f(-0.7f, 0.0f);

glColor3f(0.2f, 0.2f, 0.2f); // Dark Gray

glVertex2f(-0.9f, -0.7f);

glColor3f(1.0f, 1.0f, 1.0f); // White

glVertex2f(-0.5f, -0.7f);

glColor3f(0.2f, 0.2f, 0.2f); // Dark Gray

glVertex2f(-0.5f, -0.3f);

glColor3f(1.0f, 1.0f, 1.0f); // White

glVertex2f(-0.9f, -0.3f);

glEnd();

glBegin(GL_TRIANGLES); // Each set of 3 vertices form a triangle

glColor3f(0.0f, 0.0f, 1.0f); // Blue


glVertex2f(0.1f, -0.6f);

glVertex2f(0.7f, -0.6f);

glVertex2f(0.4f, -0.1f);

glColor3f(1.0f, 0.0f, 0.0f); // Red

glVertex2f(0.3f, -0.4f);

glColor3f(0.0f, 1.0f, 0.0f); // Green

glVertex2f(0.9f, -0.4f);

glColor3f(0.0f, 0.0f, 1.0f); // Blue

glVertex2f(0.6f, -0.9f);

glEnd();

glBegin(GL_POLYGON); // These vertices form a closed polygon

glColor3f(1.0f, 1.0f, 0.0f); // Yellow

glVertex2f(0.4f, 0.2f);

glVertex2f(0.6f, 0.2f);

glVertex2f(0.7f, 0.4f);

glVertex2f(0.6f, 0.6f);

glVertex2f(0.4f, 0.6f);

glVertex2f(0.3f, 0.4f);

glEnd();

glFlush(); // Render now

/* Main function: GLUT runs as a console application starting at main() */

int main(int argc, char** argv) {

glutInit(&argc, argv); // Initialize GLUT

glutCreateWindow("Vertex, Primitive & Color"); // Create window with the given title
glutInitWindowSize(1000, 800); // Set the window's initial width & height

glutInitWindowPosition(300, 300); // Position the window's initial top-left corner

glutDisplayFunc(display); // Register callback handler for window re-paint event

initGL(); // Our own OpenGL initialization

glutMainLoop(); // Enter the event-processing loop

return 0;

/*ROTACION DE VARIOS POLIGONOS CON SUS COLORES*/

#include <windows.h> // for MS Windows

#include <GL/glut.h> // GLUT, include glu.h and gl.h

// Global variable

GLfloat angle = 0.0f; // Current rotational angle of the shapes

GLfloat angle1 = 0.0f;

GLfloat angle2 = 0.0f;

/* Initialize OpenGL Graphics */

void initGL() {

// Set "clearing" or background color

glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black and opaque

/* Called back when there is no other event to be handled */

void idle() {

glutPostRedisplay(); // Post a re-paint request to activate display()

}
/* Handler for window-repaint event. Call back when the window first appears and

whenever the window needs to be re-painted. */

void display() {

glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer

glMatrixMode(GL_MODELVIEW); // To operate on Model-View matrix

glLoadIdentity(); // Reset the model-view matrix

glPushMatrix(); // Save model-view matrix setting

glTranslatef(-0.5f, 0.4f, 0.0f); // Translate

glRotatef(angle, 0.0f, 0.0f, 1.0f); // rotate by angle in degrees

glBegin(GL_QUADS); // Each set of 4 vertices form a quad

glColor3f(1.0f, 0.0f, 0.0f); // Red

glVertex2f(-0.3f, -0.3f);

glVertex2f(0.3f, -0.3f);

glVertex2f(0.3f, 0.3f);

glVertex2f(-0.3f, 0.3f);

glEnd();

glPopMatrix(); // Restore the model-view matrix

glPushMatrix(); // Save model-view matrix setting

glTranslatef(-0.4f, -0.3f, 0.0f); // Translate

glRotatef(angle, 0.0f, 0.0f, 1.0f); // rotate by angle in degrees

glBegin(GL_QUADS);

glColor3f(0.0f, 1.0f, 0.0f); // Green

glVertex2f(-0.3f, -0.3f);

glVertex2f(0.3f, -0.3f);

glVertex2f(0.3f, 0.3f);

glVertex2f(-0.3f, 0.3f);

glEnd();

glPopMatrix(); // Restore the model-view matrix


glPushMatrix(); // Save model-view matrix setting

glTranslatef(-0.7f, -0.5f, 0.0f); // Translate

glRotatef(angle, 0.0f, 0.0f, 1.0f); // rotate by angle in degrees

glBegin(GL_QUADS);

glColor3f(0.2f, 0.2f, 0.2f); // Dark Gray

glVertex2f(-0.2f, -0.2f);

glColor3f(1.0f, 1.0f, 1.0f); // White

glVertex2f(0.2f, -0.2f);

glColor3f(0.2f, 0.2f, 0.2f); // Dark Gray

glVertex2f(0.2f, 0.2f);

glColor3f(1.0f, 1.0f, 1.0f); // White

glVertex2f(-0.2f, 0.2f);

glEnd();

glPopMatrix(); // Restore the model-view matrix

glPushMatrix(); // Save model-view matrix setting

glTranslatef(0.4f, -0.3f, 0.0f); // Translate

glRotatef(angle, 0.0f, 0.0f, 1.0f); // rotate by angle in degrees

glBegin(GL_TRIANGLES);

glColor3f(0.0f, 0.0f, 1.0f); // Blue

glVertex2f(-0.3f, -0.2f);

glVertex2f(0.3f, -0.2f);

glVertex2f(0.0f, 0.3f);

glEnd();

glPopMatrix(); // Restore the model-view matrix

glPushMatrix(); // Save model-view matrix setting

glTranslatef(0.6f, -0.6f, 0.0f); // Translate


glRotatef(270.0f + angle2, 0.0f, 0.0f, 1.0f); // Rotate 180+angle degree

glBegin(GL_TRIANGLES);

glColor3f(1.0f, 0.0f, 0.0f); // Red

glVertex2f(-0.3f, -0.2f);

glColor3f(0.0f, 1.0f, 0.0f); // Green

glVertex2f(0.3f, -0.2f);

glColor3f(0.0f, 0.0f, 1.0f); // Blue

glVertex2f(0.0f, 0.3f);

glEnd();

glPopMatrix(); // Restore the model-view matrix

glPushMatrix(); // Save model-view matrix setting

glTranslatef(0.5f, 0.4f, 0.0f); // Translate

glRotatef(angle1, 0.0f, 0.0f, 1.0f); // rotate by angle in degrees

glBegin(GL_POLYGON);

glColor3f(1.0f, 1.0f, 0.0f); // Yellow

glVertex2f(-0.1f, -0.2f);

glVertex2f(0.1f, -0.2f);

glVertex2f(0.2f, 0.0f);

glVertex2f(0.1f, 0.2f);

glVertex2f(-0.1f, 0.2f);

glVertex2f(-0.2f, 0.0f);

glEnd();

glPopMatrix(); // Restore the model-view matrix

glutSwapBuffers(); // Double buffered - swap the front and back buffers

// Change the rotational angle after each display()

angle += 0.9f;
angle1 -= 0.5f;

angle2 += 1.5f;

/* Handler for window re-size event. Called back when the window first appears and

whenever the window is re-sized with its new width and height */

void reshape(GLsizei width, GLsizei height) { // GLsizei for non-negative integer

// Compute aspect ratio of the new window

if (height == 0) height = 1; // To prevent divide by 0

GLfloat aspect = (GLfloat)width / (GLfloat)height;

// Set the viewport to cover the new window

glViewport(0, 0, width, height);

// Set the aspect ratio of the clipping area to match the viewport

glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix

glLoadIdentity();

if (width >= height) {

// aspect >= 1, set the height from -1 to 1, with larger width

gluOrtho2D(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0);

else {

// aspect < 1, set the width to -1 to 1, with larger height

gluOrtho2D(-1.0, 1.0, -1.0 / aspect, 1.0 / aspect);

/* Main function: GLUT runs as a console application starting at main() */

int main(int argc, char** argv) {


glutInit(&argc, argv); // Initialize GLUT

glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode

glutInitWindowSize(640, 480); // Set the window's initial width & height - non-square

glutInitWindowPosition(50, 50); // Position the window's initial top-left corner

glutCreateWindow("Animation via Idle Function"); // Create window with the given title

glutDisplayFunc(display); // Register callback handler for window re-paint event

glutReshapeFunc(reshape); // Register callback handler for window re-size event

glutIdleFunc(idle); // Register callback handler if no other event

initGL(); // Our own OpenGL initialization

glutMainLoop(); // Enter the infinite event-processing loop

return 0;

/*EFECTO DE REBOTE DE UN POLIGONO*/

#include <windows.h> // for MS Windows

#include <GL/glut.h> // GLUT, includes glu.h and gl.h

#include <Math.h> // Needed for sin, cos

#define PI 3.14159265f

// Global variables

char title[] = "Full-Screen & Windowed Mode"; // Windowed mode's title

int windowWidth = 640; // Windowed mode's width

int windowHeight = 480; // Windowed mode's height

int windowPosX = 50; // Windowed mode's top-left corner x

int windowPosY = 50; // Windowed mode's top-left corner y

GLfloat ballRadius = 0.5f; // Radius of the bouncing ball

GLfloat ballX = 0.0f; // Ball's center (x, y) position


GLfloat ballY = 0.0f;

GLfloat ballXMax, ballXMin, ballYMax, ballYMin; // Ball's center (x, y) bounds

GLfloat xSpeed = 0.02f; // Ball's speed in x and y directions

GLfloat ySpeed = 0.007f;

int refreshMillis = 30; // Refresh period in milliseconds

// Projection clipping area

GLdouble clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop;

bool fullScreenMode = true; // Full-screen or windowed mode?

/* Initialize OpenGL Graphics */

void initGL() {

glClearColor(0.0, 0.0, 0.0, 1.0); // Set background (clear) color to black

/* Callback handler for window re-paint event */

void display() {

glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer

glMatrixMode(GL_MODELVIEW); // To operate on the model-view matrix

glLoadIdentity(); // Reset model-view matrix

glTranslatef(ballX, ballY, 0.0f); // Translate to (xPos, yPos)

// Use triangular segments to form a circle

glBegin(GL_TRIANGLE_FAN);

glColor3f(0.0f, 0.0f, 1.0f); // Blue

glVertex2f(0.0f, 0.0f); // Center of circle

int numSegments = 100;

GLfloat angle;
for (int i = 0; i <= numSegments; i++) { // Last vertex same as first vertex

angle = i * 2.0f * PI / numSegments; // 360 deg for all segments

glVertex2f(cos(angle) * ballRadius, sin(angle) * ballRadius);

glEnd();

glutSwapBuffers(); // Swap front and back buffers (of double buffered mode)

// Animation Control - compute the location for the next refresh

ballX += xSpeed;

ballY += ySpeed;

// Check if the ball exceeds the edges

if (ballX > ballXMax) {

ballX = ballXMax;

xSpeed = -xSpeed;

else if (ballX < ballXMin) {

ballX = ballXMin;

xSpeed = -xSpeed;

if (ballY > ballYMax) {

ballY = ballYMax;

ySpeed = -ySpeed;

else if (ballY < ballYMin) {

ballY = ballYMin;

ySpeed = -ySpeed;

}
/* Call back when the windows is re-sized */

void reshape(GLsizei width, GLsizei height) {

// Compute aspect ratio of the new window

if (height == 0) height = 1; // To prevent divide by 0

GLfloat aspect = (GLfloat)width / (GLfloat)height;

// Set the viewport to cover the new window

glViewport(0, 0, width, height);

// Set the aspect ratio of the clipping area to match the viewport

glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix

glLoadIdentity(); // Reset the projection matrix

if (width >= height) {

clipAreaXLeft = -1.0 * aspect;

clipAreaXRight = 1.0 * aspect;

clipAreaYBottom = -1.0;

clipAreaYTop = 1.0;

else {

clipAreaXLeft = -1.0;

clipAreaXRight = 1.0;

clipAreaYBottom = -1.0 / aspect;

clipAreaYTop = 1.0 / aspect;

gluOrtho2D(clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop);

ballXMin = clipAreaXLeft + ballRadius;

ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;


ballYMax = clipAreaYTop - ballRadius;

/* Called back when the timer expired */

void Timer(int value) {

glutPostRedisplay(); // Post a paint request to activate display()

glutTimerFunc(refreshMillis, Timer, 0); // subsequent timer call at milliseconds

/* Callback handler for special-key event */

void specialKeys(int key, int x, int y) {

switch (key) {

case GLUT_KEY_F1: // F1: Toggle between full-screen and windowed mode

fullScreenMode = !fullScreenMode; // Toggle state

if (fullScreenMode) { // Full-screen mode

windowPosX = glutGet(GLUT_WINDOW_X); // Save parameters for restoring later

windowPosY = glutGet(GLUT_WINDOW_Y);

windowWidth = glutGet(GLUT_WINDOW_WIDTH);

windowHeight = glutGet(GLUT_WINDOW_HEIGHT);

glutFullScreen(); // Switch into full screen

else { // Windowed mode

glutReshapeWindow(windowWidth, windowHeight); // Switch into windowed mode

glutPositionWindow(windowPosX, windowPosX); // Position top-left corner

break;

}
/* Main function: GLUT runs as a console application starting at main() */

int main(int argc, char** argv) {

glutInit(&argc, argv); // Initialize GLUT

glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode

glutInitWindowSize(windowWidth, windowHeight); // Initial window width and height

glutInitWindowPosition(windowPosX, windowPosY); // Initial window top-left corner (x, y)

glutCreateWindow(title); // Create window with given title

glutDisplayFunc(display); // Register callback handler for window re-paint

glutReshapeFunc(reshape); // Register callback handler for window re-shape

glutTimerFunc(0, Timer, 0); // First timer call immediately

glutSpecialFunc(specialKeys); // Register callback handler for special-key event

glutFullScreen(); // Put into full screen

initGL(); // Our own OpenGL initialization

glutMainLoop(); // Enter event-processing loop

return 0;

/*AUMENTO DE VELOCIDAD CONTROLADO POR LAS TECLAS DIRECCIONALES PARA UNA PELOTA*/

#include <windows.h> // for MS Windows

#include <GL/glut.h> // GLUT, include glu.h and gl.h

#include <Math.h> // Needed for sin, cos

#define PI 3.14159265f

// Global variables

char title[] = "Full-Screen & Windowed Mode"; // Windowed mode's title

int windowWidth = 640; // Windowed mode's width

int windowHeight = 480; // Windowed mode's height

int windowPosX = 50; // Windowed mode's top-left corner x

int windowPosY = 50; // Windowed mode's top-left corner y


GLfloat ballRadius = 0.5f; // Radius of the bouncing ball

GLfloat ballX = 0.0f; // Ball's center (x, y) position

GLfloat ballY = 0.0f;

GLfloat ballXMax, ballXMin, ballYMax, ballYMin; // Ball's center (x, y) bounds

GLfloat xSpeed = 0.02f; // Ball's speed in x and y directions

GLfloat ySpeed = 0.007f;

int refreshMillis = 30; // Refresh period in milliseconds

// Projection clipping area

GLdouble clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop;

bool fullScreenMode = true; // Full-screen or windowed mode?

/* Initialize OpenGL Graphics */

void initGL() {

glClearColor(0.0, 0.0, 0.0, 1.0); // Set background (clear) color to black

/* Callback handler for window re-paint event */

void display() {

glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer

glMatrixMode(GL_MODELVIEW); // To operate on the model-view matrix

glLoadIdentity(); // Reset model-view matrix

glTranslatef(ballX, ballY, 0.0f); // Translate to (xPos, yPos)

// Use triangular segments to form a circle

glBegin(GL_TRIANGLE_FAN);

glColor3f(0.0f, 0.0f, 1.0f); // Blue


glVertex2f(0.0f, 0.0f); // Center of circle

int numSegments = 100;

GLfloat angle;

for (int i = 0; i <= numSegments; i++) { // Last vertex same as first vertex

angle = i * 2.0f * PI / numSegments; // 360 deg for all segments

glVertex2f(cos(angle) * ballRadius, sin(angle) * ballRadius);

glEnd();

glutSwapBuffers(); // Swap front and back buffers (of double buffered mode)

// Animation Control - compute the location for the next refresh

ballX += xSpeed;

ballY += ySpeed;

// Check if the ball exceeds the edges

if (ballX > ballXMax) {

ballX = ballXMax;

xSpeed = -xSpeed;

else if (ballX < ballXMin) {

ballX = ballXMin;

xSpeed = -xSpeed;

if (ballY > ballYMax) {

ballY = ballYMax;

ySpeed = -ySpeed;

else if (ballY < ballYMin) {

ballY = ballYMin;

ySpeed = -ySpeed;
}

/* Call back when the windows is re-sized */

void reshape(GLsizei width, GLsizei height) {

// Compute aspect ratio of the new window

if (height == 0) height = 1; // To prevent divide by 0

GLfloat aspect = (GLfloat)width / (GLfloat)height;

// Set the viewport to cover the new window

glViewport(0, 0, width, height);

// Set the aspect ratio of the clipping area to match the viewport

glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix

glLoadIdentity(); // Reset the projection matrix

if (width >= height) {

clipAreaXLeft = -1.0 * aspect;

clipAreaXRight = 1.0 * aspect;

clipAreaYBottom = -1.0;

clipAreaYTop = 1.0;

else {

clipAreaXLeft = -1.0;

clipAreaXRight = 1.0;

clipAreaYBottom = -1.0 / aspect;

clipAreaYTop = 1.0 / aspect;

gluOrtho2D(clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop);

ballXMin = clipAreaXLeft + ballRadius;


ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;

ballYMax = clipAreaYTop - ballRadius;

/* Called back when the timer expired */

void Timer(int value) {

glutPostRedisplay(); // Post a paint request to activate display()

glutTimerFunc(refreshMillis, Timer, 0); // subsequent timer call at milliseconds

/* Callback handler for normal-key event */

void keyboard(unsigned char key, int x, int y) {

switch (key) {

case 27: // ESC key

exit(0);

break;

/* Callback handler for special-key event */

void specialKeys(int key, int x, int y) {

switch (key) {

case GLUT_KEY_F1: // F1: Toggle between full-screen and windowed mode

fullScreenMode = !fullScreenMode; // Toggle state

if (fullScreenMode) { // Full-screen mode

windowPosX = glutGet(GLUT_WINDOW_X); // Save parameters for restoring later

windowPosY = glutGet(GLUT_WINDOW_Y);

windowWidth = glutGet(GLUT_WINDOW_WIDTH);
windowHeight = glutGet(GLUT_WINDOW_HEIGHT);

glutFullScreen(); // Switch into full screen

else { // Windowed mode

glutReshapeWindow(windowWidth, windowHeight); // Switch into windowed mode

glutPositionWindow(windowPosX, windowPosX); // Position top-left corner

break;

case GLUT_KEY_RIGHT: // Right: increase x speed

xSpeed *= 1.05f; break;

case GLUT_KEY_LEFT: // Left: decrease x speed

xSpeed *= 0.95f; break;

case GLUT_KEY_UP: // Up: increase y speed

ySpeed *= 1.05f; break;

case GLUT_KEY_DOWN: // Down: decrease y speed

ySpeed *= 0.95f; break;

case GLUT_KEY_PAGE_UP: // Page-Up: increase ball's radius

ballRadius *= 1.05f;

ballXMin = clipAreaXLeft + ballRadius;

ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;

ballYMax = clipAreaYTop - ballRadius;

break;

case GLUT_KEY_PAGE_DOWN: // Page-Down: decrease ball's radius

ballRadius *= 0.95f;

ballXMin = clipAreaXLeft + ballRadius;

ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;

ballYMax = clipAreaYTop - ballRadius;

break;
}

/* Main function: GLUT runs as a console application starting at main() */

int main(int argc, char** argv) {

glutInit(&argc, argv); // Initialize GLUT

glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode

glutInitWindowSize(windowWidth, windowHeight); // Initial window width and height

glutInitWindowPosition(windowPosX, windowPosY); // Initial window top-left corner (x, y)

glutCreateWindow(title); // Create window with given title

glutDisplayFunc(display); // Register callback handler for window re-paint

glutReshapeFunc(reshape); // Register callback handler for window re-shape

glutTimerFunc(0, Timer, 0); // First timer call immediately

glutSpecialFunc(specialKeys); // Register callback handler for special-key event

glutKeyboardFunc(keyboard); // Register callback handler for special-key event

glutFullScreen(); // Put into full screen

initGL(); // Our own OpenGL initialization

glutMainLoop(); // Enter event-processing loop

return 0;

/*CONTROL DE VELOCIDAD CON TECLAS DIRECCIONALES Y USO DEL MOUSE CON LA FUNCION CLICK DEL BOTON
DE DERECHO*/

#include <windows.h> // for MS Windows

#include <GL/glut.h> // GLUT, include glu.h and gl.h

#include <Math.h> // Needed for sin, cos

#define PI 3.14159265f

// Global variables
char title[] = "Full-Screen & Windowed Mode"; // Windowed mode's title

int windowWidth = 640; // Windowed mode's width

int windowHeight = 480; // Windowed mode's height

int windowPosX = 50; // Windowed mode's top-left corner x

int windowPosY = 50; // Windowed mode's top-left corner y

GLfloat ballRadius = 0.5f; // Radius of the bouncing ball

GLfloat ballX = 0.0f; // Ball's center (x, y) position

GLfloat ballY = 0.0f;

GLfloat ballXMax, ballXMin, ballYMax, ballYMin; // Ball's center (x, y) bounds

GLfloat xSpeed = 0.02f; // Ball's speed in x and y directions

GLfloat ySpeed = 0.007f;

int refreshMillis = 30; // Refresh period in milliseconds

// Projection clipping area

GLdouble clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop;

bool fullScreenMode = true; // Full-screen or windowed mode?

bool paused = false; // Movement paused or resumed

GLfloat xSpeedSaved, ySpeedSaved; // To support resume

/* Initialize OpenGL Graphics */

void initGL() {

glClearColor(0.0, 0.0, 0.0, 1.0); // Set background (clear) color to black

/* Callback handler for window re-paint event */

void display() {

glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer


glMatrixMode(GL_MODELVIEW); // To operate on the model-view matrix

glLoadIdentity(); // Reset model-view matrix

glTranslatef(ballX, ballY, 0.0f); // Translate to (xPos, yPos)

// Use triangular segments to form a circle

glBegin(GL_TRIANGLE_FAN);

glColor3f(0.0f, 0.0f, 1.0f); // Blue

glVertex2f(0.0f, 0.0f); // Center of circle

int numSegments = 100;

GLfloat angle;

for (int i = 0; i <= numSegments; i++) { // Last vertex same as first vertex

angle = i * 2.0f * PI / numSegments; // 360 deg for all segments

glVertex2f(cos(angle) * ballRadius, sin(angle) * ballRadius);

glEnd();

glutSwapBuffers(); // Swap front and back buffers (of double buffered mode)

// Animation Control - compute the location for the next refresh

ballX += xSpeed;

ballY += ySpeed;

// Check if the ball exceeds the edges

if (ballX > ballXMax) {

ballX = ballXMax;

xSpeed = -xSpeed;

else if (ballX < ballXMin) {

ballX = ballXMin;

xSpeed = -xSpeed;
}

if (ballY > ballYMax) {

ballY = ballYMax;

ySpeed = -ySpeed;

else if (ballY < ballYMin) {

ballY = ballYMin;

ySpeed = -ySpeed;

/* Call back when the windows is re-sized */

void reshape(GLsizei width, GLsizei height) {

// Compute aspect ratio of the new window

if (height == 0) height = 1; // To prevent divide by 0

GLfloat aspect = (GLfloat)width / (GLfloat)height;

// Set the viewport to cover the new window

glViewport(0, 0, width, height);

// Set the aspect ratio of the clipping area to match the viewport

glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix

glLoadIdentity(); // Reset the projection matrix

if (width >= height) {

clipAreaXLeft = -1.0 * aspect;

clipAreaXRight = 1.0 * aspect;

clipAreaYBottom = -1.0;

clipAreaYTop = 1.0;

}
else {

clipAreaXLeft = -1.0;

clipAreaXRight = 1.0;

clipAreaYBottom = -1.0 / aspect;

clipAreaYTop = 1.0 / aspect;

gluOrtho2D(clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop);

ballXMin = clipAreaXLeft + ballRadius;

ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;

ballYMax = clipAreaYTop - ballRadius;

/* Called back when the timer expired */

void Timer(int value) {

glutPostRedisplay(); // Post a paint request to activate display()

glutTimerFunc(refreshMillis, Timer, 0); // subsequent timer call at milliseconds

/* Callback handler for normal-key event */

void keyboard(unsigned char key, int x, int y) {

switch (key) {

case 27: // ESC key

exit(0);

break;

/* Callback handler for special-key event */


void specialKeys(int key, int x, int y) {

switch (key) {

case GLUT_KEY_F1: // F1: Toggle between full-screen and windowed mode

fullScreenMode = !fullScreenMode; // Toggle state

if (fullScreenMode) { // Full-screen mode

windowPosX = glutGet(GLUT_WINDOW_X); // Save parameters for restoring later

windowPosY = glutGet(GLUT_WINDOW_Y);

windowWidth = glutGet(GLUT_WINDOW_WIDTH);

windowHeight = glutGet(GLUT_WINDOW_HEIGHT);

glutFullScreen(); // Switch into full screen

else { // Windowed mode

glutReshapeWindow(windowWidth, windowHeight); // Switch into windowed mode

glutPositionWindow(windowPosX, windowPosX); // Position top-left corner

break;

case GLUT_KEY_RIGHT: // Right: increase x speed

xSpeed *= 1.05f; break;

case GLUT_KEY_LEFT: // Left: decrease x speed

xSpeed *= 0.95f; break;

case GLUT_KEY_UP: // Up: increase y speed

ySpeed *= 1.05f; break;

case GLUT_KEY_DOWN: // Down: decrease y speed

ySpeed *= 0.95f; break;

case GLUT_KEY_PAGE_UP: // Page-Up: increase ball's radius

ballRadius *= 1.05f;

ballXMin = clipAreaXLeft + ballRadius;

ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;

ballYMax = clipAreaYTop - ballRadius;


break;

case GLUT_KEY_PAGE_DOWN: // Page-Down: decrease ball's radius

ballRadius *= 0.95f;

ballXMin = clipAreaXLeft + ballRadius;

ballXMax = clipAreaXRight - ballRadius;

ballYMin = clipAreaYBottom + ballRadius;

ballYMax = clipAreaYTop - ballRadius;

break;

/* Callback handler for mouse event */

void mouse(int button, int state, int x, int y) {

if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { // Pause/resume

paused = !paused; // Toggle state

if (paused) {

xSpeedSaved = xSpeed; // Save parameters for restore later

ySpeedSaved = ySpeed;

xSpeed = 0; // Stop movement

ySpeed = 0;

else {

xSpeed = xSpeedSaved; // Restore parameters

ySpeed = ySpeedSaved;

/* Main function: GLUT runs as a console application starting at main() */

int main(int argc, char** argv) {


glutInit(&argc, argv); // Initialize GLUT

glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode

glutInitWindowSize(windowWidth, windowHeight); // Initial window width and height

glutInitWindowPosition(windowPosX, windowPosY); // Initial window top-left corner


(x, y)

glutCreateWindow(title); // Create window with given title

glutDisplayFunc(display); // Register callback handler for window re-paint

glutReshapeFunc(reshape); // Register callback handler for window re-shape

glutTimerFunc(0, Timer, 0); // First timer call immediately

glutSpecialFunc(specialKeys); // Register callback handler for special-key event

glutKeyboardFunc(keyboard); // Register callback handler for special-key event

glutFullScreen(); // Put into full screen

glutMouseFunc(mouse); // Register callback handler for mouse event

initGL(); // Our own OpenGL initialization

glutMainLoop(); // Enter event-processing loop

return 0;

You might also like