gpt4 book ai didi

c++ - OpenGL 程序的段错误

转载 作者:行者123 更新时间:2023-11-30 02:05:14 24 4
gpt4 key购买 nike

我正在尝试绘制 Sierpinski carpet plane fractal使用 OpenGL,但我的程序不断收到 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;
}

最佳答案

很可能出现堆栈溢出。它似乎在无限递归。每次调用 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)

关于c++ - OpenGL 程序的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9692177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com