Skip to content
Open
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
5 changes: 3 additions & 2 deletions src/gcode/job.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,11 @@ describe('buildJob images', () => {

describe('buildJob device origin', () => {
// A 10x10 square on a 100x80 bed: its top-left corner is (20, 10) and the
// bottom-right corner is (30, 20) in document coordinates.
// bottom-right corner is (30, 20) in document coordinates. No stroke, so
// left/top are the drawn outline itself (a stroke would push it inwards).
async function planFor(origin: (typeof DEFAULT_DEVICE)['origin']) {
const layer = layerWithMode('line');
const rect = new Rect({ left: 20, top: 10, width: 10, height: 10 });
const rect = new Rect({ left: 20, top: 10, width: 10, height: 10, strokeWidth: 0 });
rect.set('layerId', layer.id);
return buildJob({
objects: [rect],
Expand Down
79 changes: 79 additions & 0 deletions src/geometry/paperOps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest';
import { Group, Path, Rect, type FabricObject } from 'fabric';
import { objectContours } from '@/gcode/geometry';
import paper from 'paper';
import { ensurePaper } from './paperSetup';
import { objectToSceneCompoundPathData, objectToScenePathData } from './paperOps';

type P = { x: number; y: number };

function bounds(points: P[]) {
const xs = points.map((p) => p.x);
const ys = points.map((p) => p.y);
return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) };
}

/** Where Fabric draws a rect's corners: its own box through its absolute matrix. */
function drawnCorners(rect: Rect): P[] {
const m = rect.calcTransformMatrix();
const w = rect.width / 2;
const h = rect.height / 2;
return [
[-w, -h],
[w, -h],
[w, h],
[-w, h],
].map(([x, y]) => ({ x: m[0] * x + m[2] * y + m[4], y: m[1] * x + m[3] * y + m[5] }));
}

function dataBounds(data: string | null) {
ensurePaper();
const item = new paper.CompoundPath(data ?? '');
const b = item.bounds;
item.remove();
return { minX: b.x, minY: b.y, maxX: b.x + b.width, maxY: b.y + b.height };
}

/** Within 0.005 mm: toSVG() rounds coordinates to 4 decimals before Paper reads them. */
function expectSameBox(a: ReturnType<typeof bounds>, b: ReturnType<typeof bounds>) {
expect(a.minX).toBeCloseTo(b.minX, 2);
expect(a.minY).toBeCloseTo(b.minY, 2);
expect(a.maxX).toBeCloseTo(b.maxX, 2);
expect(a.maxY).toBeCloseTo(b.maxY, 2);
}

describe('geometry/paperOps scene geometry', () => {
// The cut used to be re-aligned to getBoundingRect(), which includes the
// stroke and, for a rotated object, the rotated box's hull: rotated parts
// were cut millimetres away from where they are drawn.
for (const angle of [0, 30, 45, 90, 137]) {
it(`cuts a rect rotated ${angle}° where it is drawn`, () => {
const rect = new Rect({ left: 50, top: 40, width: 60, height: 20, angle, strokeWidth: 2, stroke: '#f00', fill: '' });
const expected = bounds(drawnCorners(rect));
expectSameBox(bounds(objectContours(rect).flatMap((c) => c.points)), expected);
expectSameBox(dataBounds(objectToSceneCompoundPathData(rect)), expected);
expectSameBox(dataBounds(objectToScenePathData(rect)), expected);
});
}

it('cuts a rotated, scaled group where its shapes are drawn', () => {
const inner = new Rect({ left: 0, top: 0, width: 20, height: 10, strokeWidth: 1, stroke: '#f00', fill: '' });
const tri = new Path('M 30 0 L 50 20 L 30 25 Z', { strokeWidth: 1, stroke: '#f00', fill: '' });
const group = new Group([inner, tri], { left: 100, top: 60, angle: 33, scaleX: 1.5, scaleY: 1.5 });
const cut = bounds(objectContours(group as FabricObject).flatMap((c) => c.points));
const rectBox = bounds(drawnCorners(inner));
// The rect is entirely inside the cut's bounds and touches its extremes
// on the sides it reaches.
expect(cut.minX).toBeLessThanOrEqual(rectBox.minX + 1e-3);
expect(cut.minY).toBeLessThanOrEqual(rectBox.minY + 1e-3);
const m = tri.calcTransformMatrix();
const off = tri.pathOffset;
const triPts = [
[30, 0],
[50, 20],
[30, 25],
].map(([x, y]) => ({ x: m[0] * (x - off.x) + m[2] * (y - off.y) + m[4], y: m[1] * (x - off.x) + m[3] * (y - off.y) + m[5] }));
expectSameBox(cut, bounds([...drawnCorners(inner), ...triPts]));
});
});
36 changes: 9 additions & 27 deletions src/geometry/paperOps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,24 +88,15 @@ export function objectToPathData(obj: FabricObject): string | null {
}

/**
* Scene-space path data. Paper normalises imported SVG coordinates to the
* origin, so we re-align the result to the source object's bounding box.
* Scene-space path data. `toSVG()` carries the object's full transform, so the
* imported geometry is already where the canvas draws it.
*
* It used to be re-aligned to `getBoundingRect()`, but that box includes the
* stroke and, for a rotated object, is the rotated box's axis-aligned hull:
* the cut drifted by up to several millimetres from what was drawn.
*/
export function objectToScenePathData(obj: FabricObject): string | null {
const data = objectToPathData(obj);
if (!data) return null;
try {
ensurePaper();
const item = new paper.CompoundPath(data);
const bounds = item.bounds;
const target = obj.getBoundingRect();
item.translate(new paper.Point(target.left - bounds.x, target.top - bounds.y));
const out = item.pathData;
item.remove();
return out ?? null;
} catch {
return null;
}
return objectToPathData(obj);
}

/** Import a Fabric object's geometry as scene-space Paper items (holes kept). */
Expand All @@ -118,10 +109,7 @@ export function objectToScenePathItems(obj: FabricObject): paper.PathItem[] {
const paths: paper.PathItem[] = [];
collectPaths(imported, paths);
if (paths.length === 0) return [];
const bounds = imported.bounds;
const target = obj.getBoundingRect();
const dx = target.left - bounds.x;
const dy = target.top - bounds.y;
// No re-alignment: see objectToScenePathData.
const out: paper.PathItem[] = [];
for (const p of paths) {
p.fillColor = new paper.Color('black');
Expand All @@ -131,7 +119,6 @@ export function objectToScenePathItems(obj: FabricObject): paper.PathItem[] {
p.fillRule = 'evenodd';
const cloned = p.clone({ insert: false }) as paper.PathItem;
cloned.fillRule = 'evenodd';
cloned.translate(new paper.Point(dx, dy));
out.push(cloned);
}
imported.remove();
Expand All @@ -156,11 +143,7 @@ export function objectToSceneCompoundPathData(obj: FabricObject): string | null
collectPaths(imported, paths);
if (paths.length === 0) return null;

const bounds = imported.bounds;
const target = obj.getBoundingRect();
const dx = target.left - bounds.x;
const dy = target.top - bounds.y;

// No re-alignment: see objectToScenePathData.
const data = paths
.map((p) => (p as unknown as { pathData?: string }).pathData ?? '')
.filter(Boolean)
Expand All @@ -169,7 +152,6 @@ export function objectToSceneCompoundPathData(obj: FabricObject): string | null

const item = new paper.CompoundPath(data);
item.fillRule = 'evenodd';
item.translate(new paper.Point(dx, dy));
const out = item.pathData ?? null;
item.remove();
return out;
Expand Down