Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions lib/solvers/RectDiffSeedingSolver/computeInverseRects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,22 @@ type ComputeInverseRectsOptions = {
minGridSize?: number
}

/** Merge grid lines separated only by floating-point roundoff. */
function getUniqueGridCoordinates(coordinates: Set<number>): number[] {
const sortedCoordinates = Array.from(coordinates).sort((a, b) => a - b)
const uniqueCoordinates: number[] = []
for (const coordinate of sortedCoordinates) {
const previousCoordinate = uniqueCoordinates.at(-1)
if (
previousCoordinate === undefined ||
coordinate - previousCoordinate > EPS
) {
uniqueCoordinates.push(coordinate)
}
}
return uniqueCoordinates
}

/**
* Simplify a polygon by reducing coordinate precision to avoid excessive grid cells.
* This rounds coordinates to a grid and removes duplicates.
Expand Down Expand Up @@ -121,8 +137,11 @@ export function computeInverseRects(
Math.max(bounds.width, bounds.height) / MAX_DIAGONAL_SUBDIVISIONS,
),
})
const xSorted = Array.from(xs).sort((a, b) => a - b)
const ySorted = Array.from(ys).sort((a, b) => a - b)
// Symmetric diagonal edges can produce coordinates that differ only by
// floating-point roundoff. Treat them as the same grid line before forming
// cells; otherwise slivers fragment the subsequent merge passes.
const xSorted = getUniqueGridCoordinates(xs)
const ySorted = getUniqueGridCoordinates(ys)

// 2. Generate grid cells and classify them
const rawRects: XYRect[] = []
Expand Down
4 changes: 2 additions & 2 deletions tests/__snapshots__/compute-inverse-rects-board109.snap.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions tests/compute-inverse-rects-narrow-feature.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { expect, test } from "bun:test"
import { computeInverseRects } from "../lib/solvers/RectDiffSeedingSolver/computeInverseRects"
import { containsPoint } from "../lib/utils/rectdiff-geometry"

test("coordinate deduplication retains a real narrow notch", () => {
const outline = [
{ x: 0, y: 0 },
{ x: 10, y: 0 },
{ x: 10, y: 10 },
{ x: 5.000001, y: 10 },
{ x: 5.000001, y: 5 },
{ x: 5, y: 5 },
{ x: 5, y: 10 },
{ x: 0, y: 10 },
]
const rects = computeInverseRects(
{ x: 0, y: 0, width: 10, height: 10 },
outline,
)
expect(
rects.some((rect) => containsPoint(rect, { x: 5.0000005, y: 8 })),
).toBe(true)
expect(rects.some((rect) => containsPoint(rect, { x: 4.999, y: 8 }))).toBe(
false,
)
expect(rects.some((rect) => containsPoint(rect, { x: 5.001, y: 8 }))).toBe(
false,
)
})
Loading