feat(inspect): render inspect.brep with the software renderer; drop VTK
Entity-map callouts re-anchor onto their own geometry when occluded; the VTK dependency, worker process and xvfb steps are gone. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -74,15 +74,13 @@ jobs:
|
||||
|
||||
- name: Install locked dependencies and build the C++ module
|
||||
run: CMAKE_ARGS="-DSCAD_OCCT_PREFIX=$HOME/occt" uv sync --locked --group dev
|
||||
- name: Verify headless rendering support
|
||||
run: command -v xvfb-run
|
||||
|
||||
|
||||
- name: Compile package
|
||||
run: uv run python -m compileall -q src/simplecadapi
|
||||
|
||||
- name: Run tests
|
||||
run: xvfb-run --auto-servernum uv run pytest test tests -q
|
||||
run: uv run pytest test tests -q
|
||||
|
||||
editor-e2e:
|
||||
needs: occt
|
||||
|
||||
@@ -309,13 +309,10 @@ jobs:
|
||||
uv sync --locked --group dev --no-install-project
|
||||
uv pip install --no-deps dist/*-"$py"-"$py"-*.whl
|
||||
|
||||
- name: Install headless rendering support
|
||||
run: sudo apt-get update && sudo apt-get install --yes xvfb
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
xvfb-run --auto-servernum .venv/bin/python -m pytest test tests -q
|
||||
xvfb-run --auto-servernum .venv/bin/python -m pytest src/cpp/tests/python -q
|
||||
.venv/bin/python -m pytest test tests -q
|
||||
.venv/bin/python -m pytest src/cpp/tests/python -q
|
||||
|
||||
release:
|
||||
name: Build the skill and publish the release
|
||||
|
||||
@@ -249,12 +249,7 @@ both models to the union of their bounds so independent camera fitting cannot
|
||||
hide size or placement differences. The rendered image remains diagnostic and
|
||||
does not replace the strict BREP gate.
|
||||
|
||||
On macOS the render functions offload drawing to an isolated worker process
|
||||
that may hit a rare native VTK crash under heavy system load. The SDK already
|
||||
retries such failures internally; if a render call still raises, the error is
|
||||
transient — retry the same call (ideally after a few seconds or once
|
||||
CPU-heavy work has finished). It does not mean the render interface is broken
|
||||
or unusable.
|
||||
The render functions draw with the SDK's own software renderer: they need no GPU, display server or VTK, and run in the calling process.
|
||||
|
||||
After `compare_steps_rbrepcomparison(...)`, use
|
||||
`comparison.to_error_summary()` to collect every failed validity, bounds,
|
||||
|
||||
@@ -42,8 +42,8 @@ The models computed are the same (volumes agree to 1e-12 relative).
|
||||
* Removed dependencies: `cadquery-ocp`, `ocp-gordon`, `py-slvs`. The OpenCASCADE view of a shape
|
||||
(`shape.wrapped`) is now the module's own binding, `simplecadapi._cpp.occt`, laid out like OCP.
|
||||
* `SCA_BACKEND` is gone: there is one backend.
|
||||
* BREP rendering through VTK is part of the `inspect` extra (`pip install "simplecadapi[inspect]"`); `cadquery-ocp` used
|
||||
to bring VTK in, so it is no longer installed by default.
|
||||
* `simplecadapi.inspect.brep` renders with the same software renderer as `render_screenshot_rpath`: no VTK, no GPU,
|
||||
no display server (no `xvfb`). The `inspect` extra is just `matplotlib`.
|
||||
|
||||
## Errors
|
||||
|
||||
|
||||
@@ -38,8 +38,7 @@ macOS Intel、musl Linux、Windows ARM 没有预编译包;这些平台由源
|
||||
* 移除的依赖:`cadquery-ocp`、`ocp-gordon`、`py-slvs`。形状的 OpenCASCADE 视图(`shape.wrapped`)现在是模块自带的绑定
|
||||
`simplecadapi._cpp.occt`,布局与 OCP 相同。
|
||||
* `SCA_BACKEND` 已删除:只有一个后端。
|
||||
* 通过 VTK 的 BREP 渲染归入 `inspect` 额外依赖(`pip install "simplecadapi[inspect]"`);原来 `cadquery-ocp` 会顺带装上 VTK,
|
||||
现在默认不再安装。
|
||||
* `simplecadapi.inspect.brep` 使用与 `render_screenshot_rpath` 相同的软渲染:不依赖 VTK、GPU 和显示服务(无需 `xvfb`)。`inspect` 额外依赖只剩 `matplotlib`。
|
||||
|
||||
## 报错
|
||||
|
||||
|
||||
@@ -55,8 +55,6 @@ editor = [
|
||||
]
|
||||
inspect = [
|
||||
"matplotlib>=3.7.0",
|
||||
# BREP rendering (simplecadapi.inspect.brep): cadquery-ocp used to bring VTK in
|
||||
"vtk>=9.3",
|
||||
]
|
||||
whucad = [
|
||||
"h5py>=3.8",
|
||||
@@ -157,7 +155,6 @@ dev = [
|
||||
"matplotlib>=3.10.8",
|
||||
"numpy-stl>=3.2.0",
|
||||
"trimesh>=4.11.3",
|
||||
"vtk>=9.3",
|
||||
"datamodel-code-generator==0.32.0",
|
||||
"ty>=0.0.18",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
"""The BREP-inspection pictures, drawn on the C++ software renderer: no VTK, no GPU, no display.
|
||||
|
||||
The geometry of a picture is plain NumPy data (:class:`MeshData`, :class:`LineData`, :class:`PointData`); ``render_views``
|
||||
puts it in a ``simplecadapi._cpp.RenderScene`` (shaded surfaces with per-triangle colours, ink-width BREP edges,
|
||||
highlight groups, points), asks the renderer for the panels, and lays the text over them with Pillow: titles, legend,
|
||||
axis letters and the callouts with their leader lines. A callout whose anchor is hidden in a panel is moved to the
|
||||
nearest visible pixel of the geometry it points at (the id buffer of the renderer says which pixels those are).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
import numpy as np
|
||||
|
||||
_STANDARD_BASE = (0.55, 0.64, 0.73)
|
||||
_STUDIO_BASE = (0.66, 0.68, 0.72)
|
||||
_EDGE_INK = (0.16, 0.21, 0.27)
|
||||
_HIGHLIGHT_SURFACE = (0.94, 0.18, 0.30)
|
||||
_HIGHLIGHT_LINE = (0.78, 0.0, 0.0)
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class MeshData:
|
||||
"""Triangles with per-vertex normals; ``colors`` is an optional (triangles, 4) uint8 RGBA, one colour per triangle."""
|
||||
|
||||
points: np.ndarray
|
||||
normals: np.ndarray
|
||||
triangles: np.ndarray
|
||||
colors: np.ndarray | None = None
|
||||
|
||||
@property
|
||||
def triangle_count(self) -> int:
|
||||
return int(len(self.triangles))
|
||||
|
||||
def bounds(self) -> tuple[float, float, float, float, float, float]:
|
||||
low, high = self.points.min(axis=0), self.points.max(axis=0)
|
||||
return (float(low[0]), float(high[0]), float(low[1]), float(high[1]), float(low[2]), float(high[2]))
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class LineData:
|
||||
"""Polylines: ``starts`` are offsets into ``points``, ``len(lines) + 1`` of them (polyline ``k`` is
|
||||
``points[starts[k]:starts[k + 1]]``; the last offset is the number of points)."""
|
||||
|
||||
points: np.ndarray
|
||||
starts: np.ndarray
|
||||
|
||||
@property
|
||||
def line_count(self) -> int:
|
||||
return int(len(self.starts)) - 1
|
||||
|
||||
def bounds(self) -> tuple[float, float, float, float, float, float]:
|
||||
low, high = self.points.min(axis=0), self.points.max(axis=0)
|
||||
return (float(low[0]), float(high[0]), float(low[1]), float(high[1]), float(low[2]), float(high[2]))
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class PointData:
|
||||
points: np.ndarray
|
||||
|
||||
@property
|
||||
def point_count(self) -> int:
|
||||
return int(len(self.points))
|
||||
|
||||
def bounds(self) -> tuple[float, float, float, float, float, float]:
|
||||
low, high = self.points.min(axis=0), self.points.max(axis=0)
|
||||
return (float(low[0]), float(high[0]), float(low[1]), float(high[1]), float(low[2]), float(high[2]))
|
||||
|
||||
|
||||
def _rgb8(color: Sequence[float]) -> tuple[int, int, int]:
|
||||
return tuple(int(round(255 * float(v))) for v in color[:3]) # type: ignore[return-value]
|
||||
|
||||
|
||||
def _add_mesh(scene, mesh: MeshData, color: Sequence[float], opacity: float, *, studio: bool) -> int:
|
||||
triangles = np.ascontiguousarray(mesh.triangles, dtype=np.uint32)
|
||||
if mesh.colors is not None:
|
||||
# one "face" per triangle: the renderer colours by face id
|
||||
face_ids = np.arange(len(triangles), dtype=np.uint32)
|
||||
face_colors = np.ascontiguousarray(mesh.colors, dtype=np.float32) / 255.0
|
||||
else:
|
||||
face_ids = np.zeros(len(triangles), dtype=np.uint32)
|
||||
face_colors = None
|
||||
return scene.add_mesh_arrays(
|
||||
np.ascontiguousarray(mesh.points, dtype=np.float32),
|
||||
np.ascontiguousarray(mesh.normals, dtype=np.float32),
|
||||
triangles,
|
||||
face_ids,
|
||||
color=tuple(float(v) for v in color),
|
||||
opacity=float(opacity),
|
||||
studio_material=studio,
|
||||
lit=True,
|
||||
face_colors=face_colors,
|
||||
)
|
||||
|
||||
|
||||
def _add_lines(scene, lines: LineData, color, *, ink: bool, width_px: float | None) -> int:
|
||||
return scene.add_polylines(
|
||||
np.ascontiguousarray(lines.points, dtype=np.float32),
|
||||
np.ascontiguousarray(lines.starts, dtype=np.uint32),
|
||||
color=tuple(float(v) for v in color),
|
||||
ink=ink,
|
||||
width_px=width_px,
|
||||
)
|
||||
|
||||
|
||||
def _visible_pixels(panel, depth: np.ndarray, points, tolerance: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Pixels (image coordinates) of those ``points`` that are in the panel and not behind the nearest surface there."""
|
||||
|
||||
if points is None or len(points) == 0:
|
||||
return np.empty(0), np.empty(0)
|
||||
sample = np.asarray(points)
|
||||
if len(sample) > 3000:
|
||||
sample = sample[:: len(sample) // 3000 + 1]
|
||||
xs, ys = [], []
|
||||
for point in sample:
|
||||
x, y, distance, in_view = panel.project(tuple(float(v) for v in point))
|
||||
if not in_view:
|
||||
continue
|
||||
column, row = int(x), int(y)
|
||||
if not (0 <= column < depth.shape[1] and 0 <= row < depth.shape[0]):
|
||||
continue
|
||||
if distance <= depth[row, column] + tolerance:
|
||||
xs.append(x)
|
||||
ys.append(y)
|
||||
return np.asarray(xs), np.asarray(ys)
|
||||
|
||||
|
||||
def render_views(
|
||||
base: MeshData | None,
|
||||
output_path: str | Path,
|
||||
*,
|
||||
title: str,
|
||||
views: Sequence[tuple[float, float, str]],
|
||||
image_size: tuple[float, float],
|
||||
dpi: int,
|
||||
context_opacity: float = 1.0,
|
||||
highlight_edge_width: float = 4.5,
|
||||
highlight_point_size: float = 15.0,
|
||||
brep_edges: LineData | None = None,
|
||||
highlighted: MeshData | None = None,
|
||||
highlighted_edges: LineData | None = None,
|
||||
highlighted_points: PointData | None = None,
|
||||
highlighted_groups: Sequence[tuple[MeshData, Sequence[float], float]] | None = None,
|
||||
highlighted_edge_groups: Sequence[tuple[LineData, Sequence[float]]] | None = None,
|
||||
highlighted_point_groups: Sequence[tuple[PointData, Sequence[float]]] | None = None,
|
||||
legend: Sequence[tuple[str, Sequence[float]]] | None = None,
|
||||
legend_columns: int = 1,
|
||||
legend_panel: bool = False,
|
||||
show_axes: bool = False,
|
||||
callouts: Sequence[tuple] | None = None,
|
||||
edge_width_scale: float = 0.0019,
|
||||
supersample: int = 1,
|
||||
style: str = "standard",
|
||||
zoom: float | None = None,
|
||||
view_up: Sequence[float] | None = None,
|
||||
datasets: Mapping[str, Any] | None = None,
|
||||
) -> Path:
|
||||
"""Draw ``views`` of the geometry into one PNG (or JPEG, by the suffix of ``output_path``)."""
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from simplecadapi import _cpp as native
|
||||
from simplecadapi._cpp.screenshot import _blend_box, _draw_callouts, _font
|
||||
|
||||
if not views:
|
||||
raise ValueError("at least one render view is required")
|
||||
if dpi < 1 or image_size[0] <= 0.0 or image_size[1] <= 0.0:
|
||||
raise ValueError("image size and DPI must be greater than zero")
|
||||
if highlight_edge_width <= 0.0:
|
||||
raise ValueError("highlight_edge_width must be greater than zero")
|
||||
if highlight_point_size <= 0.0:
|
||||
raise ValueError("highlight_point_size must be greater than zero")
|
||||
if legend_columns < 1:
|
||||
raise ValueError("legend_columns must be at least one")
|
||||
if style not in ("standard", "studio"):
|
||||
raise ValueError(f"unknown render style: {style!r} (expected 'standard' or 'studio')")
|
||||
supersample = max(1, min(4, int(supersample)))
|
||||
studio = style == "studio"
|
||||
width = max(1, int(round(image_size[0] * dpi)))
|
||||
height = max(1, int(round(image_size[1] * dpi)))
|
||||
|
||||
scene = native.RenderScene()
|
||||
mesh_index: dict[int, int] = {} # id(geometry) -> index of its mesh in the scene, for the callout re-anchoring
|
||||
|
||||
def surface(mesh: MeshData, color, opacity) -> None:
|
||||
mesh_index[id(mesh)] = _add_mesh(scene, mesh, color, opacity, studio=False)
|
||||
|
||||
if base is not None:
|
||||
mesh_index[id(base)] = _add_mesh(scene, base, _STUDIO_BASE if studio else _STANDARD_BASE, context_opacity,
|
||||
studio=studio)
|
||||
if brep_edges is not None:
|
||||
if edge_width_scale > 0.0:
|
||||
_add_lines(scene, brep_edges, _EDGE_INK, ink=True, width_px=None)
|
||||
else:
|
||||
_add_lines(scene, brep_edges, _EDGE_INK, ink=False, width_px=1.0)
|
||||
if highlighted_groups:
|
||||
for mesh, color, opacity in highlighted_groups:
|
||||
surface(mesh, color, opacity)
|
||||
elif highlighted is not None:
|
||||
surface(highlighted, _HIGHLIGHT_SURFACE, 1.0)
|
||||
edge_px = highlight_edge_width / supersample
|
||||
if highlighted_edge_groups:
|
||||
for lines, color in highlighted_edge_groups:
|
||||
_add_lines(scene, lines, color, ink=False, width_px=edge_px)
|
||||
elif highlighted_edges is not None:
|
||||
_add_lines(scene, highlighted_edges, _HIGHLIGHT_LINE, ink=False, width_px=edge_px)
|
||||
point_px = highlight_point_size / supersample
|
||||
if highlighted_point_groups:
|
||||
for points, color in highlighted_point_groups:
|
||||
scene.add_points(np.ascontiguousarray(points.points, dtype=np.float32),
|
||||
color=tuple(float(v) for v in color), size_px=point_px)
|
||||
elif highlighted_points is not None:
|
||||
scene.add_points(np.ascontiguousarray(highlighted_points.points, dtype=np.float32),
|
||||
color=_HIGHLIGHT_LINE, size_px=point_px)
|
||||
|
||||
callouts = list(callouts or ())
|
||||
legend = list(legend or ())
|
||||
panel_fraction = 0.30 if legend and legend_panel else 0.0
|
||||
frame = native.render_scene(
|
||||
scene, width, height, supersample=supersample, style=style,
|
||||
views=[(float(a), float(b), str(c)) for a, b, c in views],
|
||||
legend_panel_fraction=panel_fraction,
|
||||
view_up=tuple(float(v) for v in view_up) if view_up is not None else None,
|
||||
zoom=(float(zoom) / 4.0) if (len(views) == 1 and zoom is not None) else 1.0,
|
||||
edge_width_scale=edge_width_scale, show_axes=show_axes,
|
||||
anchors=[tuple(float(v) for v in entry[1]) for entry in callouts],
|
||||
)
|
||||
image = Image.fromarray(np.asarray(frame.rgba)[:, :, :3].copy())
|
||||
draw = ImageDraw.Draw(image)
|
||||
columns = min(2, len(views))
|
||||
rows = (len(views) + columns - 1) // columns
|
||||
ink = (0.85, 0.89, 0.94) if studio else (0.08, 0.11, 0.15)
|
||||
mesh_ids = np.asarray(frame.mesh_id)
|
||||
depth = np.asarray(frame.depth)
|
||||
low, high = scene.bounds()
|
||||
tolerance = max(float(max(h - l for l, h in zip(low, high))), 1e-9) * 0.002 # as the renderer's own anchor test
|
||||
|
||||
for index, panel in enumerate(frame.panels):
|
||||
title_font = _font(max(14, min(width // columns, height // rows) // 34))
|
||||
text = f"{title}\n{panel.label}" if index == 0 else panel.label
|
||||
draw.multiline_text((panel.x + 16, panel.y + panel.height - 14), text, font=title_font, fill=_rgb8(ink),
|
||||
anchor="ld")
|
||||
if show_axes:
|
||||
axis_font = _font(max(10, panel.height // 40), bold=False)
|
||||
for (tip_x, tip_y), (name, color) in zip(
|
||||
panel.axes_tips, (("X", (1, .3, .3)), ("Y", (.3, 1, .3)), ("Z", (.4, .55, 1)))
|
||||
):
|
||||
draw.text((tip_x + 3, tip_y - 3), name, font=axis_font, fill=_rgb8(color))
|
||||
if callouts:
|
||||
callout_font = _font(max(18, min(28, min(width // columns, height // rows) // 30)))
|
||||
items = []
|
||||
for k, entry in enumerate(callouts):
|
||||
label, color = entry[0], entry[2]
|
||||
tag = entry[3] if len(entry) > 3 else None
|
||||
x, y, _depth, _in_view, visible = panel.anchors[k]
|
||||
if visible:
|
||||
items.append((label, (x, y), color))
|
||||
continue
|
||||
target = datasets.get(str(tag)) if (tag and datasets) else None
|
||||
if target is None:
|
||||
continue # nothing to re-anchor on: the callout is dropped for this panel
|
||||
found = mesh_index.get(id(target))
|
||||
if found is not None: # a surface: the pixels the id buffer says belong to it
|
||||
region = mesh_ids[panel.y:panel.y + panel.height, panel.x:panel.x + panel.width] == found
|
||||
ys, xs = np.nonzero(region)
|
||||
xs, ys = xs + panel.x, ys + panel.y
|
||||
else: # edges and points: their own points that the depth buffer shows
|
||||
xs, ys = _visible_pixels(panel, depth, getattr(target, "points", None), tolerance)
|
||||
if len(xs) == 0:
|
||||
continue
|
||||
step = max(1, len(xs) // 4000)
|
||||
xs, ys = xs[::step], ys[::step]
|
||||
nearest = int(np.argmin((xs - x) ** 2 + (ys - y) ** 2))
|
||||
items.append((label, (float(xs[nearest]) + 0.5, float(ys[nearest]) + 0.5), color))
|
||||
_draw_callouts(draw, items, panel, callout_font)
|
||||
|
||||
if legend:
|
||||
if panel_fraction:
|
||||
font = _font(max(12, min(20, height // 52)))
|
||||
spacing = int(font.size * 1.55)
|
||||
panel_x = int(round(width * (1 - panel_fraction)))
|
||||
column_width = (width - panel_x) / legend_columns
|
||||
per_column = (len(legend) + legend_columns - 1) // legend_columns
|
||||
for k, (label, color) in enumerate(legend):
|
||||
column, row = k // per_column, k % per_column
|
||||
draw.text((panel_x + 12 + column * column_width, spacing * 2 + row * spacing), "■ " + label, font=font,
|
||||
fill=_rgb8(color))
|
||||
else:
|
||||
viewport_w, viewport_h = width // columns, height // rows
|
||||
font = _font(max(12, min(20, min(viewport_w, viewport_h) // 34)))
|
||||
spacing = int(font.size * 1.55)
|
||||
per_column = (len(legend) + legend_columns - 1) // legend_columns
|
||||
column_width = max(112, max(int(len(label) * font.size * 0.62) + 26 for label, _ in legend))
|
||||
start_x = max(16, viewport_w - column_width * legend_columns - 16)
|
||||
background = (0.02, 0.02, 0.04) if studio else (0.94, 0.96, 0.98)
|
||||
for k, (label, color) in enumerate(legend):
|
||||
column, row = k // per_column, k % per_column
|
||||
x = start_x + column * column_width
|
||||
y = max(48, 18) + row * spacing
|
||||
_blend_box(draw, (x - 2, y - 2, x + column_width - 8, y + spacing - 4), _rgb8(background), 0.8, image)
|
||||
draw.text((x, y), "■ " + label, font=font, fill=_rgb8(color))
|
||||
|
||||
output = Path(output_path)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
if output.suffix.lower() in (".jpg", ".jpeg"):
|
||||
image.save(output, quality=95)
|
||||
else:
|
||||
image.save(output, compress_level=1)
|
||||
return output
|
||||
|
||||
|
||||
def render_comparison(
|
||||
models: Sequence[tuple[str, str, MeshData, LineData | None]],
|
||||
output_path: str | Path,
|
||||
*,
|
||||
views: Sequence[tuple[float, float, str]],
|
||||
image_size: tuple[float, float],
|
||||
dpi: int,
|
||||
shared_bounds: tuple[float, float, float, float, float, float],
|
||||
) -> Path:
|
||||
"""Models side by side (one column each), one row per view, all with the same camera fit and scale.
|
||||
|
||||
The renderer fits its camera to the scene it is given, so every cell carries an invisible triangle spanning
|
||||
``shared_bounds`` (the union of the models' boxes): the fit, and so the scale, is then the same in every cell.
|
||||
"""
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from simplecadapi import _cpp as native
|
||||
from simplecadapi._cpp.screenshot import _font
|
||||
|
||||
if not views:
|
||||
raise ValueError("at least one render view is required")
|
||||
if dpi < 1 or image_size[0] <= 0.0 or image_size[1] <= 0.0:
|
||||
raise ValueError("image size and DPI must be greater than zero")
|
||||
width = max(1, int(round(image_size[0] * dpi)))
|
||||
height = max(1, int(round(image_size[1] * dpi)))
|
||||
columns, rows = len(models), len(views)
|
||||
cell_w, cell_h = width // columns, height // rows
|
||||
xmin, xmax, ymin, ymax, zmin, zmax = shared_bounds
|
||||
span = np.array([[xmin, ymin, zmin], [xmax, ymax, zmax], [xmin, ymin, zmin]], dtype=np.float32)
|
||||
up = np.tile(np.array([0.0, 0.0, 1.0], dtype=np.float32), (3, 1))
|
||||
canvas = Image.new("RGB", (cell_w * columns, cell_h * rows), (240, 245, 250))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
font = _font(max(13, min(cell_w, cell_h) // 34))
|
||||
for row, (elevation, azimuth, view_title) in enumerate(views):
|
||||
for column, (model_title, filename, mesh, edges) in enumerate(models):
|
||||
scene = native.RenderScene()
|
||||
_add_mesh(scene, mesh, _STANDARD_BASE, 1.0, studio=False)
|
||||
if edges is not None:
|
||||
_add_lines(scene, edges, _EDGE_INK, ink=False, width_px=1.0)
|
||||
scene.add_mesh_arrays(span, up, np.array([[0, 1, 2]], dtype=np.uint32), np.zeros(1, dtype=np.uint32),
|
||||
opacity=0.0)
|
||||
frame = native.render_scene(scene, cell_w, cell_h, supersample=2, style="standard",
|
||||
views=[(float(elevation), float(azimuth), str(view_title))])
|
||||
cell = Image.fromarray(np.asarray(frame.rgba)[:, :, :3].copy())
|
||||
canvas.paste(cell, (column * cell_w, row * cell_h))
|
||||
draw.multiline_text((column * cell_w + 14, (row + 1) * cell_h - 12), f"{model_title}: {filename}\n{view_title}",
|
||||
font=font, fill=_rgb8((0.08, 0.11, 0.15)), anchor="ld")
|
||||
output = Path(output_path)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
canvas.save(output, compress_level=1)
|
||||
return output
|
||||
@@ -1207,9 +1207,9 @@ def render_manufacturing_hints_rpath(
|
||||
)
|
||||
from .render import (
|
||||
DEFAULT_VIEWS,
|
||||
_edge_polydata,
|
||||
_mesh_polydata,
|
||||
_render_polydata_views,
|
||||
_edge_geometry,
|
||||
_mesh_geometry,
|
||||
_render_views,
|
||||
)
|
||||
|
||||
groups = []
|
||||
@@ -1230,7 +1230,7 @@ def render_manufacturing_hints_rpath(
|
||||
shapes = [model.resolve_entity(entity_id)[2] for entity_id in ids]
|
||||
groups.append(
|
||||
(
|
||||
_mesh_polydata(shapes, linear_deflection, angular_deflection),
|
||||
_mesh_geometry(shapes, linear_deflection, angular_deflection),
|
||||
color,
|
||||
1.0,
|
||||
)
|
||||
@@ -1238,15 +1238,15 @@ def render_manufacturing_hints_rpath(
|
||||
legend.append((label, color))
|
||||
if not groups:
|
||||
raise ValueError("The manufacturing analysis contains no highlightable faces")
|
||||
return _render_polydata_views(
|
||||
_mesh_polydata([model.root], linear_deflection, angular_deflection),
|
||||
return _render_views(
|
||||
_mesh_geometry([model.root], linear_deflection, angular_deflection),
|
||||
output_path,
|
||||
title="BREP manufacturing-feature hints",
|
||||
views=tuple(views or DEFAULT_VIEWS),
|
||||
image_size=image_size,
|
||||
dpi=dpi,
|
||||
context_opacity=0.16,
|
||||
brep_edge_polydata=_edge_polydata(
|
||||
brep_edges=_edge_geometry(
|
||||
[model.root], deflection=linear_deflection
|
||||
),
|
||||
highlighted_groups=groups,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,151 +0,0 @@
|
||||
"""One-shot VTK render worker for native crash isolation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import traceback
|
||||
from typing import Any, Mapping
|
||||
|
||||
|
||||
def _read_polydata(path: Path):
|
||||
import vtk
|
||||
|
||||
# VTK's own chatter (a missing X server, driver notes) reads as a render
|
||||
# failure; a real one fails the worker and is named by the caller.
|
||||
vtk.vtkObject.GlobalWarningDisplayOff()
|
||||
reader = vtk.vtkXMLPolyDataReader()
|
||||
reader.SetFileName(str(path))
|
||||
reader.Update()
|
||||
output = vtk.vtkPolyData()
|
||||
output.DeepCopy(reader.GetOutput())
|
||||
return output
|
||||
|
||||
|
||||
def _load_datasets(root: Path, values: Mapping[str, str | None]) -> dict[str, Any]:
|
||||
return {
|
||||
str(name): None if member is None else _read_polydata(root / str(member))
|
||||
for name, member in values.items()
|
||||
}
|
||||
|
||||
|
||||
def _render_views(
|
||||
datasets: Mapping[str, Any], output_path: Path, options: Mapping[str, Any]
|
||||
) -> None:
|
||||
from .render import _render_polydata_views_in_process
|
||||
|
||||
surface_groups = [
|
||||
(
|
||||
datasets[str(item["dataset"])],
|
||||
tuple(item["color"]),
|
||||
float(item["opacity"]),
|
||||
)
|
||||
for item in options.get("surface_groups", [])
|
||||
]
|
||||
edge_groups = [
|
||||
(datasets[str(item["dataset"])], tuple(item["color"]))
|
||||
for item in options.get("edge_groups", [])
|
||||
]
|
||||
point_groups = [
|
||||
(datasets[str(item["dataset"])], tuple(item["color"]))
|
||||
for item in options.get("point_groups", [])
|
||||
]
|
||||
legend = options.get("legend")
|
||||
callouts = options.get("callouts")
|
||||
_render_polydata_views_in_process(
|
||||
datasets.get("base"),
|
||||
output_path,
|
||||
title=str(options["title"]),
|
||||
views=tuple(tuple(item) for item in options["views"]),
|
||||
image_size=tuple(float(value) for value in options["image_size"]),
|
||||
dpi=int(options["dpi"]),
|
||||
context_opacity=float(options["context_opacity"]),
|
||||
highlight_edge_width=float(options["highlight_edge_width"]),
|
||||
highlight_point_size=float(options["highlight_point_size"]),
|
||||
brep_edge_polydata=datasets.get("brep_edges"),
|
||||
highlighted_polydata=datasets.get("highlighted"),
|
||||
highlighted_edge_polydata=datasets.get("highlighted_edges"),
|
||||
highlighted_point_polydata=datasets.get("highlighted_points"),
|
||||
highlighted_groups=surface_groups,
|
||||
highlighted_edge_groups=edge_groups,
|
||||
highlighted_point_groups=point_groups,
|
||||
legend=(
|
||||
tuple((str(label), tuple(color)) for label, color in legend)
|
||||
if legend is not None
|
||||
else None
|
||||
),
|
||||
legend_columns=int(options["legend_columns"]),
|
||||
legend_panel=bool(options["legend_panel"]),
|
||||
show_axes=bool(options.get("show_axes", False)),
|
||||
datasets=datasets,
|
||||
edge_width_scale=float(options.get("edge_width_scale", 0.0019)),
|
||||
supersample=int(options.get("supersample", 1)),
|
||||
style=str(options.get("style", "standard")),
|
||||
zoom=None if options.get("zoom") is None else float(options["zoom"]),
|
||||
view_up=(
|
||||
None
|
||||
if options.get("view_up") is None
|
||||
else tuple(float(value) for value in options["view_up"])
|
||||
),
|
||||
callouts=(
|
||||
[
|
||||
(
|
||||
str(entry[0]),
|
||||
tuple(float(value) for value in entry[1]),
|
||||
tuple(entry[2]),
|
||||
*([str(entry[3])] if len(entry) > 3 else []),
|
||||
)
|
||||
for entry in callouts
|
||||
]
|
||||
if callouts is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
def _main(manifest_path: Path) -> None:
|
||||
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
if payload.get("schema_version") != "1.0":
|
||||
raise ValueError("unsupported render worker schema")
|
||||
mode = str(payload.get("mode", ""))
|
||||
datasets = _load_datasets(manifest_path.parent, payload["datasets"])
|
||||
output_path = Path(payload["output_path"])
|
||||
options = payload["options"]
|
||||
lock_path = Path(
|
||||
os.environ.get(
|
||||
"SIMPLECAD_VTK_RENDER_LOCK", "/tmp/simplecad-vtk-render.lock"
|
||||
)
|
||||
)
|
||||
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with lock_path.open("a+b") as lock_file:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
||||
if mode == "views":
|
||||
_render_views(datasets, output_path, options)
|
||||
else:
|
||||
raise ValueError(f"unsupported render worker mode: {mode}")
|
||||
Path(payload["completion_path"]).touch()
|
||||
# vtkCocoaRenderWindow can crash while Python unwinds VTK wrappers after
|
||||
# rendering. Exit before this frame is destroyed; the OS releases the
|
||||
# one-shot worker's native resources and file lock.
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
os._exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = 0
|
||||
try:
|
||||
if len(sys.argv) != 2:
|
||||
raise ValueError("usage: python -m simplecadapi.inspect.brep.render_worker MANIFEST")
|
||||
_main(Path(sys.argv[1]))
|
||||
except BaseException:
|
||||
traceback.print_exc()
|
||||
exit_code = 1
|
||||
finally:
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
os._exit(exit_code)
|
||||
+1
-1
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import os
|
||||
|
||||
# Failure-path evidence rendering stays off for the suite at large: it is
|
||||
# slow (VTK worker per render) and exercises nothing those tests assert.
|
||||
# slow (one render per failure) and exercises nothing those tests assert.
|
||||
# Dedicated evidence tests opt back in via monkeypatch.delenv. Their
|
||||
# per-render budget scales with the slowest runner (cold CI workers), not
|
||||
# with the agent-facing default.
|
||||
|
||||
@@ -15,10 +15,6 @@
|
||||
"internal",
|
||||
"patches the Python helpers tracked_cut / fuse_shapes_with_history to prove they are not called; the C++ operators never go through a Python attribute. The behaviour (a graph-policy boolean asks the kernel for no history) is asserted by src/cpp/tests/cpp/ops_features/test_booleans.cpp via tracking::history_query_count()"
|
||||
],
|
||||
"test/test_render_screenshot_multiview.py::TestRenderScreenshotMultiView::test_default_routes_to_multiview_engine_with_annotations": [
|
||||
"internal",
|
||||
"patches the VTK engine's inspect.brep.render._prepare_polydata_render to see which engine a request is routed to; the native screenshot is the C++ renderer, there is no second engine. The routing contract (default = 4-panel grid, view= = one panel, views= = custom grid) is asserted by src/cpp/tests/python/test_render_screenshot_routing.py"
|
||||
],
|
||||
"test/test_shape_restore_cost.py::TestLazyRestore::test_a_restored_shape_is_built_on_first_use": [
|
||||
"internal",
|
||||
"tests the Python wrappers' internals (OperationNode dataclass/pickle, _TopoEntity, shape restore cost), which the C++ port does not have"
|
||||
@@ -78,13 +74,5 @@
|
||||
"tests/test_topology_identity.py::test_shared_edge_occurrences_keep_entity_state_after_whole_assignment": [
|
||||
"internal",
|
||||
"tests the Python wrappers' internals (OperationNode dataclass/pickle, _TopoEntity, shape restore cost), which the C++ port does not have"
|
||||
],
|
||||
"test/test_render_screenshot_multiview.py::TestRenderScreenshotMultiView::test_custom_views_reach_the_grid_engine": [
|
||||
"internal",
|
||||
"patches the VTK engine's inspect.brep.render._prepare_polydata_render to see which engine a request is routed to; the native screenshot is the C++ renderer, there is no second engine. The routing contract (default = 4-panel grid, view= = one panel, views= = custom grid) is asserted by src/cpp/tests/python/test_render_screenshot_routing.py"
|
||||
],
|
||||
"test/test_render_screenshot_multiview.py::TestRenderScreenshotMultiView::test_explicit_view_routes_through_the_grid_engine": [
|
||||
"internal",
|
||||
"patches the VTK engine's inspect.brep.render._prepare_polydata_render to see which engine a request is routed to; the native screenshot is the C++ renderer, there is no second engine. The routing contract (default = 4-panel grid, view= = one panel, views= = custom grid) is asserted by src/cpp/tests/python/test_render_screenshot_routing.py"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -31,12 +31,10 @@ from simplecadapi.inspect.brep.queries import (
|
||||
select_region_entities_rdescriptor,
|
||||
)
|
||||
from simplecadapi.inspect.brep.render import (
|
||||
_edge_polydata,
|
||||
_edge_geometry,
|
||||
_entity_map_legend,
|
||||
_load_step_xcaf,
|
||||
_mesh_polydata,
|
||||
_point_polydata,
|
||||
_run_render_worker,
|
||||
_mesh_geometry,
|
||||
inspect_step_components_rdescriptorlist,
|
||||
render_entity_kind_maps_rpath,
|
||||
render_entity_map_rpath,
|
||||
@@ -477,14 +475,15 @@ def test_render_step_views_preserves_xcaf_colors_and_brep_edges(tmp_path):
|
||||
shape, face_colors = _load_step_xcaf(step)
|
||||
assert face_colors
|
||||
assert all(color[:3] == pytest.approx(expected) for color in face_colors.values())
|
||||
mesh = _mesh_polydata(
|
||||
mesh = _mesh_geometry(
|
||||
[shape],
|
||||
linear_deflection=0.1,
|
||||
angular_deflection=0.2,
|
||||
face_colors=face_colors,
|
||||
)
|
||||
assert mesh.GetCellData().GetScalars().GetName() == "STEP_RGBA"
|
||||
assert _edge_polydata([shape], deflection=0.1).GetNumberOfLines() == 12
|
||||
# one RGBA colour per triangle, the STEP colours of the faces
|
||||
assert mesh.colors is not None and mesh.colors.shape == (mesh.triangle_count, 4)
|
||||
assert _edge_geometry([shape], deflection=0.1).line_count == 12
|
||||
output = tmp_path / "colored.png"
|
||||
assert render_step_views_rpath(step, output, image_size=(2.0, 2.0), dpi=60) == output
|
||||
assert output.stat().st_size > 0
|
||||
@@ -667,35 +666,6 @@ def test_render_entity_map_rejects_empty_duplicate_and_invalid_options(tmp_path)
|
||||
|
||||
|
||||
|
||||
def test_render_worker_retries_crash_and_requires_clean_exit(tmp_path, monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_run(command, **kwargs):
|
||||
del kwargs
|
||||
calls.append(tuple(command))
|
||||
payload = json.loads(Path(command[-1]).read_text(encoding="utf-8"))
|
||||
Path(payload["output_path"]).write_bytes(b"crashed-image")
|
||||
Path(payload["completion_path"]).touch()
|
||||
if len(calls) == 1:
|
||||
return SimpleNamespace(returncode=-11, stderr="", stdout="")
|
||||
Path(payload["output_path"]).write_bytes(b"complete-image")
|
||||
return SimpleNamespace(returncode=0, stderr="", stdout="")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"simplecadapi.inspect.brep.render.subprocess.run", fake_run
|
||||
)
|
||||
output = tmp_path / "worker.png"
|
||||
result = _run_render_worker(
|
||||
mode="views",
|
||||
output_path=output,
|
||||
datasets={"base": _point_polydata([(0.0, 0.0, 0.0)])},
|
||||
options={},
|
||||
)
|
||||
|
||||
assert result == output
|
||||
assert output.read_bytes() == b"complete-image"
|
||||
assert len(calls) == 2
|
||||
|
||||
def test_render_region_does_not_mutate_cached_model_geometry(tmp_path):
|
||||
model = _model()
|
||||
before = model.summary()
|
||||
|
||||
@@ -54,7 +54,7 @@ class TestOriginalBooleanApiIntegration(unittest.TestCase):
|
||||
|
||||
|
||||
class TestScreenshotRenderingIntegration(unittest.TestCase):
|
||||
def test_render_screenshot_uses_vtk_with_tags_and_annotations(self):
|
||||
def test_render_screenshot_with_tags_and_annotations(self):
|
||||
box = scad.make_box_rsolid(4.0, 3.0, 2.0)
|
||||
scad.apply_tag(box, "role.body")
|
||||
output = Path(self._testMethodName + ".png")
|
||||
|
||||
@@ -29,65 +29,6 @@ class TestRenderScreenshotMultiView(unittest.TestCase):
|
||||
labels = [entry[2] for entry in views]
|
||||
self.assertEqual(labels, ["isometric", "top / X-Y", "front / X-Z", "side / Y-Z"])
|
||||
|
||||
def test_default_routes_to_multiview_engine_with_annotations(self):
|
||||
solid = self._tagged_solid()
|
||||
with mock.patch.object(
|
||||
brep_render, "_prepare_polydata_render", wraps=brep_render._prepare_polydata_render
|
||||
) as grid:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
scad.render_screenshot_rpath(
|
||||
solid,
|
||||
str(Path(tmp) / "default.png"),
|
||||
highlight_tags=["role.body"],
|
||||
tag_labels={"role.body": "Body"},
|
||||
image_size=(640, 480),
|
||||
)
|
||||
grid.assert_called_once()
|
||||
kwargs = grid.call_args.kwargs
|
||||
self.assertEqual(
|
||||
tuple(kwargs["views"]), scad.operators.features.SCREENSHOT_VIEWS
|
||||
)
|
||||
self.assertTrue(kwargs["show_axes"])
|
||||
self.assertEqual(len(kwargs["highlighted_groups"]), 1)
|
||||
self.assertEqual(kwargs["legend"][0][0], "Body")
|
||||
self.assertEqual(kwargs["callouts"][0][0], "Body")
|
||||
|
||||
def test_custom_views_reach_the_grid_engine(self):
|
||||
solid = self._tagged_solid()
|
||||
custom = [(30.0, -60.0, "custom-iso"), (0.0, -90.0, "front")]
|
||||
with mock.patch.object(
|
||||
brep_render, "_prepare_polydata_render", wraps=brep_render._prepare_polydata_render
|
||||
) as grid:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
scad.render_screenshot_rpath(
|
||||
solid,
|
||||
str(Path(tmp) / "custom.png"),
|
||||
highlight_tags=["role.body"],
|
||||
image_size=(640, 480),
|
||||
views=custom,
|
||||
)
|
||||
grid.assert_called_once()
|
||||
self.assertEqual(tuple(kwargs_views := grid.call_args.kwargs["views"]), tuple(custom))
|
||||
|
||||
def test_explicit_view_routes_through_the_grid_engine(self):
|
||||
solid = self._tagged_solid()
|
||||
with mock.patch.object(
|
||||
brep_render, "_prepare_polydata_render", wraps=brep_render._prepare_polydata_render
|
||||
) as grid:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
output = Path(tmp) / "single.png"
|
||||
scad.render_screenshot_rpath(
|
||||
solid,
|
||||
str(output),
|
||||
highlight_tags=["role.body"],
|
||||
image_size=(320, 240),
|
||||
view="iso",
|
||||
)
|
||||
self.assertTrue(output.is_file())
|
||||
grid.assert_called_once()
|
||||
# 单格:views 参数恰好一条
|
||||
self.assertEqual(len(grid.call_args.kwargs["views"]), 1)
|
||||
|
||||
def test_real_multiview_render_writes_grid_image(self):
|
||||
solid = self._tagged_solid()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
"""Regression tests for the supersampled screenshot writer (#32).
|
||||
|
||||
The writer must create its temp frame without holding a handle open while
|
||||
vtkPNGWriter writes the same path (Windows denies the second open), and it
|
||||
must not leak temp siblings when the render fails.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from simplecadapi.inspect.brep import render as render_module
|
||||
|
||||
|
||||
def test_supersampled_write_downsamples_and_cleans_up(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
output = tmp_path / "box.png"
|
||||
|
||||
def fake_write(window, path: Path) -> None:
|
||||
Image.new("RGB", (8, 8), (255, 0, 0)).save(path)
|
||||
|
||||
monkeypatch.setattr(render_module, "_write_window", fake_write)
|
||||
render_module._write_window_supersampled(object(), output, 2)
|
||||
|
||||
with Image.open(output) as img:
|
||||
assert img.size == (4, 4)
|
||||
assert list(tmp_path.glob(".box-ss*")) == []
|
||||
|
||||
|
||||
def test_supersampled_write_cleans_up_on_render_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
output = tmp_path / "box.png"
|
||||
|
||||
def failing_write(window, path: Path) -> None:
|
||||
path.write_text("partial") # simulate vtk writing before failing
|
||||
raise RuntimeError("vtk failure")
|
||||
|
||||
monkeypatch.setattr(render_module, "_write_window", failing_write)
|
||||
with pytest.raises(RuntimeError):
|
||||
render_module._write_window_supersampled(object(), output, 2)
|
||||
|
||||
# The old NamedTemporaryFile form leaked the temp sibling here.
|
||||
assert not output.exists()
|
||||
assert list(tmp_path.glob(".box-ss*")) == []
|
||||
@@ -3020,7 +3020,6 @@ gmsh = [
|
||||
]
|
||||
inspect = [
|
||||
{ name = "matplotlib" },
|
||||
{ name = "vtk" },
|
||||
]
|
||||
whucad = [
|
||||
{ name = "h5py" },
|
||||
@@ -3040,7 +3039,6 @@ dev = [
|
||||
{ name = "twine" },
|
||||
{ name = "ty" },
|
||||
{ name = "uvicorn" },
|
||||
{ name = "vtk" },
|
||||
{ name = "websockets", version = "16.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "websockets", version = "17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
@@ -3072,7 +3070,6 @@ requires-dist = [
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0,<3" },
|
||||
{ name = "typing-extensions", specifier = ">=4.12,<5" },
|
||||
{ name = "uvicorn", marker = "extra == 'editor'", specifier = ">=0.54.0" },
|
||||
{ name = "vtk", marker = "extra == 'inspect'", specifier = ">=9.3" },
|
||||
{ name = "websockets", marker = "extra == 'editor'", specifier = ">=16.1.1" },
|
||||
]
|
||||
provides-extras = ["dev", "drawing", "editor", "inspect", "whucad", "gmsh", "fem"]
|
||||
@@ -3091,7 +3088,6 @@ dev = [
|
||||
{ name = "twine", specifier = ">=6.1.0" },
|
||||
{ name = "ty", specifier = ">=0.0.18" },
|
||||
{ name = "uvicorn", specifier = ">=0.54.0" },
|
||||
{ name = "vtk", specifier = ">=9.3" },
|
||||
{ name = "websockets", specifier = ">=16.1.1" },
|
||||
]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user