Files
Computer-Graphics-Lab/lab1/3.cpp
2026-04-10 14:32:28 +08:00

86 lines
2.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <GL/glut.h> // 引入 GLUT 库,用于创建窗口和处理事件
#include <iostream>
using namespace std;
// 辅助函数根据八分对称性绘制8个对称点
void plotCirclePoints(int xc, int yc, int x, int y) {
glBegin(GL_POINTS);
// 第1象限
glVertex2i(xc + x, yc + y);
glVertex2i(xc + y, yc + x);
// 第2象限
glVertex2i(xc - y, yc + x);
glVertex2i(xc - x, yc + y);
// 第3象限
glVertex2i(xc - x, yc - y);
glVertex2i(xc - y, yc - x);
// 第4象限
glVertex2i(xc + y, yc - x);
glVertex2i(xc + x, yc - y);
glEnd();
}
// 中点画圆算法主函数
// 参数: (xc, yc) 为圆心坐标, r 为半径
void midpointCircle(int xc, int yc, int r) {
int x = 0;
int y = r;
// 初始决策参数 d = 3 - 2r
int d = 3 - 2 * r;
// 绘制初始点
plotCirclePoints(xc, yc, x, y);
// 循环计算并绘制第一个八分之一圆弧,直到 x <= y
while (x <= y) {
x++;
if (d < 0) {
// 中点在圆内,选择正右方的点 (x+1, y)
d = d + 4 * x + 6;
} else {
// 中点在圆外或圆上,选择右下方的点 (x+1, y-1)
d = d + 4 * (x - y) + 10;
y--;
}
std::cout<< xc + x << ", " << yc + y << std::endl;
// 绘制由当前(x, y)决定的8个对称点
plotCirclePoints(xc, yc, x, y);
}
glFlush(); // 强制执行所有OpenGL命令
}
// --- OpenGL 设置与回调函数 ---
// 显示回调函数
void display() {
glClear(GL_COLOR_BUFFER_BIT); // 清除颜色缓冲区
glColor3f(1.0, 0.0, 0.0); // 设置绘制颜色为红色
glPointSize(2.0f); // 设置点的大小
// 调用中点画圆算法
midpointCircle(50, 50, 30);
}
// 初始化函数
void init() {
glClearColor(0.0, 0.0, 0.0, 1.0); // 设置背景颜色为黑色
glMatrixMode(GL_PROJECTION); // 设置投影矩阵
gluOrtho2D(0.0, 500.0, 0.0, 500.0); // 定义二维正交投影,窗口坐标范围 (0,0) 到 (500,500)
}
// --- 主函数 ---
int main(int argc, char** argv) {
glutInit(&argc, argv); // 初始化 GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // 使用单缓冲和RGB颜色模型
glutInitWindowSize(500, 500); // 设置窗口大小
glutInitWindowPosition(100, 100); // 设置窗口位置
glutCreateWindow("Midpoint Circle Algorithm"); // 创建窗口并设置标题
init(); // 调用初始化函数
glutDisplayFunc(display); // 注册显示回调函数
glutMainLoop(); // 进入 GLUT 事件处理主循环
return 0;
}