我正在尝试使用OpenGL绘制Sierpinski carpet plane fractal,但我的程序一直收到SegFault错误。
我的代码如下:
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
class GLintPoint
{
public:
GLint x, y;
};
int random(int m)
{
return rand() % m;
}
void drawDot(GLint x, GLint y)
{
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void init()
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glColor3f(0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
int isSierpinskiCarpetPixelFilled(int x, int y, int width, int height)
{
GLintPoint point;
// base case 1 of 2
if ((x <= 0)||(y <= 0)||(x>=width)||(y>=height)) //top row or left column or out of bounds should be full
{
point.x = x;
point.y = y;
drawDot(point.x, point.y);
}
{
/*
If the grid was split in 9 parts, what part(x2,y2) would x,y fit into?
*/
int x2 = x * 3 / width; // an integer from 0..2 inclusive
int y2 = y * 3 / height; // an integer from 0..2 inclusive
// base case 2 of 2
if (x2 == 1 && y2 == 1) // if in the center square, it should be empty
return 0;
// general case
/* offset x and y so it becomes bounded by 0..width/3 and 0..height/3
and prepares for recursive call
some offset is added to make sure the parts have all the correct size when
width and height isn't divisible by 3 */
x -= (x2 * width+2) / 3;
y -= (y2 * height+2) / 3;
width = (width +2-x2)/3;
height = (height+2-y2)/3;
}
return isSierpinskiCarpetPixelFilled(x, y, width, height);
}
void drawSierpinskiCarpet()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 1.0, 0.0);
int x = 50;
int y = 50;
isSierpinskiCarpetPixelFilled(x,y,50,50);
glFlush();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("The Sierpinski Carpet");
glutDisplayFunc(drawSierpinskiCarpet);
init();
glutMainLoop();
return EXIT_SUCCESS;
}
答案 0 :(得分:4)
可能会出现堆栈溢出。它似乎无限递归。每次拨打isSierpinskiCarpetPixelFilled
都会产生另一个电话:
return isSierpinskiCarpetPixelFilled(x, y, width, height);
使用给定的输入值,输入参数(按顺序)将为:
50, 50, 50, 50
0, 0, 16, 16
0, 0, 6, 6
0, 0, 2, 2
0, 0, 1, 1
0, 0, 1, 1
... (until stack overflow)