Module piecad.utilities

Miscellaneous (but important) functions

Functions

def check_mesh(vertices: list[tuple[float, float, float]], faces: list[tuple[int, int, int]]) ‑> bool
Expand source code
def check_mesh(
    vertices: list[tuple[float, float, float]], faces: list[tuple[int, int, int]]
) -> bool:
    """
    Check manifold rules and winding of the mesh defined in vertices and faces.

    Returns true if all is well. Otherwise diagnostics will be offered and false is returned.
    """
    return _check_mesh(vertices, faces)

Check manifold rules and winding of the mesh defined in vertices and faces.

Returns true if all is well. Otherwise diagnostics will be offered and false is returned.

def frange(start, stop=None, step=1, /, *, inclusive=False) ‑> Iterable[float | int]
Expand source code
def frange(start, stop=None, step=1, /, *, inclusive=False) -> Iterable[float | int]:
    """
    Generate a range of numbers. Like the built-in `range` but supports `float` values.

    If inclusive is `True`, the stop value is included in the range if it falls on a step.
    """
    if stop is None:
        start, stop = 0, start

    if not all(isinstance(value, (int, float)) for value in (start, stop, step)):
        raise TypeError("frange arguments must be integers or floats")
    if step == 0:
        raise ValueError("frange() step must not be zero")

    if all(isinstance(value, int) for value in (start, stop, step)):
        if inclusive:
            stop += 1 if step > 0 else -1
        return range(start, stop, step)

    start, stop, step = float(start), float(stop), float(step)
    if not all(math.isfinite(value) for value in (start, stop, step)):
        raise ValueError("frange arguments must be finite")

    if inclusive:
        distance = (stop - start) / step
        count = (
            math.floor(math.nextafter(distance, math.inf)) + 1 if distance >= 0 else 0
        )

        def values():
            previous = None
            for i in range(count):
                value = start + i * step
                if i and value == previous:
                    raise ValueError("frange() step is too small to advance")
                yield value
                previous = value

        return values()

    def values():
        value = start
        i = 0
        while value < stop if step > 0 else value > stop:
            yield value
            i += 1
            next_value = start + i * step
            if next_value == value:
                raise ValueError("frange() step is too small to advance")
            value = next_value

    return values()

Generate a range of numbers. Like the built-in range but supports float values.

If inclusive is True, the stop value is included in the range if it falls on a step.

def load(filename: str, *, svg_openscad: bool = False, center: bool = False) ‑> Obj2d | Obj3d
Expand source code
def load(
    filename: str, *, svg_openscad: bool = False, center: bool = False
) -> Obj3d | Obj2d:
    """
    Load a 3D or 2D object from a file.

    The format read from `filename` is determined by the file's extension.

    The available formats for 3D are:

    | Type        | Extension    |
    |:------------|:------------:|
    | 3MF         |   .3mf       |
    | GLB         |   .glb       |
    | GLTF        |   .gltf      |
    | OBJ         |   .obj       |
    | OFF         |   .off       |
    | PLY         |   .ply       |
    | STL         |   .stl_ascii |
    | STL binary  |   .stl       |

    \\(See [https://github/mikedh/trimesh] for more formats.\\)

    3MF build items and components are imported as geometry. Coordinates are
    kept in the file's units; colors and materials are not imported.

    OBJ imports preserve flat MTL diffuse colors on faces. Texture images and
    transparency are not imported. Materials without a supported color use
    the default color. Only one material library is supported; unsupported
    or missing material data produces a warning.

    OFF imports preserve flat face colors. Vertex colors and transparency are
    not imported. Polygon faces use Trimesh's fan triangulation, which may
    produce incorrect results for concave faces.

    For 2D, SVG (.svg) and DXF (.dxf) files are loaded with even-odd fill.
    SVG coordinates are used as-is and open SVG subpaths are implicitly closed.
    Only explicitly closed DXF polylines are filled. SVG and DXF imports
    support the same elements and limitations as `Path.from_svg` and
    `Path.from_dxf`, respectively.

    Set `svg_openscad=True` to use OpenSCAD 2021.01's SVG coordinate,
    open-path stroke, and per-element union conventions instead. This mode
    ignores visual styling except stroke width, line caps and joins; it does
    not support non-path shapes or visible `<use>` references.
    Set `center=True` to center the imported geometry. For OpenSCAD SVG mode,
    centering follows OpenSCAD's viewBox handling.
    """
    dot_idx = filename.rindex(".")
    ext = filename[dot_idx + 1 :]
    if ext.lower() in ("svg", "dxf"):
        from ._path import Path, _load_svg_openscad

        if ext.lower() == "svg":
            if svg_openscad:
                return _load_svg_openscad(filename, center=center)
            result = Path.from_svg(filename).to_obj2d(include_open=True)
        else:
            result = Path.from_dxf(filename).to_obj2d()
        return result.center() if center else result
    if ext.lower() == "obj":
        from ._obj import load_obj as _load_obj

        result = _load_obj(filename)
        if result is not None:
            return result.center() if center else result
    if ext.lower() == "off":
        from ._off import load_off as _load_off

        result = _load_off(filename)
        if result is not None:
            return result.center() if center else result
    if ext.lower() == "3mf":
        mesh = _load_3mf_mesh(filename)
    else:
        mesh = trimesh.exchange.load.load(
            filename, ext, force="mesh", process=True, validate=False
        )
    if type(mesh) == trimesh.path.Path2D:
        raise ValidationError("Only .svg, .dxf 2D objects are currently supported.")

    result = obj3d_from_v_and_f(mesh.vertices, mesh.faces)
    return result.center() if center else result

Load a 3D or 2D object from a file.

The format read from filename is determined by the file's extension.

The available formats for 3D are:

Type Extension
3MF .3mf
GLB .glb
GLTF .gltf
OBJ .obj
OFF .off
PLY .ply
STL .stl_ascii
STL binary .stl

(See [https://github/mikedh/trimesh] for more formats.)

3MF build items and components are imported as geometry. Coordinates are kept in the file's units; colors and materials are not imported.

OBJ imports preserve flat MTL diffuse colors on faces. Texture images and transparency are not imported. Materials without a supported color use the default color. Only one material library is supported; unsupported or missing material data produces a warning.

OFF imports preserve flat face colors. Vertex colors and transparency are not imported. Polygon faces use Trimesh's fan triangulation, which may produce incorrect results for concave faces.

For 2D, SVG (.svg) and DXF (.dxf) files are loaded with even-odd fill. SVG coordinates are used as-is and open SVG subpaths are implicitly closed. Only explicitly closed DXF polylines are filled. SVG and DXF imports support the same elements and limitations as Path.from_svg and Path.from_dxf, respectively.

Set svg_openscad=True to use OpenSCAD 2021.01's SVG coordinate, open-path stroke, and per-element union conventions instead. This mode ignores visual styling except stroke width, line caps and joins; it does not support non-path shapes or visible <use> references. Set center=True to center the imported geometry. For OpenSCAD SVG mode, centering follows OpenSCAD's viewBox handling.

def near_eq(a, b, epsilon=1e-12) ‑> bool
Expand source code
def near_eq(a, b, epsilon=Const.epsilon) -> bool:
    """
    If `a` is near `b` (within epsilon) then return True` else `return False`
    """
    return abs(a - b) <= epsilon

If a is near b (within epsilon) then return True else return False`

def near_ge(a, b, epsilon=1e-12) ‑> bool
Expand source code
def near_ge(a, b, epsilon=Const.epsilon) -> bool:
    """
    If `a - epsilon` is greater than or equal to `b` then `return True` else `return False`
    """
    return a - epsilon >= b

If a - epsilon is greater than or equal to b then return True else return False

def near_le(a, b, epsilon=1e-12) ‑> bool
Expand source code
def near_le(a, b, epsilon=Const.epsilon) -> bool:
    """
    If `a + epsilon` is less than or equal to `b` then `return True` else `return False`
    """
    return a + epsilon <= b

If a + epsilon is less than or equal to b then return True else return False

def quick_check_mesh(vertices: list[tuple[float, float, float]], faces: list[tuple[int, int, int]]) ‑> str
Expand source code
def quick_check_mesh(
    vertices: list[tuple[float, float, float]], faces: list[tuple[int, int, int]]
) -> str:
    """
    Same checking as check_mesh, but no advice is offered

    Returns an empty string `""` if all is well, otherwise a short string describing the problem is
    returned.
    """
    return _quick_check_mesh(vertices, faces)

Same checking as check_mesh, but no advice is offered

Returns an empty string "" if all is well, otherwise a short string describing the problem is returned.

def register_decorator_for_edge_modification(decorator_name: str,
func: Callable[..., tuple[Obj3d, Obj3d]]) ‑> None
Expand source code
def register_decorator_for_edge_modification(
    decorator_name: str, func: Callable[..., tuple[Obj3d, Obj3d]]
) -> None:
    """Register or replace a named corner decorator.

    The function receives a corner and its three `(edge, profile)` pairs,
    followed by the keyword arguments `original`, `modified`, `size`,
    `overhang`, `flip_on_top`, and `segments`. It returns two world-space
    `Obj3d` objects: the region to remove and the replacement to add.
    When `flip_on_top` is omitted, the decorator receives `False` if any
    corner edge uses `comma`, and `True` otherwise.
    """
    from ._edge_modification import (
        register_decorator_for_edge_modification as _register,
    )

    _register(decorator_name, func)

Register or replace a named corner decorator.

The function receives a corner and its three (edge, profile) pairs, followed by the keyword arguments original, modified, size, overhang, flip_on_top, and segments. It returns two world-space Obj3d objects: the region to remove and the replacement to add. When flip_on_top is omitted, the decorator receives False if any corner edge uses comma, and True otherwise.

def register_profile_for_edge_modification(profile_name: str,
func_3d: Callable[..., Obj3d] | None,
func_2d: Callable[..., Obj2d] | None) ‑> None
Expand source code
def register_profile_for_edge_modification(
    profile_name: str,
    func_3d: Callable[..., Obj3d] | None,
    func_2d: Callable[..., Obj2d] | None,
) -> None:
    """Register or replace a named edge profile.

    The 3D function is called with `edge` and the keywords `size`, `overhang`,
    `flip_on_top`, and `segments`. It returns a cutter along local X, centered
    on X=0, with its cross-section in local Y/Z. The 2D function receives
    `size`, `overhang`, and `segments`. Either function may be None, but not both. See
    [EdgeModification.md](https://github.com/briansturgill/Piecad/blob/main/EdgeModification.md)
    for profile geometry and an example.
    When `flip_on_top` is omitted, 3D profiles receive `False` for `comma`
    and `True` for other profile names.
    """
    from ._edge_modification import register_profile_for_edge_modification as _register

    _register(profile_name, func_3d, func_2d)

Register or replace a named edge profile.

The 3D function is called with edge and the keywords size, overhang, flip_on_top, and segments. It returns a cutter along local X, centered on X=0, with its cross-section in local Y/Z. The 2D function receives size, overhang, and segments. Either function may be None, but not both. See EdgeModification.md for profile geometry and an example. When flip_on_top is omitted, 3D profiles receive False for comma and True for other profile names.

def save(filename: str,
*objs: Obj2d | Obj3d) ‑> None
Expand source code
def save(filename: str, *objs: Obj3d | Obj2d) -> None:
    """
    Save a 3d or 2d object in a file suitable for printing, etc.

    If [p filename] does not contain a path separator character (`'/'` or `'\\'`) the
    `Downloads` directory for your platform is prepended. Thus if you set
    [p filename] to `output.obj`, the place where the file is saved is
    `c:\\Users\\username\\Downloads\\output.obj` on Windows or
    `/home/username/Downloads/output.obj` on Linux and MacOS.
    If you want a file saved in the current directory, prepend `'./'` or `'.\\'`.

    You can override the `Downloads` directory by setting the global environment variable
    `PIECAD_SAVE_DIR`.

    The model format placed in [p:filename] is determined by the file's extension.

    The available formats for 3D are:

    | Type        | Extension    |
    |:------------|:------------:|
    | 3MF         |   .3mf       |
    | GLB         |   .glb       |
    | GLTF        |   .gltf      |
    | OBJ         |   .obj       |
    | OFF         |   .off       |
    | PLY         |   .ply       |
    | STL         |   .stl_ascii |
    | STL binary  |   .stl       |

    \\(See [https://github/mikedh/trimesh] for more formats.\\)

    For 2D, the SVG (.svg) and DXF (.dxf) formats are available.
    OBJ exports include an accompanying MTL file when any exported face has
    an explicit color. Keep the OBJ and MTL files together. GLB and GLTF
    exports do not include colors. OFF exports include flat face colors when
    any exported face has an explicit color.
    When saving multiple 3D objects to 3MF, each is a separate build item.
    """

    if filename.find("/") == -1 and filename.find("\\") == -1:
        filename = str(_Path(_get_save_dir()) / filename)
        print("Saving: " + filename)
    _chkGE("len(objs)", len(objs), 1)
    dot_idx = filename.rindex(".")
    ext = filename[dot_idx + 1 :]
    if type(objs[0]) == Obj3d:
        if ext.lower() == "off":
            from ._off import save_off as _save_off

            _save_off(filename, objs)
            return
        if ext.lower() == "obj":
            from ._obj import save_obj as _save_obj

            if _save_obj(filename, objs, _face_colors):
                return
        if ext.lower() == "3mf":
            _export_3mf(
                filename,
                [obj.mo for obj in objs],
                Obj3d.color_map,
                Config.get_default_units(),
                Config.get_default_color(),
            )
            return
        include_face_colors = ext.lower() not in (
            "obj",
            "glb",
            "gltf",
            "stl",
            "stl_ascii",
        )
        if len(objs) == 1:
            obj = objs[0]
            mesh = obj.mo.to_mesh64()
            if mesh.vert_properties.shape[1] > 3:
                vertices = mesh.vert_properties[:, :3]
            else:
                vertices = mesh.vert_properties

            if include_face_colors:
                face_colors = _face_colors(mesh)
                vertex_colors = None
            else:
                def_color = Config.get_default_color() + (255,)
                vertex_colors = (
                    None
                    if include_face_colors
                    else [def_color for _ in range(len(vertices))]
                )
                face_colors = None
            mesh_output = trimesh.Trimesh(
                vertices=vertices,
                faces=mesh.tri_verts,
                face_colors=face_colors,
                vertex_colors=vertex_colors,
                process=True,
                validate=False,
            )
            # Manifold3d has a different definition than Trimesh
            if not mesh_output.is_watertight:
                print("WARNING: output mesh is not watertight")
            trimesh.exchange.export.export_mesh(mesh_output, filename, ext)
        else:
            scene = trimesh.Scene()
            for obj in objs:
                mesh = obj.mo.to_mesh64()
                if mesh.vert_properties.shape[1] > 3:
                    vertices = mesh.vert_properties[:, :3]
                else:
                    vertices = mesh.vert_properties
                face_colors = _face_colors(mesh) if include_face_colors else None
                mesh_output = trimesh.Trimesh(
                    vertices=vertices,
                    faces=mesh.tri_verts,
                    face_colors=face_colors,
                    process=True,
                    validate=False,
                )
                # Manifold3d has a different definition than Trimesh
                if not mesh_output.is_watertight:
                    print("WARNING: output mesh is not watertight")
                scene.add_geometry(mesh_output)
            if ext.lower() == "ply":
                mesh_output = trimesh.util.concatenate(list(scene.geometry.values()))
                trimesh.exchange.export.export_mesh(mesh_output, filename, ext)
            else:
                trimesh.exchange.export.export_scene(scene, filename, ext)
        # trimesh obj file export does not end with newline
        # currently this upsets prusa_slicer
        if ext == "obj":
            with open(filename, "a") as f:
                f.write("\n")
    else:  # Obj2d
        if ext == "svg":
            _save_svg(filename, *objs)
        elif ext == "dxf":
            _save_dxf(filename, *objs)
        else:
            raise ValidationError(
                "Only the SVG and DXF formats are supported for Obj2d."
            )

Save a 3d or 2d object in a file suitable for printing, etc.

If [p filename] does not contain a path separator character ('/' or '\') the Downloads directory for your platform is prepended. Thus if you set [p filename] to output.obj, the place where the file is saved is c:\Users\username\Downloads\output.obj on Windows or /home/username/Downloads/output.obj on Linux and MacOS. If you want a file saved in the current directory, prepend './' or '.\'.

You can override the Downloads directory by setting the global environment variable PIECAD_SAVE_DIR.

The model format placed in [p:filename] is determined by the file's extension.

The available formats for 3D are:

Type Extension
3MF .3mf
GLB .glb
GLTF .gltf
OBJ .obj
OFF .off
PLY .ply
STL .stl_ascii
STL binary .stl

(See [https://github/mikedh/trimesh] for more formats.)

For 2D, the SVG (.svg) and DXF (.dxf) formats are available. OBJ exports include an accompanying MTL file when any exported face has an explicit color. Keep the OBJ and MTL files together. GLB and GLTF exports do not include colors. OFF exports include flat face colors when any exported face has an explicit color. When saving multiple 3D objects to 3MF, each is a separate build item.

def sign(x: float | int) ‑> float | int
Expand source code
def sign(x: float | int) -> float | int:
    """
    Common math utility function, missing from Python.
    Evaluate `x`, if `x` < 0 return -1, or if `x` == 0 return 0 or if `x` > 0 return 1.
    """
    return (x > 0) - (x < 0)

Common math utility function, missing from Python. Evaluate x, if x < 0 return -1, or if x == 0 return 0 or if x > 0 return 1.

def view(obj: Obj2d | Obj3d,
title: str = '') ‑> None
Expand source code
def view(obj: Obj3d | Obj2d, title: str = "") -> None:
    """
    Use `Piecad-Viewer` to display the geometry object.

    Returns obj unchanged... so that it works well in return statements.

    If you have trouble viewing and are using a graphical debugger,
    see the `view_all_now()` function below.

    ```
    return union(o1, o2, o3)
    # can be displayed in 3 parts and the whole object, like this:
    return view(union(view(o1), view(o2), view(o3)))
    ```

    """
    global _view_meshes, _view_meshes_titles

    _chkGO("obj", obj)

    if title == "":
        title = _info_str("view")

    if type(obj) == Obj2d:
        color = obj._color if obj._color is not None else Config.get_default_color()
        obj = Obj3d(_m.Manifold.extrude(obj.mo, 0.1)).color(color)

    mesh = obj.mo.to_mesh64()
    if mesh.vert_properties.shape[1] > 3:
        vertices = mesh.vert_properties[:, :3]
    else:
        vertices = mesh.vert_properties
    faces = mesh.tri_verts
    mesh_output = trimesh.Trimesh(
        vertices=vertices,
        faces=faces,
        face_colors=_face_colors(mesh),
        process=True,
        validate=False,
    )
    if len(_view_meshes) == 0:
        atexit.register(_wait_for_view_handler_exit)
    _view_meshes.append(mesh_output)
    _view_meshes_titles.append(title)
    return obj

Use Piecad-Viewer to display the geometry object.

Returns obj unchanged… so that it works well in return statements.

If you have trouble viewing and are using a graphical debugger, see the view_all_now() function below.

return union(o1, o2, o3)
# can be displayed in 3 parts and the whole object, like this:
return view(union(view(o1), view(o2), view(o3)))
def view_all_now() ‑> None
Expand source code
def view_all_now() -> None:
    """
    The `view()` function merely records a list of objects to be displayed.
    By default, a function to view the meshes is called from `atexit`.
    Unfortunately a number of graphical debuggers (e.g. Visual Studio Code
    and PyCharm) have a short timeout for `atexit` functions.
    To avoid this issue, use `view_all_now()` at the end of your script to
    display all objects recorded by `view()` with no timeout.
    Alternatively, run the script without debugging.
    """
    from ._viewer import show_meshes

    v = show_meshes(_view_meshes, _view_meshes_titles)
    _viewer_closed_event.wait()
    v.clear()
    _view_meshes.clear()
    _view_meshes_titles.clear()
    _viewer_closed_event.clear()

The view() function merely records a list of objects to be displayed. By default, a function to view the meshes is called from atexit. Unfortunately a number of graphical debuggers (e.g. Visual Studio Code and PyCharm) have a short timeout for atexit functions. To avoid this issue, use view_all_now() at the end of your script to display all objects recorded by view() with no timeout. Alternatively, run the script without debugging.

def winding(lt: list[tuple[float, float]]) ‑> str
Expand source code
def winding(lt: list[tuple[float, float]]) -> str:
    """
    String description of winding of a 2D polygon.

    Returns one of `"cw"`, `"ccw"`, `"zero"` or `"too small"`.
    """

    def wstr(winding):
        if winding > 0:
            return "cw"
        if winding < 0:
            return "ccw"
        return "zero"

    length = len(lt)
    if length < 3:
        return "too small"
    winding = 0.0
    for i in range(0, length):
        winding += (lt[(i + 1) % length][0] - lt[i][0]) * (
            lt[(i + 1) % length][1] + lt[i][1]
        )
    return wstr(winding)

String description of winding of a 2D polygon.

Returns one of "cw", "ccw", "zero" or "too small".