Skip to content

Instantly share code, notes, and snippets.

@z1nc0r3
Created February 1, 2023 03:09
Show Gist options
  • Save z1nc0r3/82610dd75c689c68ffc16ce00ba053c0 to your computer and use it in GitHub Desktop.
Save z1nc0r3/82610dd75c689c68ffc16ce00ba053c0 to your computer and use it in GitHub Desktop.
Bresenham's Circle Algorithm
#include <glut.h>
#include <math.h>
#include <cmath>
int width = 600, height = 600;
int xOg = 200, yOg = 200;
int xa, ya, xb, yb;
void putPixel(int x, int y) {
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
glFlush();
}
void init() {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
}
void display() {
glClearColor(0, 1, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void plotCircle(int h, int k, int x, int y) {
putPixel((x + h), (y + k));
putPixel((y + h), (x + k));
putPixel((-y + h), (x + k));
putPixel((-x + h), (y + k));
putPixel((-x + h), (-y + k));
putPixel((-y + h), (-x + k));
putPixel((y + h), (-x + k));
putPixel((x + h), (-y + k));
}
void bresenhamCircle(int h, int k, int r)
{
int x = 0, y = r, d = 3 - 2 * r;
while (x <= y) {
plotCircle(h, k, x, y);
if (d < 0) {
d = d + 4 * x + 6;
}
else {
d = d + 4 * (x - y) + 10;
y--;
}
x++;
}
}
void mouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON) {
if (state == GLUT_DOWN) {
xa = x;
ya = height - y;
}
if (state == GLUT_UP) {
xb = x;
yb = height - y;
glutPostRedisplay();
int r = (int) sqrt(pow((double)(xb - xa), 2) + pow((double)(yb - ya), 2));
bresenhamCircle(xa, ya, r);
}
}
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(width, height);
glutCreateWindow("Polygon Creator");
init();
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment