3d-base 0.3.3__tar.gz → 0.5.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: 3d-base
3
- Version: 0.3.3
3
+ Version: 0.5.0
4
4
  Summary: Headless pictures of 3D meshes with correct occlusion and smooth shading, and a health check for exported STL files
5
5
  Author: Konstantinos Georgiou
6
6
  License-Expression: MIT
@@ -15,6 +15,8 @@ Requires-Dist: numpy>=1.22
15
15
  Requires-Dist: trimesh>=3.20
16
16
  Requires-Dist: scipy>=1.8
17
17
  Requires-Dist: rtree>=1.0
18
+ Requires-Dist: fast-simplification>=0.1
19
+ Requires-Dist: scikit-image>=0.21
18
20
  Provides-Extra: captions
19
21
  Requires-Dist: pillow>=10.1; extra == "captions"
20
22
  Provides-Extra: sections
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "3d-base"
7
- version = "0.3.3"
7
+ version = "0.5.0"
8
8
  description = "Headless pictures of 3D meshes with correct occlusion and smooth shading, and a health check for exported STL files"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
11
  license = "MIT"
12
12
  authors = [{ name = "Konstantinos Georgiou" }]
13
- dependencies = ["numpy>=1.22", "trimesh>=3.20", "scipy>=1.8", "rtree>=1.0"]
13
+ dependencies = ["numpy>=1.22", "trimesh>=3.20", "scipy>=1.8", "rtree>=1.0", "fast-simplification>=0.1", "scikit-image>=0.21"]
14
14
  keywords = ["3d", "mesh", "stl", "render", "headless", "trimesh", "3d-printing", "cad"]
15
15
  classifiers = ["Programming Language :: Python :: 3", "Topic :: Multimedia :: Graphics :: 3D Rendering"]
16
16
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: 3d-base
3
- Version: 0.3.3
3
+ Version: 0.5.0
4
4
  Summary: Headless pictures of 3D meshes with correct occlusion and smooth shading, and a health check for exported STL files
5
5
  Author: Konstantinos Georgiou
6
6
  License-Expression: MIT
@@ -15,6 +15,8 @@ Requires-Dist: numpy>=1.22
15
15
  Requires-Dist: trimesh>=3.20
16
16
  Requires-Dist: scipy>=1.8
17
17
  Requires-Dist: rtree>=1.0
18
+ Requires-Dist: fast-simplification>=0.1
19
+ Requires-Dist: scikit-image>=0.21
18
20
  Provides-Extra: captions
19
21
  Requires-Dist: pillow>=10.1; extra == "captions"
20
22
  Provides-Extra: sections
@@ -10,9 +10,11 @@ src/3d_base.egg-info/top_level.txt
10
10
  src/base3d/__init__.py
11
11
  src/base3d/cli.py
12
12
  src/base3d/mesh.py
13
+ src/base3d/nozzle.py
13
14
  src/base3d/show.py
14
15
  src/base3d/thickness.py
15
16
  src/base3d/skill/SKILL.md
16
17
  tests/test_mesh.py
18
+ tests/test_nozzle.py
17
19
  tests/test_show.py
18
20
  tests/test_thickness.py
@@ -2,6 +2,8 @@ numpy>=1.22
2
2
  trimesh>=3.20
3
3
  scipy>=1.8
4
4
  rtree>=1.0
5
+ fast-simplification>=0.1
6
+ scikit-image>=0.21
5
7
 
6
8
  [captions]
7
9
  pillow>=10.1
@@ -1,6 +1,7 @@
1
1
  """Headless pictures of 3D meshes, and an honest health check for exported STL files."""
2
2
  from .mesh import load_clean, report, surface_points, voids
3
+ from .nozzle import Nozzle
3
4
  from .show import frame_on, render, save_png, sheet, tile
4
5
 
5
- __version__ = "0.2.0"
6
- __all__ = ["frame_on", "load_clean", "render", "report", "save_png", "sheet", "surface_points", "tile", "voids"]
6
+ __version__ = "0.5.0"
7
+ __all__ = ["Nozzle", "frame_on", "load_clean", "render", "report", "save_png", "sheet", "surface_points", "tile", "voids"]
@@ -37,6 +37,8 @@ def main(argv=None) -> int:
37
37
  t.add_argument("-n", type=int, default=4000, help="sample points on the surface (default 4000)")
38
38
  t.add_argument("--printed", action="store_true",
39
39
  help="judge each wall as the part lies, +z up: two lines across a layer, two layers through a flat plate")
40
+ t.add_argument("--nozzle", type=float, help="the nozzle's diameter in mm; the bar becomes two of its lines")
41
+ t.add_argument("--layer", type=float, default=0.2, help="the layer height in mm, with --nozzle (default 0.2)")
40
42
 
41
43
  so = sub.add_parser("sound", help="whether a part is sound to print, and every reason it is not")
42
44
  so.add_argument("mesh")
@@ -71,11 +73,15 @@ def main(argv=None) -> int:
71
73
  print(json.dumps(rep, indent=1))
72
74
  return 1 if rep["faults"] else 0
73
75
  if a.cmd == "thickness":
76
+ from .nozzle import Nozzle
74
77
  from .thickness import print_thin_spots, thin_spots, wall_thickness
78
+ noz = Nozzle(a.nozzle, a.layer) if a.nozzle else None
79
+ if noz is not None:
80
+ a.bar = noz.wall
75
81
  m, _ = load_clean(a.mesh)
76
82
  _pts, _nrm, mm = wall_thickness(m, n=a.n)
77
83
  finite = [float(x) for x in mm if x != float("inf")]
78
- spots = print_thin_spots(m, line_mm=a.bar, n=a.n) if a.printed else thin_spots(m, a.bar, n=a.n)
84
+ spots = print_thin_spots(m, line_mm=a.bar, n=a.n, nozzle=noz) if a.printed else thin_spots(m, a.bar, n=a.n)
79
85
  print(json.dumps({"thinnest_mm": min(finite) if finite else None, "bar_mm": a.bar,
80
86
  "thin_spots": spots}, indent=1))
81
87
  return 1 if spots else 0
@@ -270,6 +270,47 @@ def solid_from_skin(mesh: trimesh.Trimesh, centre, lean: float = 0.3, keep=None,
270
270
  return solid
271
271
 
272
272
 
273
+ def remanifold(mesh: trimesh.Trimesh, pitch: float = 0.3, close: int = 1, smooth: int = 25,
274
+ decimate_to: int = 25000) -> trimesh.Trimesh:
275
+ """A mesh rebuilt as one simple solid on a voxel grid.
276
+
277
+ A boolean operation can leave a mesh that is watertight but not a simple solid: a tunnel through a
278
+ seam where two parts join (a handle, so the Euler number is not 2), or a near-coincident sheet
279
+ where two surfaces meet at a grazing angle, which a thickness measure reads as a wall thinner than
280
+ any line and a slicer cannot print. This turns the mesh into filled voxels of side `pitch`, which
281
+ cannot carry a tunnel or a gap thinner than `pitch`; `close` passes of a morphological closing
282
+ fill the sub-pitch tunnels and the thin grooves a surface would otherwise read as handles; the
283
+ surface is taken from the voxels and, because it comes out stepped, smoothed with `smooth` Taubin
284
+ iterations, which keep the volume and the topology. The mesh is decimated to about `decimate_to`
285
+ faces first, because voxelising a high-resolution mesh is the memory cost and the grid resamples
286
+ the surface anyway. The result is one watertight simple solid; a crisp cut such as a bore or a
287
+ slot is re-cut by the caller afterwards, since the grid fills a gap thinner than its pitch.
288
+
289
+ A hole wider than `pitch` is kept, so a part that is meant to have a hole stays as it is; only the
290
+ tunnels and gaps narrower than the grid go. Needs `scipy`, `scikit-image` and `fast-simplification`.
291
+ """
292
+ from trimesh.voxel import ops as _vops
293
+ from scipy import ndimage as _nd
294
+ if decimate_to and len(mesh.faces) > decimate_to:
295
+ try:
296
+ mesh = mesh.simplify_quadric_decimation(percent=float(decimate_to) / len(mesh.faces))
297
+ except Exception:
298
+ pass
299
+ vg = mesh.voxelized(float(pitch)).fill()
300
+ mat = np.asarray(vg.matrix)
301
+ if close:
302
+ pad = int(close) + 1
303
+ mat = _nd.binary_closing(np.pad(mat, pad), iterations=int(close))[pad:-pad, pad:-pad, pad:-pad]
304
+ out = _vops.matrix_to_marching_cubes(mat)
305
+ out.apply_transform(vg.transform)
306
+ out.merge_vertices()
307
+ out = max(out.split(only_watertight=False), key=lambda b: abs(b.volume))
308
+ out.fix_normals()
309
+ if smooth:
310
+ trimesh.smoothing.filter_taubin(out, iterations=int(smooth))
311
+ return out
312
+
313
+
273
314
  def _seen_from(mesh: trimesh.Trimesh, centre, which, cells: int = 64, batch: int = 4_000_000, skin: float = 0.0):
274
315
  """Which of the faces `which` a ray from `centre` to their middles meets first, or within `skin`
275
316
  of first: a face less than that nearer the centre is a fold or a second copy of the surface.
@@ -0,0 +1,62 @@
1
+ """The nozzle a part is printed with, and the smallest sizes that follow from it.
2
+
3
+ A slicer draws a wall as lines about as wide as the nozzle, and stacks a part in layers of the layer
4
+ height. A feature narrower than two lines prints as one weak, wavy line or not at all, and a plate
5
+ thinner than two layers is a single layer. `Nozzle` holds the nozzle's diameter and the layer height
6
+ and gives every minimum as a count of lines or layers, so a design written against it follows the
7
+ nozzle it is printed with and a check reads the same bars.
8
+
9
+ n = Nozzle(0.4) # a 0.4 mm nozzle at 0.2 mm layers
10
+ n.wall # 0.8, two lines across
11
+ n.plate # 0.4, two layers through
12
+ n.lines(5) # 2.0
13
+ Nozzle(0.2, layer=0.1).wall # 0.4
14
+
15
+ Counts are in nozzle diameters. A slicer's own line is a little wider (about 1.05 times the diameter
16
+ by default, `line_width`), so a size of two diameters always fits two of its lines.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+
22
+ #: a slicer's default extrusion width, as a share of the nozzle's diameter
23
+ LINE_SHARE = 1.05
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Nozzle:
28
+ diameter: float = 0.4
29
+ layer: float = 0.2
30
+
31
+ def __post_init__(self):
32
+ if not (self.diameter > 0 and self.layer > 0):
33
+ raise ValueError(f"a nozzle needs a positive diameter and layer height, not {self}")
34
+ if self.layer > self.diameter:
35
+ raise ValueError(f"a layer of {self.layer} mm is thicker than a {self.diameter} mm nozzle can lay")
36
+
37
+ def lines(self, n: float) -> float:
38
+ """The width of `n` lines side by side, in mm."""
39
+ return round(n * self.diameter, 6)
40
+
41
+ def layers(self, n: float) -> float:
42
+ """The height of `n` layers, in mm."""
43
+ return round(n * self.layer, 6)
44
+
45
+ @property
46
+ def line_width(self) -> float:
47
+ """The width of one line as a slicer draws it by default."""
48
+ return round(LINE_SHARE * self.diameter, 6)
49
+
50
+ @property
51
+ def wall(self) -> float:
52
+ """The thinnest wall that prints as two lines."""
53
+ return self.lines(2)
54
+
55
+ @property
56
+ def plate(self) -> float:
57
+ """The thinnest plate lying flat that prints as two layers."""
58
+ return self.layers(2)
59
+
60
+
61
+ #: the common nozzle, 0.4 mm at 0.2 mm layers
62
+ DEFAULT = Nozzle()
@@ -248,6 +248,7 @@ watertight check says so. Measure it, and measure it the way the part will lie o
248
248
  from base3d import thickness as T
249
249
  spots = T.thin_spots(mesh, bar_mm=0.8) # the places under 0.8 mm, grouped
250
250
  spots = T.print_thin_spots(placed, backed_mm=1.0) # as it lies, +z up, ridges left out
251
+ spots = T.print_thin_spots(placed, nozzle=Nozzle(0.2, layer=0.1)) # the bars of a 0.2 mm nozzle
251
252
  for s in spots:
252
253
  print(s["short_of"], s["typical_width_mm"], s["size_mm"], s["points"])
253
254
  ```
@@ -255,6 +256,10 @@ for s in spots:
255
256
  - Read `typical_mm` and `size_mm` before `mm`. Material really is thin next to a sharp edge, so a
256
257
  place of a few points with a low `mm` is an edge, which printing rounds off. A wall that will fail
257
258
  is large and thin throughout.
259
+ - Write the smallest sizes of a design against a `base3d.Nozzle` (`n.wall` is two lines, `n.plate`
260
+ two layers, `n.lines(k)` and `n.layers(k)` any count), and check with the same nozzle, so the design
261
+ and its check follow the nozzle it is printed with. `3d-base thickness part.stl --printed --nozzle 0.2
262
+ --layer 0.1` checks for a finer nozzle.
258
263
  - Judge the part as it lies. An upright wall needs two lines across a layer (0.8 mm at a 0.4 mm
259
264
  nozzle) and a flat plate needs two layers (0.4 mm at 0.2 mm layers). A 0.45 mm brim fails stood on
260
265
  its edge and passes lying flat, so `thin_spots` on the part as modelled cannot tell you.
@@ -343,6 +348,9 @@ fixed each.
343
348
 
344
349
  ## trimesh calls that cost a build each to learn
345
350
 
351
+ - `mesh.remanifold(mesh)` rebuilds a mesh as one simple solid on a voxel grid, to shed the seam
352
+ tunnels and near-coincident-sheet slivers a boolean leaves (a handle, or a wall thinner than any
353
+ line where two surfaces graze). A hole wider than the pitch is kept; re-cut a bore or a slot after.
346
354
  - A cut half is `trimesh.intersections.slice_mesh_plane(mesh, plane_normal, plane_origin, cap=True)`
347
355
  (there is no `slice_plane`), and capping needs shapely and mapbox-earcut. A cut outline is
348
356
  `mesh.section(plane_origin=, plane_normal=)`, then `.to_planar()` for 2D polygons.
@@ -20,6 +20,7 @@ import numpy as np
20
20
  import trimesh
21
21
 
22
22
  from .mesh import SAMPLE_SEED
23
+ from .nozzle import DEFAULT, Nozzle
23
24
 
24
25
  #: how far inside the surface each ray starts, so it does not hit the face it starts on
25
26
  START_MM = 1e-3
@@ -130,15 +131,19 @@ def _backed(mesh, pts, normals, mm, which, backed_mm, batch=2000):
130
131
 
131
132
 
132
133
  #: a wall inside one layer needs two lines of a 0.4 mm nozzle, and a plate lying flat two 0.2 mm layers
133
- LINE_MM = 0.8
134
- LAYER_MM = 0.4
134
+ LINE_MM = DEFAULT.wall
135
+ LAYER_MM = DEFAULT.plate
135
136
 
136
137
 
137
138
  def print_thin_spots(mesh: trimesh.Trimesh, line_mm: float = LINE_MM, layer_mm: float = LAYER_MM,
138
139
  up=(0.0, 0.0, 1.0), n: int = 4000, seed: int = SAMPLE_SEED,
139
- group_mm: float = 1.5, backed_mm: float | None = None) -> list[dict]:
140
+ group_mm: float = 1.5, backed_mm: float | None = None,
141
+ nozzle: Nozzle | None = None) -> list[dict]:
140
142
  """The places too thin to print, for the part as it lies on the plate, thinnest first.
141
143
 
144
+ `nozzle` sets both bars from the nozzle the part is printed with (its `wall` and `plate`), in
145
+ place of `line_mm` and `layer_mm`.
146
+
142
147
  A slicer cuts the part into layers across `up`, and how much a wall gets depends on which way it
143
148
  faces. A wall standing upright is drawn with lines inside each layer, and needs `line_mm` across
144
149
  (two lines). A plate lying flat is drawn as a stack of layers, and needs `layer_mm` through (two
@@ -157,6 +162,8 @@ def print_thin_spots(mesh: trimesh.Trimesh, line_mm: float = LINE_MM, layer_mm:
157
162
  after leaving it is taken as detail of that kind and left out. A free wall (a shell, a fin, a
158
163
  plate) has open space behind it and stays in.
159
164
  """
165
+ if nozzle is not None:
166
+ line_mm, layer_mm = nozzle.wall, nozzle.plate
160
167
  up = np.asarray(up, float)
161
168
  up = up / float(np.linalg.norm(up))
162
169
  pts, normals, mm = wall_thickness(mesh, n=n, seed=seed)
@@ -285,3 +285,29 @@ def test_a_sliver_just_inside_the_inner_surface_neither_hides_it_nor_stays():
285
285
  assert solid.is_watertight and solid.is_winding_consistent and solid.euler_number == 2
286
286
  assert solid.contains([[0.0, 0.0, 8.9], [0.0, 0.0, 5.0]]).all() # the top is solid through
287
287
  assert abs(solid.volume - 2.0 / 3.0 * np.pi * 1000) < 0.03 * 2094
288
+
289
+
290
+ def _block_with_hole(side, hole, height=4.0):
291
+ # a square block with a square hole through it, built from a polygon with a hole (no boolean
292
+ # backend needed), so it is a genus-1 solid: watertight with a handle
293
+ from shapely.geometry import Polygon
294
+ h, s = hole / 2.0, side / 2.0
295
+ shell = [(-s, -s), (s, -s), (s, s), (-s, s)]
296
+ inner = [(-h, -h), (h, -h), (h, h), (-h, h)]
297
+ return trimesh.creation.extrude_polygon(Polygon(shell, [inner]), height=height)
298
+
299
+
300
+ def test_remanifold_closes_a_sub_pitch_tunnel_to_a_simple_solid():
301
+ from base3d.mesh import remanifold
302
+ holed = _block_with_hole(10.0, 0.3) # a 0.3 mm tunnel through a 10 mm block
303
+ assert holed.euler_number == 0 # genus 1: a handle, not a simple solid
304
+ fixed = remanifold(holed, pitch=0.6, close=1, smooth=0)
305
+ assert fixed.is_watertight and fixed.euler_number == 2 # the sub-pitch tunnel is gone
306
+ assert 400.0 < fixed.volume < 800.0 # voxelising inflates the surface; it never shrinks the solid
307
+
308
+
309
+ def test_remanifold_keeps_a_hole_wider_than_the_pitch():
310
+ from base3d.mesh import remanifold
311
+ frame = _block_with_hole(12.0, 3.0) # a 3 mm hole, far wider than the pitch
312
+ kept = remanifold(frame, pitch=0.6, close=1, smooth=0)
313
+ assert kept.is_watertight and kept.euler_number == 0 # the real hole is still a hole
@@ -0,0 +1,27 @@
1
+ import pytest
2
+ import trimesh
3
+
4
+ from base3d import thickness as T
5
+ from base3d.nozzle import DEFAULT, Nozzle
6
+
7
+
8
+ def test_the_bars_are_counts_of_lines_and_layers():
9
+ assert DEFAULT.wall == 0.8 and DEFAULT.plate == 0.4 and DEFAULT.lines(5) == 2.0
10
+ fine = Nozzle(0.2, layer=0.1)
11
+ assert fine.wall == 0.4 and fine.plate == 0.2 and fine.layers(4) == 0.4
12
+ assert Nozzle(0.6, layer=0.3).line_width == 0.63
13
+
14
+
15
+ def test_a_nozzle_that_cannot_print_is_refused():
16
+ with pytest.raises(ValueError):
17
+ Nozzle(0.0)
18
+ with pytest.raises(ValueError):
19
+ Nozzle(0.2, layer=0.3)
20
+
21
+
22
+ def test_the_check_reads_the_bars_from_the_nozzle():
23
+ # a 0.6 mm wall standing upright is one line of a 0.4 mm nozzle and three of a 0.2 mm nozzle
24
+ wall = trimesh.creation.box(extents=(0.6, 10, 10))
25
+ assert T.print_thin_spots(wall, nozzle=Nozzle(0.4), n=3000)[0]["short_of"] == "lines"
26
+ assert T.print_thin_spots(wall, nozzle=Nozzle(0.2, layer=0.1), n=3000) == []
27
+ assert T.print_thin_spots(wall, n=3000) == T.print_thin_spots(wall, nozzle=DEFAULT, n=3000)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes