Advertisement
nasarouf

2D polygon filling

Apr 20th, 2017
705
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. //2D polygon filling (arbitrary poly; full and partial pixels are counted. handles slivers. x incremened ++)
  2. //nasarouf@cs.ubc.ca
  3.  
  4. // old, untested code
  5.  
  6. #include <iostream>
  7. #include <algorithm>
  8. #include <cmath>
  9. #include <map>
  10. using namespace std;
  11.  
  12.  
  13. #define MAX 100
  14. #define X first
  15. #define YY second
  16. #define A first
  17. #define B second
  18. typedef pair<int,int> PII;
  19. typedef pair<PII,PII> Seg;
  20.  
  21. pair<double,double> y[MAX];
  22. int Y[MAX];
  23. PII p[MAX];
  24. Seg seg[MAX],li[MAX];
  25. map<int,int> m;
  26.  
  27. int main() {
  28.     int x, i, it, n, a, lin, lit, j, segn;
  29.     Seg s, tmp;
  30.     while ((cin >> n) && n) {
  31.         for (i = 0; i < n; i++) cin >> p[i].first >> p[i].second;
  32.         segn = 0;
  33.         m.clear();
  34.         for (i = j = 0; i < n; i++) {
  35.             if (p[i].first == p[(i + 1) % n].first) continue;
  36.             else if (p[i] < p[(i + 1) % n]) seg[j++] = (make_pair(p[i], p[(i + 1) % n]));
  37.             else seg[j++] = (make_pair(p[(i + 1) % n], p[i]));
  38.         }
  39.         segn = j;
  40.         sort(seg, seg + segn);
  41.         a = 0;
  42.         x = seg[0].first.first;
  43.         it = 0;
  44.         lin = 0;
  45.         while (it < segn || lin) {
  46.             for (i = 0, lit = 0; lit < lin; lit++, i++)
  47.                 y[i] = make_pair(li[lit].A.YY + (double)(li[lit].B.YY - li[lit].A.B)*(x - 1 - li[lit].A.X) / (double)(li[lit].B.X - li[lit].A.X),
  48.                     li[lit].A.YY + (double)(li[lit].B.YY - li[lit].A.YY)*(x - li[lit].A.X) / (double)(li[lit].B.X - li[lit].A.X));
  49.             n = i;
  50.             sort(y, y + n);
  51.             for (i = 0; i < n; i += 2) {
  52.                 Y[i + 1] = (int)(ceil(max(y[i + 1].first, y[i + 1].second)));
  53.                 Y[i] = floor(min(y[i].first, y[i].second));
  54.             }
  55.             for (i = 0; i < n; i += 2) {
  56.                 if (i && Y[i] < Y[i - 1]) Y[i] = Y[i - 1];
  57.                 if (Y[i + 1] < Y[i]) Y[i + 1] = Y[i];
  58.                 a += Y[i + 1] - Y[i];
  59.             }
  60.             if (m[x])
  61.                 for (i = 0; i < lin; )
  62.                     if (li[i].second.first == x) swap(li[i], li[--lin], tmp);
  63.                     else i++;
  64.             while (it < segn && seg[it].first.first == x) {
  65.                 li[lin++] = seg[it];
  66.                 m[seg[it].second.first] = 1;
  67.                 it++;
  68.             }
  69.             x++;
  70.         }
  71.         cout << a << endl;
  72.     }
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement