边界填充 C++ OpenGL [英] Boundary Fill C++ OpenGL

查看:74
本文介绍了边界填充 C++ OpenGL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've wrote this code for Boundary Fill Algorithm with C++ in Visual Studio 2013,

但它不能正常工作,只有在调用boundaryFill4 函数一次时才有效,例如:

But it doesn't work correctly, It works only if call boundaryFill4 function one time, eg:

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);
}

推荐答案

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

This happens when your code is making a lot of recursion calls and leads to stack overflow. Reduce the size of your figure like if you are filling a triangle then reduce its dimentions and it will be fine. I can see in your code you have give a very large size of your figure that's why its giving error.

这篇关于边界填充 C++ OpenGL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆