prune rects

pull/1/head
cosmonaut 2022-07-21 15:32:56 -07:00
parent 3bcb73267c
commit d86e094933
1 changed files with 73 additions and 24 deletions

View File

@ -297,7 +297,10 @@ void Cram_Internal_PlaceRect(RectPackContext *context, Rect *rect, int32_t freeR
context->freeRectangleCount -= 1;
/* now we maybe have new free rectangles! */
/* NOTE: free rectangles can overlap. */
if (rect->y < freeRect.y + freeRect.h && rect->y + rect->h > freeRect.y)
{
/* Left side */
if (rect->x > freeRect.x && rect->x < freeRect.x + freeRect.w)
{
@ -314,7 +317,10 @@ void Cram_Internal_PlaceRect(RectPackContext *context, Rect *rect, int32_t freeR
newRect.w = freeRect.x + freeRect.w - (rect->x + rect->w);
Cram_Internal_AddFreeRect(context, newRect);
}
}
if (rect->x < freeRect.x + freeRect.w && rect->x + rect->w > freeRect.x)
{
/* Top side */
if (rect->y > freeRect.y && rect->y < freeRect.y + freeRect.h)
{
@ -332,6 +338,47 @@ void Cram_Internal_PlaceRect(RectPackContext *context, Rect *rect, int32_t freeR
Cram_Internal_AddFreeRect(context, newRect);
}
}
}
static inline uint8_t Cram_Internal_Contains(Rect *a, Rect *b)
{
return b->x >= a->x &&
b->y >= a->y &&
b->x + b->w <= a->x + a->w &&
b->y + b->h <= a->y + a->h;
}
void Cram_Internal_PruneRects(RectPackContext *context)
{
int32_t i, j;
Rect *a;
Rect *b;
for (i = context->freeRectangleCount - 1; i >= 0; i -= 1)
{
a = &context->freeRectangles[i];
for (j = context->freeRectangleCount - 1; j > i; j -= 1)
{
b = &context->freeRectangles[j];
if (Cram_Internal_Contains(b, a))
{
/* plug the hole */
context->freeRectangles[j] = context->freeRectangles[context->freeRectangleCount - 1];
context->freeRectangleCount -= 1;
break;
}
if (Cram_Internal_Contains(a, b))
{
/* plug the hole */
context->freeRectangles[j] = context->freeRectangles[context->freeRectangleCount - 1];
context->freeRectangleCount -= 1;
}
}
}
}
/* Given rects with width and height, modifies rects with packed x and y positions. */
int8_t Cram_Internal_PackRects(RectPackContext *context, Rect *rects, uint32_t numRects)
@ -385,6 +432,8 @@ int8_t Cram_Internal_PackRects(RectPackContext *context, Rect *rects, uint32_t n
/* plug the hole */
rectsToPack[bestRectIndex] = rectsToPack[rectsToPackCount - 1];
rectsToPackCount -= 1;
Cram_Internal_PruneRects(context);
}
Cram_free(rectsToPack);