Search code examples
algorithmpolygonfillpolyfills

Polygon Filling | Scan Line Algorithm


I'm developing a Game like paper.io in C++ with Win32 API. My Game data is stored in an array like:

1 = Player's Head

2 = Player's base

3 = Player's tail


  1. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  2. 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0,

  3. 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0,

  4. 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 0,

  5. 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,

  6. 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0,

  7. 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0,

  8. 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0,

  9. 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  10. 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

  11. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

Now I want to fill the polygon (Player's tail) with the Number 2 (Player's base).

Scan Line Algorithm:

What works:

  1. If I scan the 5. line The first 3 trigger the algorithm and toggle the painting function. The next 3 toggles it again it stops the painting function again

Problems:

  1. If I scan the 2. line After Every 3 the painting function will be toggled and after the line, it will paint further, because it's an odd amount of numbers.

Solutions:

  1. Toggle on the transition from zero to non-zero (and non-zero to zero)

Boundary Fill Algorithm:

Problems:

  1. I need to find the middle/spot to begin, that's in the polygon

Solution

  • There are a lot of special cases that make it tricky to determine which areas are inside the new base vs. outside, but this one is simple and reliable:

    1. Do a flood fill starting at the outer edges to find the area that is not in the base. This fill can cover any color except 1, 2, and 3
    2. Fill everything else with color 2 to make the new base.