29 KiB
29 KiB
In [1]:
from pathlib import Path
import time
import cadquery as cq
from cadquery import exporters
import numpy as np
import trimesh
import plotly.graph_objects as go
import plotly.io as pio
ARTIFACTS = Path("seminar_1_outputs")
ARTIFACTS.mkdir(exist_ok=True)
np.set_printoptions(precision=4, suppress=True)
pio.renderers.default = "plotly_mimetype+notebook"In [4]:
def _configure_3d_figure(fig, title):
fig.update_layout(
title=title,
width=850,
height=650,
margin=dict(l=0, r=0, b=0, t=55),
scene=dict(
aspectmode="data",
xaxis_title="X",
yaxis_title="Y",
zaxis_title="Z",
),
)
return fig
def _mesh_edges_trace(mesh, color="#243447", width=1, max_edges=25_000):
vertices = np.asarray(mesh.vertices)
edges = np.asarray(mesh.edges_unique)
if len(edges) > max_edges:
indices = np.linspace(0, len(edges) - 1, max_edges, dtype=int)
edges = edges[indices]
segments = vertices[edges]
coordinates = np.full((len(segments) * 3, 3), np.nan)
coordinates[0::3] = segments[:, 0]
coordinates[1::3] = segments[:, 1]
return go.Scatter3d(
x=coordinates[:, 0],
y=coordinates[:, 1],
z=coordinates[:, 2],
mode="lines",
line=dict(color=color, width=width),
hoverinfo="skip",
showlegend=False,
)
def plot_mesh(
mesh,
title="Triangle mesh",
color="#79a7d3",
opacity=1.0,
show_edges=True,
):
vertices = np.asarray(mesh.vertices)
faces = np.asarray(mesh.faces)
fig = go.Figure()
fig.add_trace(go.Mesh3d(
x=vertices[:, 0],
y=vertices[:, 1],
z=vertices[:, 2],
i=faces[:, 0],
j=faces[:, 1],
k=faces[:, 2],
color=color,
opacity=opacity,
flatshading=True,
lighting=dict(ambient=0.45, diffuse=0.8, specular=0.15),
hovertemplate=(
"x=%{x:.2f}<br>y=%{y:.2f}<br>z=%{z:.2f}"
"<extra></extra>"
),
name="surface",
showlegend=False,
))
if show_edges:
fig.add_trace(_mesh_edges_trace(mesh))
_configure_3d_figure(fig, title)
fig.show(renderer="plotly_mimetype+notebook")
def plot_point_cloud(
points,
title="Point cloud",
marker_size=2,
max_points=50_000,
):
points = np.asarray(points)
if len(points) > max_points:
indices = np.linspace(0, len(points) - 1, max_points, dtype=int)
displayed = points[indices]
else:
displayed = points
fig = go.Figure(data=[go.Scatter3d(
x=displayed[:, 0],
y=displayed[:, 1],
z=displayed[:, 2],
mode="markers",
marker=dict(
size=marker_size,
color=displayed[:, 2],
colorscale="Viridis",
opacity=0.85,
colorbar=dict(title="Z"),
),
hovertemplate=(
"x=%{x:.2f}<br>y=%{y:.2f}<br>z=%{z:.2f}"
"<extra></extra>"
),
showlegend=False,
)])
shown = f"{len(displayed):,}".replace(",", " ")
total = f"{len(points):,}".replace(",", " ")
_configure_3d_figure(fig, f"{title}")
fig.show(renderer="plotly_mimetype+notebook")
def plot_voxels(voxels, title="Voxel grid", max_boxes=5_000):
displayed = voxels
suffix = ""
if voxels.filled_count > max_boxes:
displayed = voxels.copy()
displayed.hollow()
boxes = displayed.as_boxes()
pitch = tuple(float(v) for v in np.asarray(voxels.pitch).ravel())
plot_mesh(
boxes,
title=f"{title}; pitch={pitch}{suffix}",
color="#ffb347",
opacity=0.92,
show_edges=True,
)
def make_sdf_volume_for_plot(mesh, resolution=35, padding=5.0):
"""Вычисляет компактную 3D SDF-сетку только для визуализации."""
bounds = np.asarray(mesh.bounds)
x = np.linspace(bounds[0, 0] - padding, bounds[1, 0] + padding, resolution)
y = np.linspace(bounds[0, 1] - padding, bounds[1, 1] + padding, resolution)
z = np.linspace(bounds[0, 2] - padding, bounds[1, 2] + padding, resolution)
xx, yy, zz = np.meshgrid(x, y, z, indexing="ij")
points = np.column_stack([xx.ravel(), yy.ravel(), zz.ravel()])
# trimesh: inside positive; в конспекте: inside negative.
sdf = -trimesh.proximity.signed_distance(mesh, points)
return xx, yy, zz, sdf.reshape(xx.shape)
def plot_sdf_3d(xx, yy, zz, sdf, title="SDF: f(x, y, z) = 0", tau=None):
sdf = np.asarray(sdf)
spacings = []
for coordinates in (xx[:, 0, 0], yy[0, :, 0], zz[0, 0, :]):
if len(coordinates) > 1:
spacings.append(float(np.min(np.diff(coordinates))))
epsilon = 0.2 * min(spacings)
fig = go.Figure()
if tau is not None:
tsdf = np.clip(sdf, -tau, tau)
fig.add_trace(go.Isosurface(
x=xx.ravel(), y=yy.ravel(), z=zz.ravel(),
value=tsdf.ravel(),
isomin=-tau,
isomax=tau,
surface_count=5,
opacity=0.16,
colorscale="RdBu",
caps=dict(x_show=False, y_show=False, z_show=False),
colorbar=dict(title="TSDF"),
name="TSDF levels",
))
fig.add_trace(go.Isosurface(
x=xx.ravel(), y=yy.ravel(), z=zz.ravel(),
value=sdf.ravel(),
isomin=-epsilon,
isomax=epsilon,
surface_count=1,
opacity=0.9,
colorscale=[[0, "#de5b6d"], [1, "#de5b6d"]],
caps=dict(x_show=False, y_show=False, z_show=False),
showscale=False,
hovertemplate=(
"x=%{x:.2f}<br>y=%{y:.2f}<br>z=%{z:.2f}"
"<br>SDF=%{value:.3f}<extra></extra>"
),
name="zero level",
))
_configure_3d_figure(fig, title)
fig.show(renderer="plotly_mimetype+notebook")
In [5]:
def _segment_triangle_intersection(p0, p1, triangle, eps=1e-9):
'''Moller–Trumbore intersection algorithm'''
direction = p1 - p0
v0, v1, v2 = triangle
edge1 = v1 - v0
edge2 = v2 - v0
h = np.cross(direction, edge2)
a = np.dot(edge1, h)
if abs(a) < eps:
return False
f = 1.0 / a
s = p0 - v0
u = f * np.dot(s, h)
if u < -eps or u > 1.0 + eps:
return False
q = np.cross(s, edge1)
v = f * np.dot(direction, q)
if v < -eps or u + v > 1.0 + eps:
return False
t = f * np.dot(edge2, q)
return -eps <= t <= 1.0 + eps
def _triangles_intersect(triangle_a, triangle_b):
for i in range(3):
if _segment_triangle_intersection(
triangle_a[i], triangle_a[(i + 1) % 3], triangle_b
):
return True
if _segment_triangle_intersection(
triangle_b[i], triangle_b[(i + 1) % 3], triangle_a
):
return True
return False
def has_self_intersections(mesh):
'''
Detect non-coplanar intersections between non-adjacent triangles.
The broad phase uses the triangle R-tree from trimesh; `rtree` must
therefore be installed. Coplanar overlapping faces are outside the
scope of this compact seminar helper.
'''
triangles = mesh.triangles
tree = mesh.triangles_tree
faces = mesh.faces
triangle_bounds = np.column_stack([
triangles.min(axis=1),
triangles.max(axis=1),
])
for i, bounds in enumerate(triangle_bounds):
for j in tree.intersection(bounds):
if j <= i:
continue
if np.intersect1d(faces[i], faces[j]).size:
continue
if _triangles_intersect(triangles[i], triangles[j]):
return True
return FalseIn [6]:
# Группа 1
length, width, height = 60.0, 40.0, 10.0
hole_diameter = 14.0
fillet_radius = 4.0
solid = (
cq.Workplane("XY")
.box(length, width, height)
.edges("|Z")
.fillet(fillet_radius)
.faces(">Z")
.workplane()
.hole(hole_diameter)
)
# Группа 2
# r_sphere = 25.0
# r_hole = 10.0
# solid = (
# cq.Workplane("XY")
# .sphere(radius=r_sphere)
# .circle(r_hole)
# .cutThruAll()
# )
coarse_path = ARTIFACTS / "part_coarse.stl"
fine_path = ARTIFACTS / "part_fine.stl"
# TODO: экспортируйте solid:
# coarse: tolerance=1.0, angularTolerance=0.3
# fine: tolerance=0.05, angularTolerance=0.05In [ ]:
# TODO: загрузите mesh_coarse и mesh_fine через trimesh.load_mesh.
mesh_coarse = None
mesh_fine = None
def validate_mesh(mesh):
# TODO: edge-manifold: каждое ребро инцидентно не более чем 2 граням.
manifold = None
# TODO: используйте свойство trimesh.
watertight = None
# Служебная функция предоставлена выше.
self_intersections = has_self_intersections(mesh)
return {
"manifold": manifold,
"watertight": watertight,
"has_self_intersections": self_intersections,
}
# TODO: выведите число vertices/faces и результаты для двух STL.
# TODO: визуализируйте два mesh.In [ ]:
# Проверка валидатора на контролируемых дефектах.
# TODO: удалите одну грань из копии mesh_coarse (метод trimesh) и убедитесь,
# что watertight стал False.
# TODO: создайте два box методами библиотеки trimesh, переместите второй box относительно первого
# таким образом, чтобы они пересекались
# объедините их в единое твердое тело без булевых операций.
# TODO: Экспортируйте точный mesh (mesh_fine) в папку ARTIFACTS в формате .stlIn [ ]:
from OCP.BRep import BRep_Tool
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.TopAbs import TopAbs_FACE, TopAbs_Orientation
from OCP.TopExp import TopExp_Explorer
from OCP.TopLoc import TopLoc_Location
from OCP.TopoDS import TopoDS
def tessellate_cad_shape(workplane, tolerance=0.1, angular_tolerance=0.1):
shape = workplane.val().wrapped
# TODO: запустите BRepMesh_IncrementalMesh и Perform().
vertices = []
faces = []
vertex_offset = 0
explorer = TopExp_Explorer(shape, TopAbs_FACE)
while explorer.More():
face = TopoDS.Face_s(explorer.Current())
location = TopLoc_Location()
triangulation = BRep_Tool.Triangulation_s(face, location)
if triangulation is None:
explorer.Next()
continue
# TODO: перенесите узлы в глобальную систему координат.
# TODO: добавьте треугольники с учётом vertex_offset.
# TODO: учтите TopAbs_REVERSED.
explorer.Next()
return np.asarray(vertices, dtype=float), np.asarray(faces, dtype=int)
# TODO: вызовите функцию, создайте trimesh.Trimesh,
# визуализируйте и проверьте mesh.
In [7]:
def validate_point_cloud(points, source_mesh):
# TODO: верните N и surface density.
n_points = len(points)
return {
"N": int(n_points),
"density": None,
}
point_clouds = {}
for n_points in [500, 5_000, 50_000]:
# TODO: sample_surface с seed=42.
# TODO: сохраните points и выведите validate_point_cloud.
pass
# TODO: визуализируйте минимум два облака.
# TODO: экспортируйте Point Cloud с 5_000 точек в папку ARTIFACTS в формате .plyIn [ ]:
def validate_voxels(voxels):
# TODO: occupied, total points, resolution и occupancy ratio.
return {
"resolution": {
"shape": None,
"pitch": None,
},
"occupancy": {
"occupied": None,
"ratio": None,
},
}
voxel_grids = {}
for pitch in [4.0, 2.0, 1.0]:
# TODO: mesh_fine.voxelized(...).fill().
# TODO: сохраните и проверьте решётку.
pass
# TODO: визуализируйте минимум две решётки.
# TODO: экспортируйте voxel с pitch=4.0 мм в папку ARTIFACTS в формате .binvoxIn [11]:
def make_sdf_slice(mesh, resolution=100, padding=5.0):
# TODO: создайте x/y grid и query_points в плоскости z=centroid[2].
# TODO: вызовите trimesh.proximity.signed_distance.
# TODO: поменяйте знак на соглашение конспекта.
# Вернуть linspace x, y; сетку xx, yy; точки 3D-сетки points; сами расстояния sdf
# return x, y, xx, yy, points, sdf.reshape(xx.shape)
return ...
def validate_sdf(mesh, points, raw_sdf, tsdf, tau, resolution, atol=1e-6):
# TODO: resolution.
# TODO: truncation: abs(tsdf) <= tau + atol.
# TODO: sign correctness через mesh.contains(points),
# исключив точки с abs(raw_sdf) <= atol.
return {
"resolution": None,
"truncation": None,
"sign_correctness": None,
}
tau = 5.0
# TODO: выполните построение и проверки для resolution равным 30 и 100.
# TODO: визуализируйте SDF, TSDF и нулевой уровень.
# Для интерактивной 3D-визуализации используйте:
# xx3, yy3, zz3, sdf3 = make_sdf_volume_for_plot(mesh_fine, resolution=35)
# plot_sdf_3d(xx3, yy3, zz3, sdf3, title="SDF: zero level")
# plot_sdf_3d(xx3, yy3, zz3, sdf3, title=f"TSDF, tau={tau}", tau=tau)
# TODO: экспортируйте SDF 2D-среза в NumPy-формат через np.savez_compressed:
# np.savez_compressed используется для сохранения нескольких массивов NumPy в один файл формата .npz с применением сжатия
# np.savez_compressed(
# ARTIFACTS / "sdf_slice.npz",
# x=...,
# y=...,
# z=...,
# sdf=...,
# tsdf=..,
# tau=...,
# )