Skip to content

Instantly share code, notes, and snippets.

@superzazu
Created November 13, 2017 17:09
Show Gist options
  • Save superzazu/6abea714dcf2f78218d171bd4c2b7ea6 to your computer and use it in GitHub Desktop.
Save superzazu/6abea714dcf2f78218d171bd4c2b7ea6 to your computer and use it in GitHub Desktop.
Simple screen buffer with OpenGL2 and GLFW3
// simple screen buffer with OpenGL 2 (and GLFW3)
// build with:
// Linux: gcc main.c -lglfw -lGL
// macOS: gcc main.c -lglfw -framework OpenGL
#include <GLFW/glfw3.h>
static const int WIN_WIDTH = 160;
static const int WIN_HEIGHT = 144;
int main(int argc, char **argv) {
// GLFW setup (creating window + OpenGL context)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
GLFWwindow* window;
if (!glfwInit()) {
return -1;
}
window = glfwCreateWindow(WIN_WIDTH * 2, WIN_HEIGHT * 2, "test",
NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
glfwSetWindowSizeLimits(window, WIN_WIDTH, WIN_HEIGHT,
GLFW_DONT_CARE, GLFW_DONT_CARE);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
//
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float screen_buffer[WIN_HEIGHT][WIN_WIDTH][3];
GLuint texture;
// zero-ing the screen_buffer + putting random values in it
for (int x=0; x<WIN_WIDTH; x++) {
for (int y=0; y<WIN_HEIGHT; y++) {
screen_buffer[y][x][0] = 0;
screen_buffer[y][x][1] = 0;
screen_buffer[y][x][2] = 0;
}
}
screen_buffer[80][80][0] = 0;
screen_buffer[80][80][1] = 1;
screen_buffer[80][80][2] = 0;
screen_buffer[81][80][0] = 1;
screen_buffer[81][80][1] = 0;
screen_buffer[81][80][2] = 0;
screen_buffer[83][85][0] = 0;
screen_buffer[83][85][1] = 0;
screen_buffer[83][85][2] = 1;
// creating the OpenGL texture
glGenTextures(1, &texture); // create texture
glBindTexture(GL_TEXTURE_2D, texture); // specify that the texture is 2D
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glEnable(GL_TEXTURE_2D);
// copying the contents of screen_buffer to the OpenGL texture
// call that every time you want to update the texture with new buffer
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIN_WIDTH, WIN_HEIGHT, 0,
GL_RGB, GL_FLOAT, screen_buffer);
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
// draw the textured quad
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(-1, 1);
glTexCoord2f(0, 1); glVertex2f(-1, -1);
glTexCoord2f(1, 1); glVertex2f(1, -1);
glTexCoord2f(1, 0); glVertex2f(1, 1);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment