Source code for pyvcad_rendering.profile_plot

"""Quick 2D plots of profiles, sketches and curves, for checking a sketch before turning it into a solid."""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch

import pyvcad as pv

# Outline colours for successive items when several are plotted together.
_COLORS = ("#1f5fa8", "#c4512b", "#2e8b57", "#8a4fb8", "#b8860b", "#00838f")
_HOLE_COLOR = "#7a7a7a"


def _curve_points(curve, tolerance):
    """Tessellate a curve in the XY plane to an (N, 2) array; closed curves repeat their first point."""
    points = np.asarray(curve.tessellate(tolerance))[:, :2]
    if curve.is_closed:
        points = np.vstack([points, points[:1]])
    return points


def _loop_tolerance(size):
    return max(size, 1e-9) * 2e-4


def _draw_direction(ax, points, color):
    """An arrowhead halfway along a polyline, pointing the way it runs."""
    lengths = np.cumsum(np.linalg.norm(np.diff(points, axis=0), axis=1))
    if len(lengths) == 0 or lengths[-1] <= 0.0:
        return
    i = int(np.searchsorted(lengths, 0.5 * lengths[-1]))
    i = min(i, len(points) - 2)
    a, b = points[i], points[i + 1]
    if np.allclose(a, b):
        return
    ax.annotate("", xy=b, xytext=a, arrowprops=dict(arrowstyle="-|>", color=color, lw=1.2, mutation_scale=14))


def _plot_profile(ax, profile, color, fill, show_corners, corner_angle, show_direction, label):
    loops = profile.loops
    if not loops:
        return
    low, high = profile.bounding_box()
    tolerance = _loop_tolerance(float(np.linalg.norm(np.asarray(high) - np.asarray(low))))

    # One compound path: outlines run counter-clockwise and holes clockwise, so the non-zero rule fills
    # the material and leaves the holes empty.
    vertices = []
    codes = []
    outlines = []
    for index, loop in enumerate(loops):
        points = _curve_points(loop, tolerance)
        outlines.append((points, profile.is_hole(index)))
        vertices.extend(points)
        codes.extend([Path.MOVETO] + [Path.LINETO] * (len(points) - 2) + [Path.CLOSEPOLY])
    if fill:
        patch = PathPatch(Path(np.asarray(vertices), codes), facecolor=color, alpha=0.18, edgecolor="none")
        ax.add_patch(patch)

    for n, (points, hole) in enumerate(outlines):
        outline_color = _HOLE_COLOR if hole else color
        ax.plot(points[:, 0], points[:, 1], color=outline_color, lw=1.6, linestyle="--" if hole else "-",
                label=label if n == 0 else None)
        if show_direction:
            _draw_direction(ax, points, outline_color)

    if show_corners:
        corners = np.asarray(profile.corners(corner_angle))
        if len(corners):
            ax.plot(corners[:, 0], corners[:, 1], "o", ms=4.5, mfc="white", mec=color, mew=1.2, zorder=5)


def _plot_curve(ax, curve, color, show_direction, label):
    low, high = curve.bounding_box()
    tolerance = _loop_tolerance(float(np.linalg.norm(np.asarray(high) - np.asarray(low))))
    points = _curve_points(curve, tolerance)
    ax.plot(points[:, 0], points[:, 1], color=color, lw=1.6, label=label)
    if not curve.is_closed:
        ax.plot(points[[0, -1], 0], points[[0, -1], 1], "s", ms=4.5, color=color, zorder=5)
    if show_direction:
        _draw_direction(ax, points, color)


def _items(item):
    """Flatten the argument into (kind, object) pairs: profiles, and curves (from sketches too)."""
    if isinstance(item, (list, tuple)):
        result = []
        for child in item:
            result.extend(_items(child))
        return result
    if isinstance(item, pv.Profile):
        return [("profile", item)]
    if isinstance(item, pv.Polygon2):
        return [("profile", pv.Profile(item))]
    if isinstance(item, pv.Sketch):
        # A sketch whose paths are all closed draws as its profile (holes filled correctly); otherwise as curves.
        try:
            return [("profile", item.profile())]
        except RuntimeError:
            return [("curve", curve) for curve in item.curves()]
    if isinstance(item, pv.Curve):
        return [("curve", item)]
    raise TypeError(f"plot_profile() draws Profile, Polygon2, Sketch and Curve objects, not {type(item).__name__}")


[docs] def plot_profile(profile, ax=None, show=True, filename=None, fill=True, show_corners=True, corner_angle=5.0, show_direction=True, title=None, labels=None, dpi=200): """Plots profiles, sketches and curves in 2D, to check a sketch before turning it into a solid. Outlines are solid lines and holes dashed grey lines, each with an arrowhead showing which way it runs (outlines counter-clockwise, holes clockwise). The material is shaded, and the corners that ``fillet()`` and ``chamfer()`` can pick are marked with open circles. Open curves (a sketch with an unclosed path, or a sweep path) are drawn as lines with square end markers. Args: profile: What to draw: a Profile, Polygon2, Sketch or Curve, or a list of them to overlay in different colours. ax (matplotlib.axes.Axes, optional): Axes to draw into. Defaults to a new figure. show (bool, optional): Whether to display the plot window. Defaults to True; set to False in headless scripts, for example together with ``filename``. filename (str, optional): Save the figure to this image file (PNG, SVG, PDF, ...). fill (bool, optional): Shade the material of profiles. Defaults to True. show_corners (bool, optional): Mark the corners of profiles. Defaults to True. corner_angle (float, optional): Mark only corners where the outline turns by more than this many degrees, so the vertices of a polygon approximation (an offset can be one) are not marked. Defaults to 5. show_direction (bool, optional): Draw an arrowhead on each loop and curve. Defaults to True. title (str, optional): The plot title. Defaults to a summary of the first profile (loops, holes, area). labels (list[str], optional): Legend labels, one per item drawn. dpi (int, optional): Resolution used when saving to ``filename``. Defaults to 200. Returns: A tuple of the matplotlib figure and axes holding the plot. """ items = _items(profile) if not items: raise ValueError("plot_profile() needs at least one profile, sketch or curve to draw") if labels is not None and len(labels) != len(items): raise ValueError(f"plot_profile() got {len(labels)} labels for {len(items)} items") if ax is None: fig, ax = plt.subplots(figsize=(7, 6)) else: fig = ax.figure for n, (kind, item) in enumerate(items): color = _COLORS[n % len(_COLORS)] label = labels[n] if labels is not None else None if kind == "profile": _plot_profile(ax, item, color, fill, show_corners, corner_angle, show_direction, label) else: _plot_curve(ax, item, color, show_direction, label) if title is None: first = next((item for kind, item in items if kind == "profile"), None) if first is not None: holes = sum(1 for i in range(len(first.loops)) if first.is_hole(i)) title = f"{len(first.loops)} loop(s), {holes} hole(s), area {first.area():.4g}" else: title = f"{len(items)} curve(s)" ax.set_title(title) ax.set_aspect("equal", adjustable="datalim") ax.autoscale_view() ax.grid(True, color="#d9d9d9", lw=0.6) ax.set_axisbelow(True) ax.set_xlabel("x") ax.set_ylabel("y") if labels is not None: ax.legend(loc="best", frameon=False) if filename is not None: fig.savefig(filename, dpi=dpi, bbox_inches="tight") if show: plt.show() return fig, ax
__all__ = ["plot_profile"]