0
votes

I wrote the following piece of code for flood-fill as part of a paint program I'm developing:

void setPixel(int x, int y)
{
     glColor4f(red, green, blue, alpha);
     glBegin(GL_POINTS);
     glVertex2f(x, y);
     glEnd();
     glFlush();
}
void floodFill(int x, int y)
{
     unsigned char pick_col[3];
     float R, G, B;
     glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pick_col);
     R = (float) pick_col[0]/255.0;
     G = (float) pick_col[1]/255.0;
     B = (float) pick_col[2]/255.0;

     //std::cout<<R<<" "<<G<<" "<<B<<"\n";

     if(R!=0.0 || G!=0.0 || B!=0.0) //true for any non-black colour (BTW, my canvas is black)
     return;

     setPixel(x,y);

     floodFill(x+1,y);
     floodFill(x,y+1);
     floodFill(x,y-1);
     floodFill(x-1,y);
}

Unfortunately, this code is not working. For example, I first drew a rectangle and tried to fill the rectangle. What actually happened was that from the point where I clicked to fill, pixels to its right started getting filled in a line and eventually the pixels near the right-most edge started getting drawn. But that's all that happened. I don't understand why.

1
Why are you converting the RGB values to float? Why not just check for zero and be done with it?Captain Obvlious
@CaptainObvlious Okay, so I modified the code to avoid the conversion but the code still doesn't work. I have the feeling my algorithm is incorrect but it doesn't seem so when I look at the code.Ricky
Try reading from this website... ericlippert.com/2014/03/05/how-to-debug-small-programsuser10066522

1 Answers

0
votes

First of all: don't do this. Doing it completely on the CPU will be orders of magnitude faster than doing 2 roundtrips to the GPU per pixel.

Having said that, I can still see the problem with your implementation: you are never checking the borders. glReadPixels will just return undefined results if you try to read back pixels which lie outside of the framebuffer, and that might very well be all zeros.