边界填充C ++ OpenGL

时间:2014-04-28 16:25:24

标签: c++ opengl

我在Visual Studio 2013中用C ++编写了边界填充算法代码,

但它没有正常工作, 它仅在调用boundaryFill4函数一次时有效,例如:

boundaryFill4 (x + 1, y); 

但它应该是:

boundaryFill4 (x + 1, y);
boundaryFill4 (x -1, y);
boundaryFill4 (x , y + 1);
boundaryFill4 (x , y -1);

这是代码:

#include "stdafx.h"
#include <iostream>
#include "GL/glut.h"
using namespace std;
void init();
void display();
void setPixel(int, int);
void getPixel(int, int, float*);
void mouse(int, int, int, int);
float borderColor[3]={0,0,1}, fillColor[3]={0,0,1};

int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(400, 400);
    glutInitWindowPosition(400, 100);
    glutCreateWindow("Project");
    init();
    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMainLoop();
    return 0;
}
bool match(float* x1, float* x2){
    return (x1[0] == x2[0] && x1[1] == x2[1] && x1[2] == x2[2]);
}
void boundaryFill4(int x, int y){
    float interiorColor[3];
    getPixel (x, y, interiorColor);
    if (!match(interiorColor, borderColor) && !match(interiorColor, fillColor)) {
    setPixel (x, y);
    boundaryFill4 (x + 1, y);
    boundaryFill4 (x -1, y);
    boundaryFill4 (x , y + 1);
    boundaryFill4 (x , y -1);
    } 
}
void mouse(int button, int state, int x, int y){
    //cout << "x: "<< x << ", y:" << y << endl;
    boundaryFill4(x, y);
    glFlush();
}
void draw(){
    glBegin(GL_LINE_LOOP);
        glVertex2i(100, 100);
        glVertex2i(300, 100);
        glVertex2i(300, 300);
        glVertex2i(100, 300);
    glEnd();
}
void setPixel(int x, int y){
    glBegin(GL_POINTS);
        glColor3fv(borderColor);
        glVertex2i(x, y);
    glEnd();
}
void getPixel(int x, int y, float* color) {
    glReadPixels(x,y,1,1,GL_RGB,GL_FLOAT, color);
    //cout << "R:" << color[0] << ", G:" << color[1] << ", B:" << color[2] << "\n";
}
void display(){
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3fv(borderColor);
    draw();
    glFlush();
}
void init(){
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0.0, 400.0, 400.0, 0.0);
}

1 个答案:

答案 0 :(得分:1)

当您的代码进行大量递归调用并导致堆栈溢出时,就会发生这种情况。 减小图形的大小,就像填充三角形一样,然后减小其尺寸,就可以了。 我可以在您的代码中看到您给出的图形尺寸非常大,这就是它给出错误的原因。