8000 Add outline scaling to the tool editor by jasonmadigan · Pull Request #258 · tracefinity/tracefinity · GitHub
[go: up one dir, main page]

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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ No API key and prefer not to use the local model? Upload a mask manually:
- **Selective saving** -- Choose which traced outlines to keep before saving to your library
- **Tool library** -- Save traced tools and reuse them across multiple bins
- **Bin projects** -- Plan a group of tools and bins together, track which tools still need bins, and create project-scoped bins
- **Tool editor** -- Rotate tools, add/remove vertices, adjust outlines, snap to grid
- **Tool editor** -- Rotate tools, add/remove vertices, adjust outlines, scale to a measured size, snap to grid
- **Smooth or accurate** -- Toggle Chaikin subdivision for smooth curves, or keep the raw trace; SVG and STL exports both respect this
- **Finger holes** -- Circular, square, or rectangular cutouts for easy tool removal
- **Interior rings** -- Hollow tools (e.g. spanners) traced correctly with holes preserved
Expand Down
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Reference for AI agents. Check here before suggesting new features or claiming s
- 90-degree rotation (clockwise/counter-clockwise)
- Flip/mirror (horizontal and vertical)
- Auto-rotate (minimise bounding box)
- Uniform scaling (typed width, height or percentage; cutouts keep their size)
- Interior rings / fill-in mode for donut shapes
- Undo/redo (Ctrl+Z / Ctrl+Shift+Z)
- Source image overlay with opacity control
Expand Down
12 changes: 8 additions & 4 deletions docs/gotchas.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,14 @@ mesh booleans were measured at 10-100x faster for this workload. See
- Undo/redo uses the `useHistory` hook (deep-clone, Cmd+Z handling). The `set()` method pushes to history; `undo()`/`redo()` call the `onChange` callback.
- The tool editor's Detail slider derives from the latest edited outline. Keep
its full-detail base and slider level in undo history with the points. Manual
vertex edits establish a new base; rotation and reflection transform the base
with the displayed outline; changing Detail alone preserves it. Retaining the
mount-time base can silently undo a saved size correction. An edit after undo
must create a new history entry and replace the redo branch.
vertex edits establish a new base; rotation, reflection and scaling transform
the base with the displayed outline; changing Detail alone preserves it.
Retaining the mount-time base can silently undo a saved size correction. An
edit after undo must create a new history entry and replace the redo branch.
- The tool editor's Size fields scale on Enter only (`commitOnBlur={false}` on `NumericInput`). A drag
snapshots the outline on mousedown, before the blur that mousedown causes, so a
scale committed on blur would be overwritten by the drag while the photo matrix
and Detail base stayed scaled.
- ToolEditor and BinEditor are split into orchestrator + toolbar + canvas sub-components. `CutoutOverlay` renders finger holes in both.

## AVX / ONNX requirement
Expand Down
1 change: 1 addition & 0 deletions docs/usage/tool-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ used for bins and SVG exports. This preference is saved with the tool.
- Flip horizontally or vertically.
- Auto-rotate: finds the rotation angle that minimises the bounding box. Runs on the backend.
- Free-rotate by dragging the rotation handle near the centroid.
- Size: the width and height fields show the outline's bounding box in mm. Type a measured width or height and press Enter to scale the whole outline to match, keeping its proportions. A percentage scales it relative to its current size, then the field returns to 100. Leaving a field without pressing Enter discards what was typed. Cutouts move with the outline but keep their own size.

## Grid snap

Expand Down
22 changes: 20 additions & 2 deletions docs/usage/uploading-photos.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,25 @@ The paper is for scale only. Tools can overflow the paper edges. The full visibl
- **Flat tools** -- tools should lie flat on the paper. Raised handles or 3D shapes confuse the mask generation.
- **No overlap** -- leave a small gap between tools so the AI can separate them.
- **Shoot from above** -- aim for directly overhead. Perspective correction handles some angle, but straight-down needs the least correction. Overhead does not mean close up: distance matters more than angle for scale accuracy.
- **Shoot from a distance** -- 50-60cm or more, with the page filling around half the frame. The paper calibrates the table surface, so anything raised above it projects oversized by H/(H-t) (camera height H, tool thickness t). A thick tool shot from around 20cm can trace roughly 8% too large; from 60cm or more that drops to around 2%.
- **Shoot from a distance** -- 50-60cm or more, with the page filling around half the frame; zoom in if the page looks small. The paper calibrates the table surface, so an outline raised above it traces oversized by H/(H-t) (camera height H, outline height t): about 2.5% for an edge 15mm above the paper from 60cm. See [Tall or thick objects](#tall-or-thick-objects).

## Tall or thick objects

The paper sets the scale at the table surface. The outline Tracefinity traces is the widest edge the camera can see, and on a tall object that edge is the top, which is nearer the lens than the paper. It traces too large, by roughly the height of that edge divided by the camera height.

| Edge above the paper | From 30cm | From 60cm | From 1.5m |
|-|-|-|-|
| 15mm | 5% | 2.5% | 1% |
| 40mm | 15% | 7% | 3% |
| 75mm | 33% | 14% | 5% |

To get the size right:

1. Lay the object on its flattest side, so the traced edge is as low as it can be.
2. Shoot from as far as is practical and zoom in until the page fills about half the frame.
3. Measure one dimension of the object, open the tool in the [tool editor](tool-editor.md#transforms) and type that measurement into the matching Size field and press Enter. The whole outline scales to fit.

One scale suits an object whose outline forms at a single height. Where parts of the outline sit at different heights, set the size from the main body and adjust the rest by moving vertices.

## Photo warnings

Expand All @@ -39,4 +57,4 @@ After uploading, select A4, Letter, A3, or Tabloid. Pick whichever you actually

## Troubleshooting

- **Cutout comes out a few percent larger than the tool** -- the photo was taken too close. The paper sits on the table, but a thick tool's outline sits above it, nearer the camera, so it projects oversized. Re-shoot from 50-60cm or more.
- **Cutout comes out larger than the tool** -- the tool's outline sits above the paper, nearer the camera, so it traces oversized. Measure the tool and type that dimension into the Size fields in the [tool editor](tool-editor.md#transforms). See [Tall or thick objects](#tall-or-thick-objects).
39 changes: 39 additions & 0 deletions frontend/e2e-accuracy/physical-size.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,42 @@ test('Detail preserves a manual size correction through saved STL export', async
expect(measurement.dimensions_mm[0]).toBeCloseTo(30.2, 1)
expect(measurement.dimensions_mm[1]).toBeCloseTo(72.2, 1)
})

test('typed outline width scales the saved tool and its STL pocket', async ({ page }, testInfo) => {
await createScannedBin(page)
const binId = page.url().split('/bins/')[1]
const bin = await (await page.request.get(`/api/bins/${binId}`)).json()
const toolId = bin.placed_tools[0].tool_id
const span = (outline: { x: number; y: number }[], axis: 'x' | 'y') =>
Math.max(...outline.map(p => p[axis])) - Math.min(...outline.map(p => p[axis]))
const traced = await (await page.request.get(`/api/tools/${toolId}`)).json()
expect(Math.abs(span(traced.points, 'x') - 80)).toBeLessThan(1)
expect(Math.abs(span(traced.points, 'y') - 30)).toBeLessThan(1)

await page.goto(`/tools/${toolId}`)
// autosave ignores changes made in its first 100 ms, so let the page settle
await page.waitForLoadState('networkidle')
const width = page.getByTitle(/^Outline width \(mm\)/)
await expect(width).toBeVisible()
// the editor can also save on load; wait for the save carrying the resized outline
const saved = page.waitForResponse(response =>
response.url().endsWith(`/api/tools/${toolId}`)
&& response.request().method() === 'PUT'
&& Math.abs(span(response.request().postDataJSON().points, 'x') - 64) < 1e-6)
await width.fill('64')
await width.press('Enter')
await expect(page.getByText(/ · 64\.0×\d+\.\d mm$/)).toBeVisible()
expect((await saved).ok()).toBeTruthy()
const resized = await (await page.request.get(`/api/tools/${toolId}`)).json()
const factor = 64 / span(traced.points, 'x')
expect(span(resized.points, 'x')).toBeCloseTo(64, 6)
expect(span(resized.points, 'y')).toBeCloseTo(span(traced.points, 'y') * factor, 6)
// the photo underlay is saved at the same scale
expect(resized.source_image_transform[0]).toBeCloseTo(traced.source_image_transform[0] * factor, 6)

await page.goto(`/bins/${binId}`)
// the pocket is the resized outline, about 64 x 24 mm, plus 1 mm clearance a side
const measurement = await downloadPocket(page, testInfo, 'resized-tool')
expect(Math.abs(measurement.dimensions_mm[0] - (span(resized.points, 'y') + 2))).toBeLessThan(1)
expect(Math.abs(measurement.dimensions_mm[1] - 66)).toBeLessThan(1)
})
57 changes: 57 additions & 0 deletions frontend/src/components/NumericInput.behaviour.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render } from '@testing-library/react'
import { NumericInput } from './NumericInput'

describe('NumericInput commits', () => {
afterEach(cleanup)

function setup(commitOnBlur?: boolean) {
const >
const { container } = render(
<NumericInput value={5} min={1} max={50} commitOnBlur={commitOnBlur} />,
)
const input = container.querySelector('input') as HTMLInputElement
input.focus()
fireEvent.change(input, { target: { value: '7' } })
return { input, onChange }
}

it('commits once on Enter, not again on the blur that follows', () => {
const { input, onChange } = setup()
fireEvent.keyDown(input, { key: 'Enter' })
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenCalledWith(7)
expect(document.activeElement).not.toBe(input)
})

it('discards typed text on Escape', () => {
const { input, onChange } = setup()
fireEvent.keyDown(input, { key: 'Escape' })
expect(onChange).not.toHaveBeenCalled()
expect(input.value).toBe('5')
})

it('commits on blur by default', () => {
const { input, onChange } = setup()
fireEvent.blur(input)
expect(onChange).toHaveBeenCalledWith(7)
})

it('commits again after an Enter when refocused and edited', () => {
const { input, onChange } = setup()
fireEvent.keyDown(input, { key: 'Enter' })
input.focus()
fireEvent.change(input, { target: { value: '9' } })
fireEvent.blur(input)
expect(onChange).toHaveBeenLastCalledWith(9)
expect(onChange).toHaveBeenCalledTimes(2)
})

it('discards typed text on blur when only Enter may commit', () => {
const { input, onChange } = setup(false)
fireEvent.blur(input)
expect(onChange).not.toHaveBeenCalled()
expect(input.value).toBe('5')
})
})
19 changes: 17 additions & 2 deletions frontend/src/components/NumericInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ interface Props {
className?: string
disabled?: boolean
title?: string
// false discards typed text on blur, so only Enter commits
commitOnBlur?: boolean
}

export function clampNumericValue(raw: string, min: number, max: number, step: number, fallback: number): number {
Expand All @@ -22,9 +24,12 @@ export function clampNumericValue(raw: string, min: number, max: number, step: n
}

// defers min/max clamping to blur or Enter -- lets users type freely
export function NumericInput({ value, min, max, step = 1, onChange, className, disabled, title }: Props) {
export function NumericInput({ value, min, max, step = 1, onChange, className, disabled, title, commitOnBlur = true }: Props) {
const [text, setText] = useState(String(value))
const committedRef = useRef(value)
// Enter and Escape settle the field themselves. the blur they cause must
// not commit the text a second time, or commit what Escape discarded
const settledRef = useRef(false)

useEffect(() => {
// sync display when value changes externally (e.g. slider drag)
Expand Down Expand Up @@ -56,14 +61,24 @@ export function NumericInput({ value, min, max, step = 1, onChange, className, d
disabled={disabled}
title={title}
=> setText(e.target.value)}
=> commit(e.target.value)}
=> { settledRef.current = false }}
=> {
if (settledRef.current) {
settledRef.current = false
return
}
if (commitOnBlur) commit(e.target.value)
else setText(String(committedRef.current))
}}
=> {
if (e.key === 'Enter') {
commit(e.currentTarget.value)
settledRef.current = true
e.currentTarget.blur()
}
if (e.key === 'Escape') {
setText(String(committedRef.current))
settledRef.current = true
e.currentTarget.blur()
}
}}
Expand Down
Loading
Loading
0