pySlicer 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyslicer/__init__.py +3 -0
- pyslicer/__main__.py +6 -0
- pyslicer/cli.py +341 -0
- pyslicer/clipper_ops.py +78 -0
- pyslicer/config.py +217 -0
- pyslicer/config.schema.json +242 -0
- pyslicer/constants.py +3 -0
- pyslicer/demo.py +262 -0
- pyslicer/gcode/__init__.py +24 -0
- pyslicer/gcode/cooling.py +102 -0
- pyslicer/gcode/motion.py +193 -0
- pyslicer/gcode/overhang.py +147 -0
- pyslicer/gcode/parse.py +39 -0
- pyslicer/gcode/pressure.py +20 -0
- pyslicer/gcode/seam.py +191 -0
- pyslicer/gcode/writer.py +323 -0
- pyslicer/geometry/__init__.py +47 -0
- pyslicer/geometry/contour.py +149 -0
- pyslicer/geometry/exceptions.py +25 -0
- pyslicer/geometry/facet.py +26 -0
- pyslicer/geometry/intersection.py +23 -0
- pyslicer/geometry/line.py +225 -0
- pyslicer/geometry/math_utils.py +22 -0
- pyslicer/geometry/vector_ops.py +43 -0
- pyslicer/geometry/vertex.py +44 -0
- pyslicer/infill/__init__.py +5 -0
- pyslicer/infill/linear.py +225 -0
- pyslicer/mesh/__init__.py +7 -0
- pyslicer/mesh/layer.py +40 -0
- pyslicer/mesh/model.py +108 -0
- pyslicer/mesh/stl_io.py +129 -0
- pyslicer/preview/__init__.py +25 -0
- pyslicer/preview/__main__.py +49 -0
- pyslicer/preview/bead_profile.py +72 -0
- pyslicer/preview/gcode_html.py +613 -0
- pyslicer/preview/gcode_parse.py +518 -0
- pyslicer/preview/render_anim.py +201 -0
- pyslicer/preview/viewer_js.py +1192 -0
- pyslicer/slicing/__init__.py +19 -0
- pyslicer/slicing/perimeters.py +70 -0
- pyslicer/slicing/plane.py +191 -0
- pyslicer/slicing/process.py +92 -0
- pyslicer/slicing/segments.py +174 -0
- pyslicer/timer.py +23 -0
- pyslicer-0.2.0.dist-info/METADATA +216 -0
- pyslicer-0.2.0.dist-info/RECORD +50 -0
- pyslicer-0.2.0.dist-info/WHEEL +5 -0
- pyslicer-0.2.0.dist-info/entry_points.txt +3 -0
- pyslicer-0.2.0.dist-info/licenses/LICENSE +22 -0
- pyslicer-0.2.0.dist-info/top_level.txt +1 -0
pyslicer/__init__.py
ADDED
pyslicer/__main__.py
ADDED
pyslicer/cli.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
"""CLI entry point for pyslicer."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import logging
|
|
5
|
+
import sys
|
|
6
|
+
from operator import attrgetter
|
|
7
|
+
|
|
8
|
+
from pyslicer import clipper_ops
|
|
9
|
+
from pyslicer.config import (
|
|
10
|
+
apply_settings_to_model,
|
|
11
|
+
canonicalize_config,
|
|
12
|
+
load_layered_config,
|
|
13
|
+
parse_config_paths,
|
|
14
|
+
)
|
|
15
|
+
from pyslicer.geometry.contour import Contour
|
|
16
|
+
from pyslicer.infill import simple_linear_infill
|
|
17
|
+
from pyslicer.mesh import Model, read_file
|
|
18
|
+
from pyslicer.slicing import slice_model
|
|
19
|
+
from pyslicer.timer import Timer
|
|
20
|
+
|
|
21
|
+
# Seeded for every CLI run so --config and no-config share the same baseline.
|
|
22
|
+
_CLI_HISTORICAL_DEFAULTS = {
|
|
23
|
+
"perimeters_only": False,
|
|
24
|
+
"append_perimeters": False,
|
|
25
|
+
"perimeter_overlap_percent": 1.0,
|
|
26
|
+
"number_perimeters": 3,
|
|
27
|
+
"filament_diameter": 1.75,
|
|
28
|
+
"layerHeight": 0.1,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
_CLI_SETTING_DESTS = frozenset(
|
|
32
|
+
{
|
|
33
|
+
"perimeters_only",
|
|
34
|
+
"append_perimeters",
|
|
35
|
+
"perimeter_overlap_percent",
|
|
36
|
+
"num_perimeters",
|
|
37
|
+
"filament_diameter",
|
|
38
|
+
"layer_height",
|
|
39
|
+
"outer_speed",
|
|
40
|
+
"inner_speed",
|
|
41
|
+
"infill_speed",
|
|
42
|
+
"max_corner_speed",
|
|
43
|
+
"max_accel",
|
|
44
|
+
"max_jerk",
|
|
45
|
+
"min_corner_angle",
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_arg_parser():
|
|
51
|
+
parser = argparse.ArgumentParser(
|
|
52
|
+
description="An STL slicer for producing 3D printer gcode."
|
|
53
|
+
)
|
|
54
|
+
parser.add_argument("stl", help="STL file to be sliced.")
|
|
55
|
+
parser.add_argument("output", help="Output path for generated gcode.")
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--config",
|
|
58
|
+
metavar="PATHS",
|
|
59
|
+
help=(
|
|
60
|
+
"Comma-separated YAML config files, layered left-to-right "
|
|
61
|
+
"(later files override earlier). CLI flags always win."
|
|
62
|
+
),
|
|
63
|
+
)
|
|
64
|
+
parser.add_argument(
|
|
65
|
+
"-p",
|
|
66
|
+
"--perimeters-only",
|
|
67
|
+
"--perimeters_only",
|
|
68
|
+
dest="perimeters_only",
|
|
69
|
+
help="Generate only perimeters, no infill.",
|
|
70
|
+
action=argparse.BooleanOptionalAction,
|
|
71
|
+
default=argparse.SUPPRESS,
|
|
72
|
+
)
|
|
73
|
+
parser.add_argument(
|
|
74
|
+
"-a",
|
|
75
|
+
"--append-perimeters",
|
|
76
|
+
"--append_perimeters",
|
|
77
|
+
dest="append_perimeters",
|
|
78
|
+
help="Include original stl perimeters with no offsetting in the output.",
|
|
79
|
+
action=argparse.BooleanOptionalAction,
|
|
80
|
+
default=argparse.SUPPRESS,
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument("-v", "--verbose", help="Be verbose.", action="store_true")
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
"-o",
|
|
85
|
+
"--perimeter_overlap_percent",
|
|
86
|
+
help="Percent overlap between perimeters. Smaller results in more overlap.",
|
|
87
|
+
type=float,
|
|
88
|
+
default=argparse.SUPPRESS,
|
|
89
|
+
)
|
|
90
|
+
parser.add_argument(
|
|
91
|
+
"-n",
|
|
92
|
+
"--num-perimeters",
|
|
93
|
+
help="Minimum number of perimeters.",
|
|
94
|
+
type=int,
|
|
95
|
+
default=argparse.SUPPRESS,
|
|
96
|
+
)
|
|
97
|
+
parser.add_argument(
|
|
98
|
+
"-d",
|
|
99
|
+
"--filament-diameter",
|
|
100
|
+
help="Measured diameter of filament to at least two decimal places.",
|
|
101
|
+
type=float,
|
|
102
|
+
default=argparse.SUPPRESS,
|
|
103
|
+
)
|
|
104
|
+
parser.add_argument(
|
|
105
|
+
"-l",
|
|
106
|
+
"--layer-height",
|
|
107
|
+
help="Slicing layer height",
|
|
108
|
+
type=float,
|
|
109
|
+
default=argparse.SUPPRESS,
|
|
110
|
+
)
|
|
111
|
+
parser.add_argument(
|
|
112
|
+
"--outer-speed",
|
|
113
|
+
type=float,
|
|
114
|
+
default=argparse.SUPPRESS,
|
|
115
|
+
help="Outer perimeter print speed (mm/s).",
|
|
116
|
+
)
|
|
117
|
+
parser.add_argument(
|
|
118
|
+
"--inner-speed",
|
|
119
|
+
type=float,
|
|
120
|
+
default=argparse.SUPPRESS,
|
|
121
|
+
help="Inner perimeter print speed (mm/s).",
|
|
122
|
+
)
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
"--infill-speed",
|
|
125
|
+
type=float,
|
|
126
|
+
default=argparse.SUPPRESS,
|
|
127
|
+
help="Infill print speed (mm/s).",
|
|
128
|
+
)
|
|
129
|
+
parser.add_argument(
|
|
130
|
+
"--max-corner-speed",
|
|
131
|
+
type=float,
|
|
132
|
+
default=argparse.SUPPRESS,
|
|
133
|
+
help="Max speed at a 90° corner (mm/s).",
|
|
134
|
+
)
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"--max-accel",
|
|
137
|
+
type=float,
|
|
138
|
+
default=argparse.SUPPRESS,
|
|
139
|
+
help="Max print acceleration for feed planning (mm/s²).",
|
|
140
|
+
)
|
|
141
|
+
parser.add_argument(
|
|
142
|
+
"--max-jerk",
|
|
143
|
+
type=float,
|
|
144
|
+
default=argparse.SUPPRESS,
|
|
145
|
+
help="Max corner speed change Δv for feed planning (mm/s).",
|
|
146
|
+
)
|
|
147
|
+
parser.add_argument(
|
|
148
|
+
"--min-corner-angle",
|
|
149
|
+
type=float,
|
|
150
|
+
default=argparse.SUPPRESS,
|
|
151
|
+
help="Min turn angle (deg) before accel/jerk caps apply.",
|
|
152
|
+
)
|
|
153
|
+
parser.add_argument(
|
|
154
|
+
"--html-preview",
|
|
155
|
+
metavar="PATH",
|
|
156
|
+
help="Also write an HTML toolpath preview to this path.",
|
|
157
|
+
)
|
|
158
|
+
return parser
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _cli_overrides_to_model_settings(args) -> dict:
|
|
162
|
+
"""Map explicitly passed CLI flags to Model-native settings."""
|
|
163
|
+
raw = {k: v for k, v in vars(args).items() if k in _CLI_SETTING_DESTS}
|
|
164
|
+
if not raw:
|
|
165
|
+
return {}
|
|
166
|
+
# Dest names match YAML keys (num_perimeters, layer_height, outer_speed, …).
|
|
167
|
+
return canonicalize_config(raw)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def configure_model(args) -> Model:
|
|
171
|
+
"""Build a Model with CLI historical defaults → YAML layers → CLI overrides."""
|
|
172
|
+
model = Model()
|
|
173
|
+
apply_settings_to_model(model, _CLI_HISTORICAL_DEFAULTS)
|
|
174
|
+
config_arg = getattr(args, "config", None)
|
|
175
|
+
if config_arg:
|
|
176
|
+
paths = parse_config_paths(config_arg)
|
|
177
|
+
apply_settings_to_model(model, load_layered_config(paths))
|
|
178
|
+
apply_settings_to_model(model, _cli_overrides_to_model_settings(args))
|
|
179
|
+
return model
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _compute_roofs_and_overhangs(layers):
|
|
183
|
+
for layer_num in range(1, len(layers)):
|
|
184
|
+
zcur = layers[layer_num].z
|
|
185
|
+
if not layers[layer_num].perimeters:
|
|
186
|
+
continue
|
|
187
|
+
current = [c.to_path() for c in layers[layer_num].perimeters[-1]]
|
|
188
|
+
previous = []
|
|
189
|
+
if layers[layer_num - 1].perimeters:
|
|
190
|
+
previous = [
|
|
191
|
+
c.to_path()
|
|
192
|
+
for c in layers[layer_num - 1].perimeters[-1]
|
|
193
|
+
if c.is_closed()
|
|
194
|
+
]
|
|
195
|
+
nxt = []
|
|
196
|
+
if layer_num < len(layers) - 2 and layers[layer_num + 1].perimeters:
|
|
197
|
+
nxt = [c.to_path() for c in layers[layer_num + 1].perimeters[-1]]
|
|
198
|
+
|
|
199
|
+
roofs = clipper_ops.difference_polygons(previous, current)
|
|
200
|
+
for poly in roofs:
|
|
201
|
+
layers[layer_num - 1].roofs.append(Contour.from_path(poly, zcur))
|
|
202
|
+
|
|
203
|
+
previous_minus_roof = clipper_ops.difference_polygons(previous, roofs)
|
|
204
|
+
for poly in previous_minus_roof:
|
|
205
|
+
layers[layer_num - 1].normalInfill.append(Contour.from_path(poly, zcur))
|
|
206
|
+
|
|
207
|
+
overhang = clipper_ops.difference_polygons(nxt, current)
|
|
208
|
+
for poly in overhang:
|
|
209
|
+
if layer_num + 1 < len(layers):
|
|
210
|
+
layers[layer_num + 1].overhang.append(Contour.from_path(poly, zcur))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def run(args):
|
|
214
|
+
logger = logging.getLogger()
|
|
215
|
+
ch = logging.StreamHandler(sys.stdout)
|
|
216
|
+
logger.addHandler(ch)
|
|
217
|
+
logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)
|
|
218
|
+
|
|
219
|
+
sys.setrecursionlimit(6000)
|
|
220
|
+
logger.info("Reading...")
|
|
221
|
+
with Timer() as total_time:
|
|
222
|
+
with Timer() as read_time:
|
|
223
|
+
model = configure_model(args)
|
|
224
|
+
read_file(args.stl, model)
|
|
225
|
+
logger.info("File read took %s seconds", read_time.secs)
|
|
226
|
+
|
|
227
|
+
logger.info("Slicing...")
|
|
228
|
+
with Timer() as slice_time:
|
|
229
|
+
layers = slice_model(model)
|
|
230
|
+
logger.warning(
|
|
231
|
+
"Slicing took %s seconds. %s layers", slice_time.secs, len(layers)
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
layers.sort(key=attrgetter("z"))
|
|
235
|
+
_compute_roofs_and_overhangs(layers)
|
|
236
|
+
|
|
237
|
+
logger.info("Starting infill...")
|
|
238
|
+
with Timer() as infill_time:
|
|
239
|
+
for layer_num in range(len(layers)):
|
|
240
|
+
z = layers[layer_num].z
|
|
241
|
+
if model.perimeters_only:
|
|
242
|
+
layers[layer_num].infill = []
|
|
243
|
+
continue
|
|
244
|
+
angle = (
|
|
245
|
+
model.infill_angle if layer_num % 2 else -model.infill_angle
|
|
246
|
+
)
|
|
247
|
+
perimeters = layers[layer_num].perimeters
|
|
248
|
+
if not perimeters or not perimeters[-1]:
|
|
249
|
+
layers[layer_num].infill = []
|
|
250
|
+
continue
|
|
251
|
+
if layer_num < 4 or layer_num > len(layers) - 4:
|
|
252
|
+
layers[layer_num].infill = simple_linear_infill(
|
|
253
|
+
perimeters[-1],
|
|
254
|
+
z,
|
|
255
|
+
spacing=model.offset(),
|
|
256
|
+
min_extrude=1.0,
|
|
257
|
+
angle=angle,
|
|
258
|
+
name="normal",
|
|
259
|
+
)
|
|
260
|
+
else:
|
|
261
|
+
infill = simple_linear_infill(
|
|
262
|
+
layers[layer_num].normalInfill,
|
|
263
|
+
z,
|
|
264
|
+
spacing=2.0,
|
|
265
|
+
min_extrude=1.0,
|
|
266
|
+
angle=angle,
|
|
267
|
+
name="normal",
|
|
268
|
+
)
|
|
269
|
+
layers[layer_num].infill = infill
|
|
270
|
+
roof_infill = simple_linear_infill(
|
|
271
|
+
layers[layer_num].roofs,
|
|
272
|
+
z,
|
|
273
|
+
spacing=model.offset(),
|
|
274
|
+
min_extrude=0.5,
|
|
275
|
+
angle=angle,
|
|
276
|
+
name="roof",
|
|
277
|
+
)
|
|
278
|
+
layers[layer_num].infill.extend(roof_infill)
|
|
279
|
+
logger.info("Infill time %s", infill_time.secs)
|
|
280
|
+
|
|
281
|
+
with Timer() as model_time:
|
|
282
|
+
for result in layers:
|
|
283
|
+
zcur = result.z
|
|
284
|
+
model.layers.append(result)
|
|
285
|
+
for contour in result.contours:
|
|
286
|
+
contour.zlevel = zcur
|
|
287
|
+
model.contours.append(contour)
|
|
288
|
+
model.infillAtLayer[zcur] = result.infill
|
|
289
|
+
logger.warning("Model setup took %s seconds", model_time.secs)
|
|
290
|
+
|
|
291
|
+
with Timer() as gcode_time:
|
|
292
|
+
model.writeGCode(args.output)
|
|
293
|
+
logger.warning("GCode generation took %s seconds", gcode_time.secs)
|
|
294
|
+
|
|
295
|
+
if args.html_preview:
|
|
296
|
+
from pyslicer.preview import write_gcode_preview
|
|
297
|
+
|
|
298
|
+
preview_path = write_gcode_preview(
|
|
299
|
+
args.output,
|
|
300
|
+
args.html_preview,
|
|
301
|
+
subtitle=f"From {args.stl}",
|
|
302
|
+
nozzle_diameter=model.nozzle_diameter,
|
|
303
|
+
layer_height=model.layerHeight,
|
|
304
|
+
max_accel=model.max_accel,
|
|
305
|
+
planning_limits={
|
|
306
|
+
# User-facing speeds are mm/s (G-code F is mm/min)
|
|
307
|
+
"maxSpeed": model.outer_perimeter_speed / 60.0,
|
|
308
|
+
"outerSpeed": model.outer_perimeter_speed / 60.0,
|
|
309
|
+
"innerSpeed": model.inner_perimeter_speed / 60.0,
|
|
310
|
+
"infillSpeed": model.infill_speed / 60.0,
|
|
311
|
+
"maxAccel": model.max_accel,
|
|
312
|
+
"maxJerk": model.max_jerk,
|
|
313
|
+
"minAngleDeg": model.min_corner_angle,
|
|
314
|
+
"maxCornerSpeed": model.max_corner_speed / 60.0,
|
|
315
|
+
},
|
|
316
|
+
)
|
|
317
|
+
logger.info("HTML preview wrote %s", preview_path)
|
|
318
|
+
|
|
319
|
+
logger.info("TOTAL TIME %s seconds", total_time.secs)
|
|
320
|
+
logger.info(
|
|
321
|
+
"facets: %d facet end: %d zmin: %f zmax: %f ",
|
|
322
|
+
len(model.facets),
|
|
323
|
+
model.endLoop,
|
|
324
|
+
model.zmin,
|
|
325
|
+
model.zmax,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def main(argv=None):
|
|
330
|
+
from pyslicer.config import ConfigError
|
|
331
|
+
|
|
332
|
+
parser = build_arg_parser()
|
|
333
|
+
args = parser.parse_args(argv)
|
|
334
|
+
try:
|
|
335
|
+
run(args)
|
|
336
|
+
except ConfigError as exc:
|
|
337
|
+
parser.exit(2, f"error: {exc}\n")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
if __name__ == "__main__":
|
|
341
|
+
main()
|
pyslicer/clipper_ops.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Thin pyclipper adapter for polygon boolean ops and offsets.
|
|
2
|
+
|
|
3
|
+
All public functions take model-unit (mm) float paths. Scaled clipper
|
|
4
|
+
integers are never accepted — call Contour.clipper_points only for
|
|
5
|
+
legacy introspection, not as clipper_ops input.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import pyclipper
|
|
9
|
+
|
|
10
|
+
from pyslicer.constants import CLIPPER_SCALE_FACTOR
|
|
11
|
+
|
|
12
|
+
SCALE = CLIPPER_SCALE_FACTOR
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _to_paths(polygons):
|
|
16
|
+
"""Convert mm float paths to clipper integers. Empty → []."""
|
|
17
|
+
if not polygons:
|
|
18
|
+
return []
|
|
19
|
+
return [pyclipper.scale_to_clipper(path, SCALE) for path in polygons]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _from_paths(paths):
|
|
23
|
+
"""Return float (x, y) paths in mm."""
|
|
24
|
+
if not paths:
|
|
25
|
+
return []
|
|
26
|
+
return pyclipper.scale_from_clipper(paths, SCALE)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def union_polygons(paths):
|
|
30
|
+
"""Union subject paths. paths: list of float (x,y) rings in mm."""
|
|
31
|
+
if not paths:
|
|
32
|
+
return []
|
|
33
|
+
pc = pyclipper.Pyclipper()
|
|
34
|
+
pc.AddPaths(_to_paths(paths), pyclipper.PT_SUBJECT, True)
|
|
35
|
+
result = pc.Execute(
|
|
36
|
+
pyclipper.CT_UNION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD
|
|
37
|
+
)
|
|
38
|
+
return _from_paths(result)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def difference_polygons(subject_paths, clip_paths):
|
|
42
|
+
if not subject_paths:
|
|
43
|
+
return []
|
|
44
|
+
pc = pyclipper.Pyclipper()
|
|
45
|
+
pc.AddPaths(_to_paths(subject_paths), pyclipper.PT_SUBJECT, True)
|
|
46
|
+
if clip_paths:
|
|
47
|
+
pc.AddPaths(_to_paths(clip_paths), pyclipper.PT_CLIP, True)
|
|
48
|
+
result = pc.Execute(
|
|
49
|
+
pyclipper.CT_DIFFERENCE, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD
|
|
50
|
+
)
|
|
51
|
+
return _from_paths(result)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def offset_polygons(paths, delta):
|
|
55
|
+
"""Offset by delta in mm. Negative shrinks."""
|
|
56
|
+
if not paths:
|
|
57
|
+
return []
|
|
58
|
+
pco = pyclipper.PyclipperOffset()
|
|
59
|
+
for path in _to_paths(paths):
|
|
60
|
+
pco.AddPath(path, pyclipper.JT_MITER, pyclipper.ET_CLOSEDPOLYGON)
|
|
61
|
+
result = pco.Execute(int(delta * SCALE))
|
|
62
|
+
return _from_paths(result)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def simplify_polygon(path):
|
|
66
|
+
"""Simplify a single mm float path; return list of float paths."""
|
|
67
|
+
if not path:
|
|
68
|
+
return []
|
|
69
|
+
scaled = pyclipper.scale_to_clipper(path, SCALE)
|
|
70
|
+
result = pyclipper.SimplifyPolygon(scaled, pyclipper.PFT_EVENODD)
|
|
71
|
+
return _from_paths(result)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def clean_polygons(paths, distance=1.415):
|
|
75
|
+
if not paths:
|
|
76
|
+
return []
|
|
77
|
+
cleaned = pyclipper.CleanPolygons(_to_paths(paths), distance)
|
|
78
|
+
return _from_paths(cleaned)
|
pyslicer/config.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Layered YAML configuration for pyslicer print settings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from functools import lru_cache
|
|
7
|
+
from importlib import resources
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Mapping
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
from jsonschema import Draft202012Validator
|
|
13
|
+
|
|
14
|
+
# CLI-facing mm/s keys → Model attribute (stored as mm/min).
|
|
15
|
+
# Values are converted (*60) during canonicalize; merged dict is Model-native.
|
|
16
|
+
_SPEED_MM_S_TO_ATTR = {
|
|
17
|
+
"outer_speed": "outer_perimeter_speed",
|
|
18
|
+
"inner_speed": "inner_perimeter_speed",
|
|
19
|
+
"infill_speed": "infill_speed",
|
|
20
|
+
"max_corner_speed": "max_corner_speed",
|
|
21
|
+
"slow_down_min_speed": "slow_down_min_speed",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Model-native mm/min speed keys that share an attribute with an mm/s alias.
|
|
25
|
+
_SPEED_MM_MIN_ATTRS = frozenset(
|
|
26
|
+
{
|
|
27
|
+
"outer_perimeter_speed",
|
|
28
|
+
"inner_perimeter_speed",
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Non-speed aliases → Model attribute (same units).
|
|
33
|
+
_KEY_ALIASES = {
|
|
34
|
+
"layer_height": "layerHeight",
|
|
35
|
+
"num_perimeters": "number_perimeters",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
# Groups of YAML keys that target the same Model attribute (mutually exclusive).
|
|
39
|
+
_MUTUAL_EXCLUSION_GROUPS = (
|
|
40
|
+
frozenset({"outer_speed", "outer_perimeter_speed"}),
|
|
41
|
+
frozenset({"inner_speed", "inner_perimeter_speed"}),
|
|
42
|
+
frozenset({"layer_height", "layerHeight"}),
|
|
43
|
+
frozenset({"num_perimeters", "number_perimeters"}),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
# Print settings that may appear in YAML (Model attribute names).
|
|
47
|
+
_MODEL_SETTING_KEYS = frozenset(
|
|
48
|
+
{
|
|
49
|
+
"nozzle_diameter",
|
|
50
|
+
"layerHeight",
|
|
51
|
+
"retract_amount",
|
|
52
|
+
"retract_speed",
|
|
53
|
+
"unretract_speed",
|
|
54
|
+
"default_print_speed",
|
|
55
|
+
"outer_perimeter_speed",
|
|
56
|
+
"inner_perimeter_speed",
|
|
57
|
+
"infill_speed",
|
|
58
|
+
"default_travel_speed",
|
|
59
|
+
"default_z_speed",
|
|
60
|
+
"max_corner_speed",
|
|
61
|
+
"max_accel",
|
|
62
|
+
"max_jerk",
|
|
63
|
+
"min_corner_angle",
|
|
64
|
+
"filament_diameter",
|
|
65
|
+
"number_perimeters",
|
|
66
|
+
"processing_threads",
|
|
67
|
+
"infill_density",
|
|
68
|
+
"infill_angle",
|
|
69
|
+
"width_over_height",
|
|
70
|
+
"perimeters_only",
|
|
71
|
+
"append_perimeters",
|
|
72
|
+
"perimeter_overlap_percent",
|
|
73
|
+
"minimum_retract_travel",
|
|
74
|
+
"print_temperature",
|
|
75
|
+
"simplification_factor",
|
|
76
|
+
"min_contour_area",
|
|
77
|
+
"min_extrude",
|
|
78
|
+
"firmware",
|
|
79
|
+
"pressure_advance",
|
|
80
|
+
"enable_dynamic_overhang_speeds",
|
|
81
|
+
"overhang_speed_0",
|
|
82
|
+
"overhang_speed_25",
|
|
83
|
+
"overhang_speed_50",
|
|
84
|
+
"overhang_speed_75",
|
|
85
|
+
"min_layer_time",
|
|
86
|
+
"slow_down_min_speed",
|
|
87
|
+
"dont_slow_down_outer_wall",
|
|
88
|
+
"seam_position",
|
|
89
|
+
"wipe_distance",
|
|
90
|
+
"wipe_on_loops",
|
|
91
|
+
"seam_gap",
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
_ALLOWED_YAML_KEYS = (
|
|
96
|
+
_MODEL_SETTING_KEYS | frozenset(_KEY_ALIASES) | frozenset(_SPEED_MM_S_TO_ATTR)
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ConfigError(ValueError):
|
|
101
|
+
"""Invalid YAML config content or unknown keys."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _shallow_merge(base: dict[str, Any], overlay: Mapping[str, Any]) -> dict[str, Any]:
|
|
105
|
+
merged = dict(base)
|
|
106
|
+
merged.update(overlay)
|
|
107
|
+
return merged
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@lru_cache(maxsize=1)
|
|
111
|
+
def load_config_schema() -> dict[str, Any]:
|
|
112
|
+
"""Load the packaged JSON Schema for pyslicer YAML configs."""
|
|
113
|
+
text = resources.files("pyslicer").joinpath("config.schema.json").read_text(
|
|
114
|
+
encoding="utf-8"
|
|
115
|
+
)
|
|
116
|
+
return json.loads(text)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def validate_config(data: Mapping[str, Any], *, source: str | Path | None = None) -> None:
|
|
120
|
+
"""Validate config data against the JSON Schema. Raises ConfigError on failure."""
|
|
121
|
+
validator = Draft202012Validator(load_config_schema())
|
|
122
|
+
errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
|
|
123
|
+
if not errors:
|
|
124
|
+
return
|
|
125
|
+
where = f" in {source}" if source is not None else ""
|
|
126
|
+
messages = []
|
|
127
|
+
for err in errors:
|
|
128
|
+
path = ".".join(str(p) for p in err.path) or "(root)"
|
|
129
|
+
messages.append(f"{path}: {err.message}")
|
|
130
|
+
raise ConfigError(f"Invalid config{where}: " + "; ".join(messages))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def canonicalize_config(
|
|
134
|
+
data: Mapping[str, Any], *, source: str | Path | None = None
|
|
135
|
+
) -> dict[str, Any]:
|
|
136
|
+
"""Map YAML keys to Model attributes with Model-native units.
|
|
137
|
+
|
|
138
|
+
CLI-style speed keys (outer_speed, inner_speed, infill_speed, max_corner_speed,
|
|
139
|
+
slow_down_min_speed) are mm/s and converted to mm/min.
|
|
140
|
+
outer_perimeter_speed / inner_perimeter_speed are already mm/min.
|
|
141
|
+
Dual keys that target the same attribute raise ConfigError.
|
|
142
|
+
|
|
143
|
+
Note: YAML has no separate mm/min twin for infill_speed / max_corner_speed /
|
|
144
|
+
slow_down_min_speed; those keys always mean mm/s (matching the CLI flags).
|
|
145
|
+
"""
|
|
146
|
+
where = f" in {source}" if source is not None else ""
|
|
147
|
+
for group in _MUTUAL_EXCLUSION_GROUPS:
|
|
148
|
+
present = group & data.keys()
|
|
149
|
+
if len(present) > 1:
|
|
150
|
+
keys = ", ".join(sorted(present))
|
|
151
|
+
raise ConfigError(
|
|
152
|
+
f"Conflicting config keys{where}: {keys} set the same setting"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
canonical: dict[str, Any] = {}
|
|
156
|
+
for key, value in data.items():
|
|
157
|
+
if key in _SPEED_MM_S_TO_ATTR:
|
|
158
|
+
attr = _SPEED_MM_S_TO_ATTR[key]
|
|
159
|
+
canonical[attr] = float(value) * 60.0
|
|
160
|
+
elif key in _SPEED_MM_MIN_ATTRS:
|
|
161
|
+
canonical[key] = float(value)
|
|
162
|
+
elif key in _KEY_ALIASES:
|
|
163
|
+
canonical[_KEY_ALIASES[key]] = value
|
|
164
|
+
else:
|
|
165
|
+
canonical[key] = value
|
|
166
|
+
return canonical
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def load_config_file(path: str | Path) -> dict[str, Any]:
|
|
170
|
+
"""Load one YAML file and return Model-native canonical settings."""
|
|
171
|
+
path = Path(path)
|
|
172
|
+
try:
|
|
173
|
+
with path.open(encoding="utf-8") as f:
|
|
174
|
+
data = yaml.safe_load(f)
|
|
175
|
+
except OSError as exc:
|
|
176
|
+
raise ConfigError(f"Cannot read config {path}: {exc}") from exc
|
|
177
|
+
if data is None:
|
|
178
|
+
return {}
|
|
179
|
+
if not isinstance(data, dict):
|
|
180
|
+
raise ConfigError(f"Config root must be a mapping: {path}")
|
|
181
|
+
validate_config(data, source=path)
|
|
182
|
+
return canonicalize_config(data, source=path)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def load_layered_config(paths: list[str | Path]) -> dict[str, Any]:
|
|
186
|
+
"""Load YAML files in order; later layers replace overlapping Model settings."""
|
|
187
|
+
if not paths:
|
|
188
|
+
raise ConfigError("No config paths provided")
|
|
189
|
+
merged: dict[str, Any] = {}
|
|
190
|
+
for path in paths:
|
|
191
|
+
layer = load_config_file(path)
|
|
192
|
+
merged = _shallow_merge(merged, layer)
|
|
193
|
+
return merged
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def parse_config_paths(value: str) -> list[str]:
|
|
197
|
+
"""Split a comma-separated --config value into path strings."""
|
|
198
|
+
paths = [p.strip() for p in value.split(",") if p.strip()]
|
|
199
|
+
if not paths:
|
|
200
|
+
raise ConfigError("No config paths provided")
|
|
201
|
+
return paths
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def apply_settings_to_model(model: Any, settings: Mapping[str, Any]) -> None:
|
|
205
|
+
"""Apply Model-native settings (already canonicalized) onto a Model."""
|
|
206
|
+
for key, value in settings.items():
|
|
207
|
+
setattr(model, key, value)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def apply_config_to_model(model: Any, config: Mapping[str, Any]) -> None:
|
|
211
|
+
"""Validate raw YAML keys, canonicalize to Model-native units, and apply.
|
|
212
|
+
|
|
213
|
+
For already-canonical settings from load_layered_config, use
|
|
214
|
+
apply_settings_to_model instead (avoids double-converting speeds).
|
|
215
|
+
"""
|
|
216
|
+
validate_config(config)
|
|
217
|
+
apply_settings_to_model(model, canonicalize_config(config))
|