My goal here is to take a grid of rectangles and combine them in such a way that reduces the amount of rectangles. Each grid is marked as False if nothing is in it otherwise it contains a rectangle with a value called level. Rectangles with matching levels can be merged with another using union_ip which joins two rectangles into one, in place. The result should return a list of rectangles of the new merged ones.
However I am getting inconsistent behavior. Here is an example. The black area contains rectangles while the white area does not. The thicker red line shows the result of the merge. The top right is what is produced in the current case I've been testing. The bottom left case is what I am looking for but it will only work with a border or if only the top or bottom borders are added.
If anyone can help I'd appreciate it. I know the code is a mess, but it has been working up until now.
def getGrid():
grid = {}
for i in xrange(0, 18):
grid[i] = {}
for j in xrange(0, 18):
grid[i][j] = False;
return grid
def getReducedRects(grid):
tablx = {}
myrect = False
x_max, y_max = len(grid), len(grid[0]);
for x in xrange(0, x_max):
for y in xrange(0, y_max):
if grid[x][y]:
if myrect:
if grid[x][y].level == myrect.level:
myrect.union_ip(grid[x][y])
else:
try:
tablx[x].append(myrect);
except:
tablx[x] = [];
tablx[x].append(myrect);
myrect = grid[x][y];
else:
myrect = grid[x][y].copy();
else:
if myrect:
try:
tablx[x].append(myrect);
except:
tablx[x] = [];
tablx[x].append(myrect);
myrect = False;
for x in xrange(0, x_max - 1):
try:
le = len(tablx[x]);
tablx[x + 1];
except:
continue;
i = 0
while i < le:
r = tablx[x][i];
coll = aabb_collision_single(r, tablx[x + 1]);
for rc in coll:
if rc.bottom == r.bottom and rc.top == r.top and r.level == rc.level:
rc.union_ip(r);
del(tablx[x][i]);
le -= 1;
i -= 1;
break;
i += 1;
myr = []
for r in tablx.itervalues():
myr += r;
return myr
RESOLVED by adding another check at the end of the column! Sorry for my long spaghetti code but it works perfectly now.
def getReducedRects(grid):
tablx = {}
myrect = False
x_max, y_max = len(grid), len(grid[0]);
for x in xrange(0, x_max):
for y in xrange(0, y_max):
if grid[x][y]:
if myrect:
if grid[x][y].level == myrect.level:
myrect.union_ip(grid[x][y])
else:
try:
tablx[x].append(myrect);
except:
tablx[x] = [];
tablx[x].append(myrect);
myrect = grid[x][y];
else:
myrect = grid[x][y].copy();
else:
if myrect:
try:
tablx[x].append(myrect);
except:
tablx[x] = [];
tablx[x].append(myrect);
myrect = False;
if myrect:
try:
tablx[x].append(myrect);
except:
tablx[x] = [myrect];
myrect = False;
for x in xrange(0, x_max - 1):
try:
le = len(tablx[x]);
tablx[x + 1];
except:
continue;
i = 0
while i < le:
r = tablx[x][i];
coll = aabb_collision_single(r, tablx[x + 1]);
for rc in coll:
if rc.bottom == r.bottom and rc.top == r.top and r.level == rc.level:
rc.union_ip(r);
del(tablx[x][i]);
le -= 1;
i -= 1;
break;
i += 1;
myr = []
for r in tablx.itervalues():
myr += r;
return myr