Spaces:
Sleeping
Drop raster lines no head prints from the shared motion; {preset} markers
Browse filesInfill motion optimization:
- Lines that NO shape dispenses on are dropped from the motion instead
of swept valve-off: each grid line survives if ANY shape's infill
pattern prints it, and every shape receives the same combined
fraction list, so the shared motion stays identical across heads.
All shapes at 50% halve the path (measured 49.6%); mixed 50/75/50
drops only lines all three skip (72.7%); any shape at 100% keeps
every line. Solo shapes bound their own motion the same way
- Circle spiral: rings nobody prints drop out; perimeter walls always
stay (they always dispense). Rectangular spiral keeps its full
continuous walk - removing an interior loop would break the spiral
into disconnected rectangles
- Engine default is safe: shared-motion callers that do not pass
motion_infill_fractions get unrestricted motion, so heads can never
desynchronize by accident (the app always passes the list)
Aerotech host compatibility:
- The two pressure-setup header lines now carry the {preset} marker
({preset}serialPort3.write(eval(setpress(25)))), matching the lab's
newer TCode host format: presets execute at the controller's START
signal instead of with the initial valve toggles. Files without the
marker keep working; our parser ignores it
- _format_duration extracted from the viz time estimate (refactor)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Files changed (5)
- README.md+1-1
- app.py+22-7
- tests/test_vector_gcode.py+87-19
- vector_gcode.py+15-2
- vector_toolpath.py+70-7
53 unmodified lines5455565758596053 unmodified lines- Splits one sliced shape's geometry into an editable row/column grid for multi-nozzle printing of one large shape- Converts sliced layers into G-code files with pressure, valve, nozzle, port, and infill % settings per shape from the Shape Settings table- **Pressure is a port property** (one pressure regulator per serial port): shapes sharing a Port always share one pressure — editing one shape's pressure updates every shape on that port, moving a shape onto a port adopts that port's pressure, and newly added shapes join at their port's existing pressure- **Infill %** per shape skips dispensing on evenly-distributed raster lines (rings/revolutions for spiral patterns) — at 50% every other line prints — while the motion path stays exactly the same, so parallel shapes with different infill still share one print path- Appends a shape outline contour after each enabled shape layer by tracing that layer's polygon boundary- Offers a choice of raster pattern for G-code generation; all shapes always share one combined reference outline for motion (one nozzle path; each dispenses only its own geometry), and every move is emitted as `G1` at one constant speed (no `G0` rapid travel)- Slicing is automatic: **Generate G-Code** slices every shape (fresh or stale) before writing G-code, and **Split Selected Shape into Grid Pieces** slices before splitting — "upload, then Generate G-Code" works in one click with no separate slice step53 unmodified lines5455565758596053 unmodified lines- Splits one sliced shape's geometry into an editable row/column grid for multi-nozzle printing of one large shape- Converts sliced layers into G-code files with pressure, valve, nozzle, port, and infill % settings per shape from the Shape Settings table- **Pressure is a port property** (one pressure regulator per serial port): shapes sharing a Port always share one pressure — editing one shape's pressure updates every shape on that port, moving a shape onto a port adopts that port's pressure, and newly added shapes join at their port's existing pressure- **Infill %** per shape skips dispensing on evenly-distributed raster lines (rings for the circle spiral) — at 50% every other line prints. Parallel shapes with different infill still share one print path, and lines that **no** shape dispenses on are dropped from the motion entirely instead of being swept valve-off (every shape at 50% roughly halves the print path; with mixed infills a line survives if any shape prints it). The rectangular spiral keeps its full continuous walk; circle-spiral perimeter walls always stay- Appends a shape outline contour after each enabled shape layer by tracing that layer's polygon boundary- Offers a choice of raster pattern for G-code generation; all shapes always share one combined reference outline for motion (one nozzle path; each dispenses only its own geometry), and every move is emitted as `G1` at one constant speed (no `G0` rapid travel)- Slicing is automatic: **Generate G-Code** slices every shape (fresh or stale) before writing G-code, and **Split Selected Shape into Grid Pieces** slices before splitting — "upload, then Generate G-Code" works in one click with no separate slice step
3940 unmodified lines39413942394339443945394635 unmodified lines39823983398439853986398772 unmodified lines4060406140624063406440652 unmodified lines40684069407040714072407340744075407640774078407940803940 unmodified linesif record.get("layer_stack") is not Noneand getattr(record["layer_stack"], "scan_frame", None) is None]# Lead-in is driven entirely by the per-shape "Lead In" column: the# purge motion exists whenever any shape dispenses it (all heads must# share the motion), and each shape's own flag gates its valve.35 unmodified linescontour_sources=contour_sources,active_contour_owner=int(record.get("idx", 0)),infill=_coerce_float(record.get("infill", 100.0), 100.0) / 100.0,lead_in_enabled=bool(lead_in_enabled),lead_in_length=float(lead_in_length),lead_in_clearance=effective_lead_in_clearance,72 unmodified linesreturn totaldef _print_time_estimate(length_mm: float, nozzle_speed: Any) -> str | None:"""Human-readable print duration at a constant nozzle speed, or None.2 unmodified linesspeed = _coerce_float(nozzle_speed, 0.0)if speed <= 0.0 or length_mm <= 0.0:return Nonehours, remainder = divmod(int(round(length_mm / speed)), 3600)minutes, seconds = divmod(remainder, 60)if hours:return f"{hours} h {minutes:02d} min"if minutes:return f"{minutes} min {seconds:02d} s"return f"{seconds} s"def render_dynamic_nozzle_spacing(3940 unmodified lines394139423943394439453946394739483949395039513952395339543955395635 unmodified lines399239933994399539963997399872 unmodified lines40714072407340744075407640774078407940804081408240834084408540862 unmodified lines40894090409140924093409440953940 unmodified linesif record.get("layer_stack") is not Noneand getattr(record["layer_stack"], "scan_frame", None) is None]# Infill motion optimization: raster lines/rings that NO head dispenses# on are dropped from the shared motion (e.g. every shape at 50% halves# the path). Same list for every shape, so the shared motion stays in# sync across heads.motion_infill_fractions = [_coerce_float(record.get("infill", 100.0), 100.0) / 100.0for record in recordsif record.get("layer_stack") is not Noneand getattr(record["layer_stack"], "layers", None)]# Lead-in is driven entirely by the per-shape "Lead In" column: the# purge motion exists whenever any shape dispenses it (all heads must# share the motion), and each shape's own flag gates its valve.35 unmodified linescontour_sources=contour_sources,active_contour_owner=int(record.get("idx", 0)),infill=_coerce_float(record.get("infill", 100.0), 100.0) / 100.0,motion_infill_fractions=motion_infill_fractions,lead_in_enabled=bool(lead_in_enabled),lead_in_length=float(lead_in_length),lead_in_clearance=effective_lead_in_clearance,72 unmodified linesreturn totaldef _format_duration(total_seconds: float) -> str:hours, remainder = divmod(int(round(total_seconds)), 3600)minutes, seconds = divmod(remainder, 60)if hours:return f"{hours} h {minutes:02d} min"if minutes:return f"{minutes} min {seconds:02d} s"return f"{seconds} s"def _print_time_estimate(length_mm: float, nozzle_speed: Any) -> str | None:"""Human-readable print duration at a constant nozzle speed, or None.2 unmodified linesspeed = _coerce_float(nozzle_speed, 0.0)if speed <= 0.0 or length_mm <= 0.0:return Nonereturn _format_duration(length_mm / speed)def render_dynamic_nozzle_spacing(
213 unmodified lines214215216217218219220221641 unmodified lines86386486586686786886914 unmodified lines88488588688788888989089189289389489589689789889990018 unmodified lines91992092192292392492592692792892993012 unmodified lines943944945946947948949950951952953954955956957213 unmodified lines# (the toolpath's world anchor is returned via origin_sink instead).assert not any("PathOrigin" in line for line in lines)assert lines[1] == "{aux_command}WAGO_ValveCommands(7, 0)"assert lines[2] == "serialPort3.write(eval(setpress(25)))"assert lines[3] == "serialPort3.write(eval(togglepress()))"assert lines[4].startswith("{aux_command}WAGO_ValveCommands(")assert lines[5].startswith("{aux_command}WAGO_ValveCommands(")641 unmodified lines)def test_half_infill_skips_alternate_lines_but_keeps_the_same_path(tmp_path) -> None:layer = box(0.0, 0.0, 4.0, 4.0)stack = _stack(layer, layer)14 unmodified linesfull = _generate(1.0, "full")half = _generate(0.5, "half")# Identical motion: same final position and same total traversed length.assert full[-1]["end"] == half[-1]["end"]assert abs(_total_length(full) - _total_length(half)) < 1e-6# Half the lines dispense: 2 of the 4 sweeps per layer print.assert abs(_print_length(half) - _print_length(full) / 2) < 1e-6# The printing sweeps sit on alternating scanlines (one fil apart x2).half_print_rows = sorted({round(m["start"][1], 6) for m in half if m["color"] == 255 and m["start"][2] == 0.0})assert len(half_print_rows) == 2assert abs((half_print_rows[1] - half_print_rows[0]) - 2.0) < 1e-9def test_infill_selection_is_shared_across_reference_motion(tmp_path) -> None:18 unmodified linessparse = _generate(small, 0.5, "sparse")dense = _generate(big, 1.0, "dense")# Different infill per shape, one shared motion path.assert sparse[-1]["end"] == dense[-1]["end"]assert abs(_total_length(sparse) - _total_length(dense)) < 1e-6assert 0 < _print_length(sparse) < _print_length(dense)def test_spiral_infill_skips_rings_and_keeps_the_path(tmp_path) -> None:layer = box(0.0, 0.0, 6.0, 6.0)stack = _stack(layer)12 unmodified lines)return _moves_with_colors(path.read_text())for pattern in (RASTER_PATTERN_RECTANGULAR_SPIRAL, RASTER_PATTERN_CIRCLE_SPIRAL):full = _generate(pattern, 1.0, f"{pattern}-full".replace(" ", "_"))half = _generate(pattern, 0.5, f"{pattern}-half".replace(" ", "_"))# Identical path within the writer's micron-level delta rounding# (segment split points differ, so the rounding accumulates# differently by up to ~1 um over tens of thousands of moves).assert math.dist(full[-1]["end"], half[-1]["end"]) < 1e-4, patternassert abs(_total_length(full) - _total_length(half)) < 1e-3, patternassert 0 < _print_length(half) < _print_length(full), patterndef test_layer_contour_loops_follow_polygon_rings() -> None:213 unmodified lines214215216217218219220221222641 unmodified lines86486586686786886987014 unmodified lines88588688788888989089189289389489589689789889990090190218 unmodified lines92192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598612 unmodified lines99910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025213 unmodified lines# (the toolpath's world anchor is returned via origin_sink instead).assert not any("PathOrigin" in line for line in lines)assert lines[1] == "{aux_command}WAGO_ValveCommands(7, 0)"# {preset} marks pressure setup for the Aerotech host runtime.assert lines[2] == "{preset}serialPort3.write(eval(setpress(25)))"assert lines[3] == "{preset}serialPort3.write(eval(togglepress()))"assert lines[4].startswith("{aux_command}WAGO_ValveCommands(")assert lines[5].startswith("{aux_command}WAGO_ValveCommands(")641 unmodified lines)def test_half_infill_skips_alternate_lines_and_their_motion(tmp_path) -> None:layer = box(0.0, 0.0, 4.0, 4.0)stack = _stack(layer, layer)14 unmodified linesfull = _generate(1.0, "full")half = _generate(0.5, "half")# A solo shape's motion skips the lines it never prints: the path# shrinks instead of sweeping dead lines valve-off.assert _total_length(half) < _total_length(full)# Half the lines dispense: 2 of the 4 sweeps per layer print, and the# sweeps only visit those 2 scanlines (one fil apart x2).assert abs(_print_length(half) - _print_length(full) / 2) < 1e-6half_rows = sorted({round(m["start"][1], 6) for m in half if m["start"][2] == 0.0 and m["start"][1] == m["end"][1]})half_print_rows = sorted({round(m["start"][1], 6) for m in half if m["color"] == 255 and m["start"][2] == 0.0})assert len(half_print_rows) == 2assert abs((half_print_rows[1] - half_print_rows[0]) - 2.0) < 1e-9assert set(half_rows) == set(half_print_rows)def test_infill_selection_is_shared_across_reference_motion(tmp_path) -> None:18 unmodified linessparse = _generate(small, 0.5, "sparse")dense = _generate(big, 1.0, "dense")# Different infill per shape, one shared motion path (without a# motion_infill_fractions list, shared motion is never restricted).assert sparse[-1]["end"] == dense[-1]["end"]assert abs(_total_length(sparse) - _total_length(dense)) < 1e-6assert 0 < _print_length(sparse) < _print_length(dense)def test_shared_motion_skips_lines_no_head_prints(tmp_path) -> None:layer = box(0.0, 0.0, 4.0, 4.0)first = _stack(layer, name="first")second = _stack(layer, name="second")reference = build_reference_stack([first, second])def _generate(stack: LayerStack, infill: float, fractions, label: str):path = generate_vector_gcode(stack,shape_name=label,pressure=25,valve=7,port=3,fil_width=1.0,motion=reference,infill=infill,motion_infill_fractions=fractions,output_dir=tmp_path / label,)return _moves_with_colors(path.read_text())# Both shapes at 50%: the union skips every other line, so the shared# motion halves — and stays IDENTICAL across heads.half_a = _generate(first, 0.5, [0.5, 0.5], "half_a")half_b = _generate(second, 0.5, [0.5, 0.5], "half_b")assert [(m["start"], m["end"]) for m in half_a] == [(m["start"], m["end"]) for m in half_b]full_a = _generate(first, 1.0, [1.0, 1.0], "full_a")assert _total_length(half_a) < _total_length(full_a)rows_half = {round(m["start"][1], 6) for m in half_a if m["start"][1] == m["end"][1]}rows_full = {round(m["start"][1], 6) for m in full_a if m["start"][1] == m["end"][1]}assert len(rows_half) == 2 and len(rows_full) == 4# Mixed 50% + 75%: a line survives if EITHER pattern prints it (only# lines both skip drop out). 50% keeps odd k, 75% skips k=0 (mod 4):# of the 4 grid lines, only k=0 drops.# (Move SPLIT points differ per head — each splits at its own valve# transitions — so compare the path itself: length, end, and rows.)mixed_a = _generate(first, 0.5, [0.5, 0.75], "mixed_a")mixed_b = _generate(second, 0.75, [0.5, 0.75], "mixed_b")assert abs(_total_length(mixed_a) - _total_length(mixed_b)) < 1e-6assert mixed_a[-1]["end"] == mixed_b[-1]["end"]rows_mixed = {round(m["start"][1], 6) for m in mixed_a if m["start"][1] == m["end"][1]}assert rows_mixed == {round(m["start"][1], 6) for m in mixed_b if m["start"][1] == m["end"][1]}assert len(rows_mixed) == 3# Any head at 100% keeps every line in the motion.dense = _generate(first, 0.5, [0.5, 1.0], "dense_pair")rows_dense = {round(m["start"][1], 6) for m in dense if m["start"][1] == m["end"][1]}assert len(rows_dense) == 4def test_spiral_infill_skips_rings_and_keeps_the_path(tmp_path) -> None:layer = box(0.0, 0.0, 6.0, 6.0)stack = _stack(layer)12 unmodified lines)return _moves_with_colors(path.read_text())# Rectangular spiral: the continuous walk is kept (a skipped loop would# break the spiral into disconnected rectangles), so the motion stays# identical within the writer's micron-level delta rounding.full = _generate(RASTER_PATTERN_RECTANGULAR_SPIRAL, 1.0, "rect-full")half = _generate(RASTER_PATTERN_RECTANGULAR_SPIRAL, 0.5, "rect-half")assert math.dist(full[-1]["end"], half[-1]["end"]) < 1e-4assert abs(_total_length(full) - _total_length(half)) < 1e-3assert 0 < _print_length(half) < _print_length(full)# Circle spiral: rings a solo shape never prints drop out of the motion# (the perimeter wall always stays and always dispenses).full = _generate(RASTER_PATTERN_CIRCLE_SPIRAL, 1.0, "circle-full")half = _generate(RASTER_PATTERN_CIRCLE_SPIRAL, 0.5, "circle-half")assert _total_length(half) < _total_length(full)assert 0 < _print_length(half) < _print_length(full)wall_radius = max(math.hypot((m["start"][0] + m["end"][0]) / 2 - 3.0, (m["start"][1] + m["end"][1]) / 2 - 3.0)for m in halfif m["color"] == 255)assert wall_radius > 2.0 # the outer wall is still printeddef test_layer_contour_loops_follow_polygon_rings() -> None:
74 unmodified lines757677787980818283848586878889105 unmodified lines19519619719819920019 unmodified lines22022122222322422589 unmodified lines31531631731831932074 unmodified linesdef _setpress_cmd(port: str, pressure: float, start: bool) -> str:if start:return f"\n\r{port}.write(eval(setpress({pressure:g})))"insert = ""return f"\n\r{insert}{port}.write({_setpress(pressure)})"def _toggle_cmd(port: str, start: bool) -> str:if start:return f"\n\r{port}.write(eval(togglepress()))"insert = ""return f"\n\r{insert}{port}.write({_togglepress()})"105 unmodified linescontour_sources: list[ContourSource] | None = None,active_contour_owner: int | None = None,infill: float = 1.0,increase_pressure_per_layer: float = 0.1,pressure_ramp_enabled: bool = True,all_g1: bool = False,19 unmodified linesthe Circle Spiral under shared motion: every shape's own wall radiusjoins the ONE shared ring set, so each shape keeps a smooth completeouter circle. Pass the SAME list to every shape's generation call."""if shape is None or not shape.layers:raise ValueError("The shape has no sliced layers to generate G-code from.")89 unmodified linesinfill_fraction=max(0.0, min(1.0, float(infill))),extra_wall_radii=extra_wall_radii,ring_center=ring_center,)# World anchor: the toolpath origin expressed in the shape's own frame.74 unmodified lines7576777879808182838485868788899091105 unmodified lines19719819920020120220319 unmodified lines22322422522622722822923023123223389 unmodified lines32332432532632732832933033133233374 unmodified linesdef _setpress_cmd(port: str, pressure: float, start: bool) -> str:# {preset} marks pressure setup for the Aerotech host runtime: presets# execute at the controller's START signal, before the initial toggles.if start:return f"\n\r{{preset}}{port}.write(eval(setpress({pressure:g})))"insert = ""return f"\n\r{insert}{port}.write({_setpress(pressure)})"def _toggle_cmd(port: str, start: bool) -> str:if start:return f"\n\r{{preset}}{port}.write(eval(togglepress()))"insert = ""return f"\n\r{insert}{port}.write({_togglepress()})"105 unmodified linescontour_sources: list[ContourSource] | None = None,active_contour_owner: int | None = None,infill: float = 1.0,motion_infill_fractions: list[float] | None = None,increase_pressure_per_layer: float = 0.1,pressure_ramp_enabled: bool = True,all_g1: bool = False,19 unmodified linesthe Circle Spiral under shared motion: every shape's own wall radiusjoins the ONE shared ring set, so each shape keeps a smooth completeouter circle. Pass the SAME list to every shape's generation call.`motion_infill_fractions` lists EVERY shape's infill fraction (again thesame list for every call): raster lines/rings that no head dispenses onare dropped from the shared motion instead of swept valve-off. Whenomitted, this shape's own fraction bounds its motion."""if shape is None or not shape.layers:raise ValueError("The shape has no sliced layers to generate G-code from.")89 unmodified linesinfill_fraction=max(0.0, min(1.0, float(infill))),extra_wall_radii=extra_wall_radii,ring_center=ring_center,motion_infill_fractions=([max(0.0, min(1.0, float(fraction))) for fraction in motion_infill_fractions]if motion_infill_fractions is not Noneelse None),)# World anchor: the toolpath origin expressed in the shape's own frame.
327 unmodified lines32832933033133233352 unmodified lines3863873883893903913 unmodified lines39539639739839940040126 unmodified lines4284294304314324331 unmodified line43543643743843944044144244356 unmodified lines50050150250350450550650750850910 unmodified lines52052152252352452519 unmodified lines54554654754854955037 unmodified lines588589590591592593746 unmodified lines1340134113421343134413452 unmodified lines134813491350135113521353135413551 unmodified line13571358135913601361136250 unmodified lines14131414141514161417141867 unmodified lines14861487148814891490149110 unmodified lines150215031504150515061507327 unmodified linesreturn keepdef _scan_anchor(lo: float, hi: float, fil_width: float) -> float:"""First scanline position of the centred grid spanning [lo, hi].52 unmodified linesstart_forward: bool = True,scan_anchor: float | None = None,infill_keep=None,) -> list[Seg]:"""Snake raster of `motion`, dispensing only inside `valve`.3 unmodified linesvalve-settle travel buffer before and after. `scan_anchor` pins thescanlines to a global grid (see `_scan_coords`). `infill_keep(k)` gatesdispensing per grid line for partial infill: skipped lines are stillswept, just with the valve closed, so the motion never changes."""if motion is None or motion.is_empty:return []26 unmodified linessegments: list[Seg] = []sweep_number = 0for coord in coords:probe = min(max(coord, probe_lo), probe_hi)motion_runs = _chord_runs(motion, axis, probe)if not motion_runs:1 unmodified linesweep_lo = motion_runs[0][0]sweep_hi = motion_runs[-1][1]if infill_keep is not None and not infill_keep(int(round((coord - index_base) / fil_width))):valve_runs: list[tuple[float, float]] = []else:valve_runs = []56 unmodified linesprefer_default: bool = False,scan_anchor: float | None = None,infill_keep=None,) -> list[Seg]:"""Pick the raster orientation whose start is nearest the current position."""default_segments = _axis_raster_segments(motion, valve, fil_width, axis, scan_anchor=scan_anchor, infill_keep=infill_keep)if prefer_default or not default_segments:return default_segments10 unmodified linesstart_forward=start_forward,scan_anchor=scan_anchor,infill_keep=infill_keep,)if segments and segments not in candidates:candidates.append(segments)19 unmodified linesprefer_default: bool,frame: tuple[float, float, float, float],infill_keep=None,) -> list[Seg]:"""Snake raster at an arbitrary angle, reusing the axis raster machinery.37 unmodified linesprefer_default=prefer_default,scan_anchor=anchor,infill_keep=infill_keep,)theta_back = math.radians(angle_degrees)746 unmodified linesinfill_fraction: float = 1.0,extra_wall_radii: list[list[float]] | None = None,ring_center: tuple[float, float] | None = None,) -> tuple[list[dict], tuple[float, float]]:"""Assemble per-layer segments into a relative move list for all patterns.2 unmodified linesrotation pivot for diagonal layers.`infill_fraction` < 1 skips dispensing on evenly-distributed lines (gridlines for axis rasters, rings/revolutions for spirals) while the motionpath stays exactly the same as at 100% infill.Returns the move list and the toolpath origin — the world position therelative moves start from (the first segment start of the first non-empty1 unmodified line"""raster_pattern = _normalize_raster_pattern(raster_pattern)infill_keep = _infill_line_keep(infill_fraction)if scan_frame is not None:anchor_x = _scan_anchor(scan_frame[0], scan_frame[2], fil_width)anchor_y = _scan_anchor(scan_frame[1], scan_frame[3], fil_width)50 unmodified linesradii.append(radius)wall_radii = tuple(sorted(set(wall_radii) | set(extra_walls), reverse=True))points = _circle_rings_polyline(center_x, center_y, radii, fil_width)if layer_number % 2 == 1:points.reverse()67 unmodified linesprefer_default=not raster_origin_initialized,frame=frame,infill_keep=infill_keep,)else:raster_axis = _raster_axis_for_pattern(raster_pattern, layer_number)10 unmodified linesprefer_default=not raster_origin_initialized,scan_anchor=axis_anchor,infill_keep=infill_keep,)if not segments:327 unmodified lines32832933033133233333433533633733833934034134234334434534634734834935035135235335435535635752 unmodified lines4104114124134144154163 unmodified lines42042142242342442542642742826 unmodified lines4554564574584594604614624631 unmodified line46546646746846947047156 unmodified lines52852953053153253353453553653753853954054154254354410 unmodified lines55555655755855956056119 unmodified lines58158258358458558658737 unmodified lines625626627628629630631746 unmodified lines13781379138013811382138313842 unmodified lines138713881389139013911392139313941395139613971398139914001 unmodified line14021403140414051406140714081409141014111412141350 unmodified lines146414651466146714681469147014711472147314741475147614771478147967 unmodified lines154715481549155015511552155310 unmodified lines1564156515661567156815691570327 unmodified linesreturn keepdef _combined_infill_keep(fractions):"""Union infill gate over every shape sharing the motion; None = keep all.A grid line is traversed iff ANY shape's infill pattern dispenses on it —lines nobody prints are dropped from the MOTION entirely instead of beingswept valve-off (e.g. every shape at 50% infill halves the path). Everyshape must be given the same fraction list so the shared motion staysidentical across heads."""keeps = []for fraction in fractions or []:keep = _infill_line_keep(fraction)if keep is None:return None # someone prints every line: no motion line can dropkeeps.append(keep)if not keeps:return Nonedef keep_any(line_index: int) -> bool:return any(keep(line_index) for keep in keeps)return keep_anydef _scan_anchor(lo: float, hi: float, fil_width: float) -> float:"""First scanline position of the centred grid spanning [lo, hi].52 unmodified linesstart_forward: bool = True,scan_anchor: float | None = None,infill_keep=None,motion_keep=None,) -> list[Seg]:"""Snake raster of `motion`, dispensing only inside `valve`.3 unmodified linesvalve-settle travel buffer before and after. `scan_anchor` pins thescanlines to a global grid (see `_scan_coords`). `infill_keep(k)` gatesdispensing per grid line for partial infill: skipped lines are stillswept with the valve closed. `motion_keep(k)` drops a grid line from theMOTION entirely — used when NO shape sharing the motion dispenses there(the union of every head's infill pattern), so nobody sweeps dead lines."""if motion is None or motion.is_empty:return []26 unmodified linessegments: list[Seg] = []sweep_number = 0for coord in coords:line_index = int(round((coord - index_base) / fil_width))if motion_keep is not None and not motion_keep(line_index):continue # no head prints this line: drop it from the motionprobe = min(max(coord, probe_lo), probe_hi)motion_runs = _chord_runs(motion, axis, probe)if not motion_runs:1 unmodified linesweep_lo = motion_runs[0][0]sweep_hi = motion_runs[-1][1]if infill_keep is not None and not infill_keep(line_index):valve_runs: list[tuple[float, float]] = []else:valve_runs = []56 unmodified linesprefer_default: bool = False,scan_anchor: float | None = None,infill_keep=None,motion_keep=None,) -> list[Seg]:"""Pick the raster orientation whose start is nearest the current position."""default_segments = _axis_raster_segments(motion,valve,fil_width,axis,scan_anchor=scan_anchor,infill_keep=infill_keep,motion_keep=motion_keep,)if prefer_default or not default_segments:return default_segments10 unmodified linesstart_forward=start_forward,scan_anchor=scan_anchor,infill_keep=infill_keep,motion_keep=motion_keep,)if segments and segments not in candidates:candidates.append(segments)19 unmodified linesprefer_default: bool,frame: tuple[float, float, float, float],infill_keep=None,motion_keep=None,) -> list[Seg]:"""Snake raster at an arbitrary angle, reusing the axis raster machinery.37 unmodified linesprefer_default=prefer_default,scan_anchor=anchor,infill_keep=infill_keep,motion_keep=motion_keep,)theta_back = math.radians(angle_degrees)746 unmodified linesinfill_fraction: float = 1.0,extra_wall_radii: list[list[float]] | None = None,ring_center: tuple[float, float] | None = None,motion_infill_fractions: list[float] | None = None,) -> tuple[list[dict], tuple[float, float]]:"""Assemble per-layer segments into a relative move list for all patterns.2 unmodified linesrotation pivot for diagonal layers.`infill_fraction` < 1 skips dispensing on evenly-distributed lines (gridlines for axis rasters, rings for the circle spiral). Lines that NO headprints are dropped from the motion entirely: `motion_infill_fractions`lists every shape sharing the motion (pass the SAME list to every shape,or the shared paths diverge). When omitted, a SOLO shape's own fractionbounds its motion, while shared motion is never restricted (the otherheads' infill is unknown). The rectangular spiral keeps its fullcontinuous walk (a skipped loop would break the spiral intodisconnected rectangles).Returns the move list and the toolpath origin — the world position therelative moves start from (the first segment start of the first non-empty1 unmodified line"""raster_pattern = _normalize_raster_pattern(raster_pattern)infill_keep = _infill_line_keep(infill_fraction)if motion_infill_fractions is not None:motion_keep = _combined_infill_keep(motion_infill_fractions)elif shared_motion:motion_keep = Noneelse:motion_keep = infill_keepif scan_frame is not None:anchor_x = _scan_anchor(scan_frame[0], scan_frame[2], fil_width)anchor_y = _scan_anchor(scan_frame[1], scan_frame[3], fil_width)50 unmodified linesradii.append(radius)wall_radii = tuple(sorted(set(wall_radii) | set(extra_walls), reverse=True))if motion_keep is not None:# Rings NO head dispenses on drop out of the motion (walls# always print, so they always stay).radii = [radiusfor radius in radiiif any(abs(radius - wall) <= fil_width * 0.25 for wall in wall_radii)or motion_keep(max(0, int(round(radius / fil_width - 0.5))))]points = _circle_rings_polyline(center_x, center_y, radii, fil_width)if layer_number % 2 == 1:points.reverse()67 unmodified linesprefer_default=not raster_origin_initialized,frame=frame,infill_keep=infill_keep,motion_keep=motion_keep,)else:raster_axis = _raster_axis_for_pattern(raster_pattern, layer_number)10 unmodified linesprefer_default=not raster_origin_initialized,scan_anchor=axis_anchor,infill_keep=infill_keep,motion_keep=motion_keep,)if not segments: