8000 Allow blank bin generation by noobydp · Pull Request #163 · tracefinity/tracefinity · GitHub
[go: up one dir, main page]

Skip to content
Draft
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: 0 additions & 2 deletions backend/app/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2200,8 +2200,6 @@ def _generate_bin_stl(bin_id: str, user_id: str, user_tools: ToolStore, user_bin
bin_data = user_bins.get(bin_id)
if not bin_data:
raise HTTPException(status_code=404, detail="bin not found")
if not bin_data.placed_tools:
raise HTTPException(status_code=400, detail="bin has no tools placed")

bc = bin_data.bin_config

Expand Down
37 changes: 32 additions & 5 deletions backend/app/services/stl_generator_manifold.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from app.constants import GF_GRID

# Bump when geometry changes so saved previews and exports regenerate.
STL_GEOMETRY_VERSION = 2
STL_GEOMETRY_VERSION = 3

GF_HALF_GRID = GF_GRID / 2 # 21mm
GF_HEIGHT_UNIT = 7.0
Expand Down Expand Up @@ -550,6 +550,27 @@ def _resolve_pocket_depth(override: float | None, config, max_depth: float) -> f
return min(max_depth, max(5, base))


def _make_blank_bin_cutout(config: GenerateRequest, wall_top_z: float, max_depth: float):
"""Full-bin interior pocket for bins with no placed tools."""
import manifold3d as mf

outer_w = config.grid_x * GF_GRID - 0.5
outer_h = config.grid_y * GF_GRID - 0.5
wall = bin_interior_inset(config.wall_thickness, config.stacking_lip)
inner_w = outer_w - 2 * wall
inner_h = outer_h - 2 * wall
if inner_w <= 0 or inner_h <= 0:
return None, 0

pocket_depth = _resolve_pocket_depth(None, config, max_depth)
inner_r = min(GF_CORNER_R, inner_w / 2, inner_h / 2)
cutter = mf.Manifold.extrude(
_cs(_rounded_rect_pts(inner_w, inner_h, inner_r)),
pocket_depth + 0.01,
).translate((0.0, 0.0, wall_top_z - pocket_depth))
return cutter, pocket_depth


def _filleted_rect_radius(width: float, pocket_depth: float) -> float:
"""Bottom fillet radius for the filleted-rectangle cutter profile."""
return max(0.0, min(width / 3.0, pocket_depth / 2.0))
Expand Down Expand Up @@ -1389,11 +1410,11 @@ def generate_bin(
cutters.append(_make_magnet_holes(config))

pocket_depth = 5
floor_z = GF_BASE_HEIGHT
# Pockets start at the wall top; the lip and raised rim sit above it.
# Retain the base and 2mm of material beneath every pocket.
max_depth = wall_top_z - floor_z - 2
if polygons:
floor_z = GF_BASE_HEIGHT
# Pockets start at the wall top; the lip and raised rim sit above it.
# Retain the base and 2mm of material beneath every pocket.
max_depth = wall_top_z - floor_z - 2
# Default pocket_depth still tracks the global cutout_depth; per-cutout
# overrides are resolved inside the cutter functions.
pocket_depth = _resolve_pocket_depth(None, config, max_depth)
Expand All @@ -1420,6 +1441,12 @@ def generate_bin(
if fh_chamfers:
cutters.append(fh_chamfers)
logger.info("chamfer cutouts: %.2fs", time.monotonic() - t1)
else:
t1 = time.monotonic()
blank_cutout, pocket_depth = _make_blank_bin_cutout(config, wall_top_z, max_depth)
if blank_cutout:
cutters.append(blank_cutout)
logger.info("blank bin cutout: %.2fs", time.monotonic() - t1)

# text labels (recessed cutters + embossed body additions).
text_body = None
Expand Down
111 changes: 111 additions & 0 deletions backend/tests/test_blank_bin_generation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
from pathlib import Path

import pytest

from app.models.schemas import GenerateRequest
from app.services.stl_generator_manifold import (
GF_BASE_HEIGHT,
GF_GRID,
GF_HEIGHT_UNIT,
LIP_D0,
LIP_D2,
ManifoldSTLGenerator,
_make_blank_bin_cutout,
)


def test_generate_blank_bin_writes_full_width_cutout(tmp_path: Path):
output_path = tmp_path / "blank_bin.stl"
config = GenerateRequest(
grid_x=2,
grid_y=1,
height_units=3,
magnets=False,
stacking_lip=True,
bed_size=0,
)

body, text_body = ManifoldSTLGenerator().generate_bin([], config, str(output_path))

assert text_body is None
assert output_path.exists()
assert output_path.stat().st_size > 0
assert body.bounding_box()[5] > 0


def test_blank_bin_cutout_observes_cutout_depth():
shallow = GenerateRequest(
grid_x=2,
grid_y=1,
height_units=4,
magnets=False,
stacking_lip=False,
cutout_depth=8,
)
deep = shallow.model_copy(update={"cutout_depth": 14})
wall_top_z = shallow.height_units * GF_HEIGHT_UNIT
max_depth = wall_top_z - GF_BASE_HEIGHT - 2

_, shallow_depth = _make_blank_bin_cutout(shallow, wall_top_z, max_depth)
_, deep_depth = _make_blank_bin_cutout(deep, wall_top_z, max_depth)

assert shallow_depth == 8
assert deep_depth == 14


@pytest.mark.parametrize(("stacking_lip", "wall_thickness", "expected_wall"), [
(False, 1.6, 1.6),
(False, 5, 5),
(True, 1.6, LIP_D0 + LIP_D2),
(True, 5, 5),
])
def test_blank_bin_cutout_respects_wall_and_lip(stacking_lip, wall_thickness, expected_wall):
config = GenerateRequest(
grid_x=2,
grid_y=1,
height_units=4,
magnets=False,
stacking_lip=stacking_lip,
wall_thickness=wall_thickness,
cutout_depth=8,
)
wall_top_z = config.height_units * GF_HEIGHT_UNIT
max_depth = wall_top_z - GF_BASE_HEIGHT - 2

cutter, _ = _make_blank_bin_cutout(config, wall_top_z, max_depth)
min_x, min_y, _, max_x, max_y, _ = cutter.bounding_box()

assert max_x - min_x == pytest.approx(config.grid_x * GF_GRID - 0.5 - 2 * expected_wall)
assert max_y - min_y == pytest.approx(config.grid_y * GF_GRID - 0.5 - 2 * expected_wall)


@pytest.mark.parametrize("stacking_lip", [False, True])
@pytest.mark.parametrize("height_units", [1, 3])
def test_blank_bin_maximum_depth_preserves_floor(tmp_path, stacking_lip, height_units):
config = GenerateRequest(
grid_x=2, grid_y=1, height_units=height_units, magnets=False,
stacking_lip=stacking_lip, cutout_depth=100, bed_size=0,
)
body, _ = ManifoldSTLGenerator().generate_bin([], config, str(tmp_path / "floor.stl"))
floor_z = GF_BASE_HEIGHT + 2
# An actual cross-section below the floor is solid; above it is a cavity.
assert len(body.slice(floor_z - 0.05).to_polygons()) == 1
assert len(body.slice(floor_z + 0.05).to_polygons()) == 2


def test_deeper_blank_bin_cutout_removes_more_material(tmp_path: Path):
config = GenerateRequest(
grid_x=2,
grid_y=1,
height_units=4,
magnets=False,
stacking_lip=False,
cutout_depth=8,
bed_size=0,
)
generator = ManifoldSTLGenerator()

shallow_body, _ = generator.generate_bin([], config, str(tmp_path / "shallow.stl"))
deep_body, _ = generator.generate_bin([], config.model_copy(update={"cutout_depth": 14}), str(tmp_path / "deep.stl"))

assert shallow_body.volume() > deep_body.volume()
13 changes: 10 additions & 3 deletions backend/tests/test_half_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,16 @@ def test_half_grid_base_more_cells_than_standard(tmp_path: Path):
# both should produce valid geometry
assert s_body.volume() > 0
assert h_body.volume() > 0
# volumes should be very close (same outer dimensions, just different base pattern)
ratio = h_body.volume() / s_body.volume()
8BD0 assert 0.95 < ratio < 1.05
# Blank cavities change the volume ratio. Both variants retain the same
# outer envelope and must still have distinct base-pad patterns.
s_bb = s_body.bounding_box()
h_bb = h_body.bounding_box()
assert h_bb[3] - h_bb[0] == pytest.approx(s_bb[3] - s_bb[0])
assert h_bb[4] - h_bb[1] == pytest.approx(s_bb[4] - s_bb[1])
assert h_bb[5] - h_bb[2] == pytest.approx(s_bb[5] - s_bb[2])
# Below the shared floor each pad must remain a distinct base cell.
assert len(s_body.slice(0.4).to_polygons()) == 4
assert len(h_body.slice(0.4).to_polygons()) == 16


def test_half_unit_bin_correct_outer_dimensions(tmp_path: Path):
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/app/bins/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ export default function BinPage() {
}), [placedTools, config, textLabels, smoothedToolIds, smoothLevels])

const doGenerate = useCallback(async () => {
if (placedTools.length === 0 || gridLimitError) return
if (gridLimitError) return

const key = generationKey
if (key === lastGenerateRef.current) return
Expand Down Expand Up @@ -223,7 +223,7 @@ export default function BinPage() {
abortRef.current = null
}
}
}, [binId, placedTools.length, generationKey, gridLimitError, flushSave])
}, [binId, generationKey, gridLimitError, flushSave])

useEffect(() => {
doGenerateRef.current = doGenerate
Expand Down Expand Up @@ -611,8 +611,10 @@ export default function BinPage() {
<div className="flex items-center gap-2 text-[11px] text-text-muted">
{generating && <Loader2 className="w-3 h-3 animate-spin text-accent" />}
<span>{config.grid_x}x{config.grid_y} Grid ({binW} x {binH} mm)</span>
{placedTools.length > 0 && (
{placedTools.length > 0 ? (
<span>· {placedTools.length} tool{placedTools.length !== 1 ? 's' : ''} placed</span>
) : (
<span>· blank bin</span>
)}
</div>
</div>
Expand Down Expand Up @@ -648,8 +650,6 @@ export default function BinPage() {
</>
) : gridLimitError ? (
<span className="max-w-xs px-4 text-center">Layout is too large to generate. Your edits are still saved.</span>
) : placedTools.length === 0 ? (
<span>Add tools to see preview</span>
) : (
<span>Preview will appear here</span>
)}
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/app/projects/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@

useEffect(() => {
loadData()
}, [projectId])

Check warning on line 102 in frontend/src/app/projects/[id]/page.tsx

View workflow job for this annotation

GitHub Actions / frontend

React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array

async function loadData() {
setLoading(true)
Expand Down Expand Up @@ -299,7 +299,7 @@
}

async function handleCreateBin() {
if (!project || selectedBinToolIds.size === 0) return
if (!project) return
setCreatingBin(true)
setError(null)
try {
Expand Down Expand Up @@ -457,11 +457,11 @@
</select>
<button
>
disabled={creatingBin || selectedBinToolIds.size === 0}
disabled={creatingBin}
className="btn-primary px-3 py-2 text-xs flex items-center gap-1.5"
>
{creatingBin ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Package className="w-3.5 h-3.5" />}
Create bin{selectedBinToolIds.size > 0 ? ` (${selectedBinToolIds.size})` : ''}
{selectedBinToolIds.size > 0 ? `Create bin (${selectedBinToolIds.size})` : 'Create blank bin'}
</button>
</div>
</div>
Expand Down
Loading
0