211 lines
10 KiB
Python
211 lines
10 KiB
Python
"""Small deterministic measurements shared by tools and independent reviews."""
|
|
import math
|
|
from collections import Counter
|
|
from engine.gear_inspection import spur_gear_measurements
|
|
|
|
from OCP.BRepAdaptor import BRepAdaptor_Surface
|
|
from OCP.GeomAbs import GeomAbs_Cylinder
|
|
|
|
|
|
def cylinder_surfaces(shape):
|
|
result = []
|
|
for face in shape.faces():
|
|
surface = BRepAdaptor_Surface(face.wrapped)
|
|
if surface.GetType() != GeomAbs_Cylinder:
|
|
continue
|
|
cylinder = surface.Cylinder()
|
|
p, d = cylinder.Location(), cylinder.Axis().Direction()
|
|
box = face.bounding_box()
|
|
result.append({"bbox_min": list(box.min), "bbox_max": list(box.max), "radius_mm": cylinder.Radius(), "origin": [p.X(), p.Y(), p.Z()],
|
|
"axis": [d.X(), d.Y(), d.Z()], "area_mm2": face.area})
|
|
return result
|
|
|
|
|
|
def inspect_geometry(shape, points=None, include_edges=False, radial_sections=None):
|
|
from .radial_sections import measure_radial_sections
|
|
sections = measure_radial_sections(shape, **radial_sections) if radial_sections is not None else None
|
|
box = shape.bounding_box()
|
|
cylinders = cylinder_surfaces(shape)
|
|
return {
|
|
"valid": bool(shape.is_valid), "solid_count": len(shape.solids()),
|
|
"volume_mm3": shape.volume, "bbox_min": list(box.min), "bbox_max": list(box.max),
|
|
"bbox_size": list(box.size),
|
|
"solid_components": [{"bbox_min": list(s.bounding_box().min), "bbox_max": list(s.bounding_box().max), "volume_mm3": s.volume} for s in shape.solids()[:32]],
|
|
**({"radial_sections": sections} if sections is not None else {}),
|
|
"spur_gear_measurements": spur_gear_measurements(shape),
|
|
"surface_types": dict(Counter(str(f.geom_type) for f in shape.faces())),
|
|
"planar_faces": planar_boundaries(shape),
|
|
"conical_faces": conical_boundaries(shape),
|
|
**({"edges": edge_inventory(shape)} if include_edges else {}),
|
|
"helical_measurements": z_helical_measurements(shape),
|
|
"cylindrical_faces": cylinders[:120], "cylindrical_face_count": len(cylinders),
|
|
"note": "圆柱面数量不等于孔数;一个孔可能分成多个面。",
|
|
"point_material": [{"point": p, "inside": any(s.is_inside(tuple(p)) for s in shape.solids())}
|
|
for p in (points or [])],
|
|
}
|
|
|
|
|
|
def matching_hole_surface(shape, axis, diameter, center, tolerance):
|
|
component = "XYZ".index(axis)
|
|
for surface in cylinder_surfaces(shape):
|
|
if abs(abs(surface["axis"][component]) - 1) > 1e-5:
|
|
continue
|
|
if abs(2 * surface["radius_mm"] - diameter) > tolerance:
|
|
continue
|
|
radial_distance = math.sqrt(sum((surface["origin"][i] - center[i]) ** 2
|
|
for i in range(3) if i != component))
|
|
if radial_distance <= tolerance:
|
|
return True
|
|
return False
|
|
|
|
|
|
def planar_boundaries(shape):
|
|
"""Measured planar cut boundaries, not a feature count inferred from a view."""
|
|
from OCP.GeomAbs import GeomAbs_Plane
|
|
rows = []
|
|
for face in shape.faces():
|
|
s = BRepAdaptor_Surface(face.wrapped)
|
|
if s.GetType() != GeomAbs_Plane:
|
|
continue
|
|
b = face.bounding_box()
|
|
n = s.Plane().Axis().Direction()
|
|
rows.append({'bbox_min': list(b.min), 'bbox_max': list(b.max),
|
|
'normal': [n.X(), n.Y(), n.Z()], 'area_mm2': face.area})
|
|
return rows[:160]
|
|
|
|
|
|
def _z_helical_measurements(shape):
|
|
"""Sample real edges/flank derivatives about world Z; never echo operation inputs.
|
|
|
|
This evidence measures lead and axial-section flank angles. Edge count does
|
|
not determine thread start count, and rotated/off-axis threads need a local
|
|
measurement frame rather than interpreting missing results as absence.
|
|
"""
|
|
from OCP.GeomAbs import GeomAbs_BSplineSurface
|
|
from OCP.gp import gp_Pnt, gp_Vec
|
|
leads, angles, helical_edges, edge_samples = [], [], set(), []
|
|
for e in shape.edges():
|
|
if 'BSPLINE' not in str(e.geom_type):
|
|
continue
|
|
p0 = e.position_at(0)
|
|
radius0 = math.hypot(p0.X, p0.Y)
|
|
if radius0 < 1e-5:
|
|
continue
|
|
# Bound the angular step to avoid aliasing long, multi-turn edges.
|
|
samples = max(16, math.ceil(e.length / (radius0 * math.pi / 3)))
|
|
if samples > 4096:
|
|
continue
|
|
ps = [e.position_at(i / samples) for i in range(samples + 1)]
|
|
radii = [math.hypot(p.X, p.Y) for p in ps]
|
|
if min(radii) < 1e-5 or max(radii)-min(radii) > .002:
|
|
continue
|
|
theta = [math.atan2(p.Y, p.X) for p in ps]
|
|
unwrapped = [theta[0]]
|
|
for prev, now in zip(theta, theta[1:]):
|
|
unwrapped.append(unwrapped[-1]+math.atan2(math.sin(now-prev),math.cos(now-prev)))
|
|
dz, da = ps[-1].Z-ps[0].Z, unwrapped[-1]-unwrapped[0]
|
|
if abs(dz) < .2 or abs(da) < .2:
|
|
continue
|
|
slope = dz/da
|
|
error = max(abs(p.Z-ps[0].Z-slope*(t-unwrapped[0])) for p,t in zip(ps,unwrapped))
|
|
if error < .005:
|
|
leads.append(round(slope*2*math.pi,5))
|
|
helical_edges.add(hash(e))
|
|
edge_samples.extend(ps)
|
|
if not leads:
|
|
return {'axis': 'world Z through origin', 'measured_helical_edges': 0}
|
|
for f in shape.faces():
|
|
s = BRepAdaptor_Surface(f.wrapped)
|
|
if s.GetType() != GeomAbs_BSplineSurface or not any(hash(e) in helical_edges for e in f.edges()):
|
|
continue
|
|
p, u, v = gp_Pnt(), gp_Vec(), gp_Vec()
|
|
s.D1((s.FirstUParameter()+s.LastUParameter())/2,
|
|
(s.FirstVParameter()+s.LastVParameter())/2,p,u,v)
|
|
radius = math.hypot(p.X(),p.Y())
|
|
if radius < 1e-5:
|
|
continue
|
|
ut=(-p.Y()*u.X()+p.X()*u.Y())/radius
|
|
vt=(-p.Y()*v.X()+p.X()*v.Y())/radius
|
|
dr=((u.X()*vt-v.X()*ut)*p.X()+(u.Y()*vt-v.Y()*ut)*p.Y())/radius
|
|
dz=u.Z()*vt-v.Z()*ut
|
|
if abs(dr)>1e-6 and abs(dz)>1e-6:
|
|
angle=180-2*math.degrees(math.atan2(abs(dr),abs(dz)))
|
|
if 10 < angle < 120:
|
|
angles.append(round(angle,4))
|
|
sections = []
|
|
radial = [math.hypot(p.X,p.Y) for p in edge_samples]
|
|
low, high = min(p.Z for p in edge_samples), max(p.Z for p in edge_samples)
|
|
depth = max(radial)-min(radial)
|
|
if depth > .01 and shape.solids():
|
|
# Count measured material arcs near the crest. Cutouts can interrupt an
|
|
# arc, so return section evidence, never silently equate arcs to starts.
|
|
from OCP.BRepClass3d import BRepClass3d_SolidClassifier
|
|
from OCP.TopAbs import TopAbs_IN, TopAbs_ON
|
|
classifiers = [BRepClass3d_SolidClassifier(s.wrapped) for s in shape.solids()]
|
|
radius = max(radial)-depth*.15
|
|
for fraction in (.23,.47,.71):
|
|
z = low+(high-low)*fraction
|
|
occupied = []
|
|
for i in range(180):
|
|
a = 2*math.pi*i/180
|
|
p = gp_Pnt(radius*math.cos(a),radius*math.sin(a),z)
|
|
inside = False
|
|
for classifier in classifiers:
|
|
classifier.Perform(p,1e-7)
|
|
inside |= classifier.State() in (TopAbs_IN,TopAbs_ON)
|
|
occupied.append(inside)
|
|
arcs = sum(now and not occupied[i-1] for i,now in enumerate(occupied))
|
|
sections.append({'z_mm':round(z,5),'radius_mm':round(radius,5),
|
|
'angular_step_deg':2,'material_arcs':arcs if not all(occupied) else 1,
|
|
'occupied_samples':sum(occupied),'total_samples':180})
|
|
return {'axis':'world Z through origin', 'measured_helical_edges':len(leads),
|
|
'signed_lead_mm_range':[min(leads),max(leads)],
|
|
'hand':'right' if min(leads)>0 else 'left' if max(leads)<0 else 'mixed',
|
|
'measured_flank_faces':len(angles), 'crest_sections':sections,
|
|
'symmetric_axial_profile_angle_deg_range':[min(angles),max(angles)] if angles else None,
|
|
'note':'由实体边采样与曲面导数测得;导程不等于多线螺纹的螺距,边数不是线数;crest_sections为牙顶附近截面材料弧段数,开窗可能截断弧段,须结合轴向位置核对线数;角度范围不证明加工公差。'}
|
|
|
|
|
|
def z_helical_measurements(shape):
|
|
try:
|
|
return _z_helical_measurements(shape)
|
|
except Exception as exc:
|
|
return {"axis": "world Z through origin", "measurement_unavailable": str(exc)}
|
|
|
|
|
|
def conical_boundaries(shape):
|
|
"""Actual cone angle and axial/radial extents, useful for turned chamfers."""
|
|
from OCP.GeomAbs import GeomAbs_Cone
|
|
from OCP.gp import gp_Pnt
|
|
result=[]
|
|
for face in shape.faces():
|
|
s=BRepAdaptor_Surface(face.wrapped)
|
|
if s.GetType()!=GeomAbs_Cone:
|
|
continue
|
|
cone=s.Cone(); origin=cone.Location(); axis=cone.Axis().Direction()
|
|
axial=[]; radial=[]
|
|
for v in (s.FirstVParameter(),s.LastVParameter()):
|
|
p=gp_Pnt();s.D0(s.FirstUParameter(),v,p)
|
|
delta=[p.X()-origin.X(),p.Y()-origin.Y(),p.Z()-origin.Z()]
|
|
direction=[axis.X(),axis.Y(),axis.Z()]
|
|
z=sum(a*b for a,b in zip(delta,direction))
|
|
axial.append(z);radial.append(math.sqrt(max(0,sum(a*a for a in delta)-z*z)))
|
|
b=face.bounding_box()
|
|
result.append({'bbox_min':list(b.min),'bbox_max':list(b.max),
|
|
'axis':[axis.X(),axis.Y(),axis.Z()],
|
|
'half_angle_deg':abs(math.degrees(cone.SemiAngle())),
|
|
'axial_extent_mm':abs(axial[1]-axial[0]),
|
|
'radial_extent_mm':abs(radial[1]-radial[0]),
|
|
'radius_range_mm':sorted(radial),'area_mm2':face.area})
|
|
return result[:160]
|
|
|
|
|
|
def edge_inventory(shape):
|
|
rows=[]
|
|
for i,e in enumerate(shape.edges()):
|
|
b=e.bounding_box()
|
|
rows.append({'index':i,'type':str(e.geom_type),'length_mm':e.length,
|
|
'midpoint':list(e.position_at(.5)), 'bbox_min':list(b.min),'bbox_max':list(b.max)})
|
|
return {'count':len(rows),'items':rows[:600],
|
|
'note':'index仅对应本次id当前实体;每次改变几何后必须重新测量,不能沿用旧索引。超过600条需改用局部建模步骤分解。'}
|