| from OCC.Core.BRepBndLib import brepbndlib
|
| from OCC.Core.STEPControl import STEPControl_Reader
|
| from OCC.Core.TopAbs import TopAbs_COMPOUND, TopAbs_SOLID, TopAbs_SHELL
|
| from OCC.Core.TopExp import TopExp_Explorer
|
| from OCC.Display.SimpleGui import init_display
|
| from OCC.Core.Quantity import Quantity_Color, Quantity_NOC_RED
|
| from OCC.Core.Quantity import Quantity_TOC_RGB
|
| from OCC.Core.TopAbs import (TopAbs_COMPOUND, TopAbs_SOLID,
|
| TopAbs_SHELL, TopAbs_FACE,
|
| TopAbs_WIRE, TopAbs_EDGE,
|
| TopAbs_VERTEX)
|
| from OCC.Core.Bnd import Bnd_Box
|
| from OCC.Core.gp import gp_Pnt
|
| import numpy as np
|
| from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeEdge
|
| from tqdm import tqdm
|
| class StepParser:
|
| def __init__(self, stepfile):
|
| self.stepfile = stepfile
|
|
|
| def analyze_shape(shape):
|
| """分析形状类型和子组件"""
|
| shape_type = shape.ShapeType()
|
| type_names = {
|
| TopAbs_COMPOUND: "Compound",
|
| TopAbs_SOLID: "Solid",
|
| TopAbs_SHELL: "Shell",
|
| TopAbs_FACE: "Face",
|
| TopAbs_WIRE: "Wire",
|
| TopAbs_EDGE: "Edge",
|
| TopAbs_VERTEX: "Vertex"
|
| }
|
| return type_names.get(shape_type, "Unknown")
|
|
|
| def _extract_subshapes(shape, output_list):
|
| """递归提取子形状"""
|
| shape_type = shape.ShapeType()
|
|
|
|
|
| if shape_type in [TopAbs_COMPOUND, TopAbs_SHELL]:
|
| explorer = TopExp_Explorer(shape, TopAbs_SOLID)
|
| while explorer.More():
|
| sub_shape = explorer.Current()
|
| output_list.append(sub_shape)
|
| explorer.Next()
|
| else:
|
| output_list.append(shape)
|
|
|
| def parse_step_file(file_path, expand_compounds=True):
|
| """改进的STEP解析函数,支持展开复合体"""
|
| reader = STEPControl_Reader()
|
| reader.ReadFile(file_path)
|
| reader.TransferRoots()
|
| all_shapes = []
|
| for i in range(reader.NbShapes()):
|
| root_shape = reader.Shape(i + 1)
|
| if expand_compounds:
|
|
|
| StepParser._extract_subshapes(root_shape, all_shapes)
|
| else:
|
| all_shapes.append(root_shape)
|
|
|
| return all_shapes
|
|
|
| def visualize_single_shape(shapes, index=0):
|
| """交互式单实体可视化"""
|
|
|
| if not 0 <= index < len(shapes):
|
| raise ValueError(f"索引 {index} 超出范围 (0-{len(shapes) - 1})")
|
|
|
|
|
| display, start_display, _, _ = init_display()
|
| display.EraseAll()
|
|
|
|
|
| target_shape = shapes[index]
|
|
|
|
|
| shape_type = StepParser.analyze_shape(target_shape)
|
| print(f"正在显示实体 {index}:")
|
| print(f" - 类型: {shape_type}")
|
|
|
|
|
|
|
| display.DisplayShape(target_shape, color=Quantity_NOC_RED)
|
|
|
|
|
| bbox = Bnd_Box()
|
| brepbndlib.Add(target_shape, bbox)
|
| StepParser.display_bounding_box(display, bbox, color="white")
|
|
|
|
|
| display.FitAll()
|
| start_display()
|
|
|
| def interactive_viewer(shapes):
|
| """交互式实体查看器"""
|
| while True:
|
| try:
|
|
|
| print(f"\n当前文件包含 {len(shapes)} 个实体")
|
| print("输入要查看的实体索引 (q退出): ", end="")
|
|
|
|
|
| user_input = input().strip()
|
| if user_input.lower() == 'q':
|
| break
|
|
|
| index = int(user_input)
|
| StepParser.visualize_single_shape(shapes, index)
|
|
|
| except ValueError as e:
|
| print(f"错误输入: {e}")
|
| except KeyboardInterrupt:
|
| break
|
|
|
|
|
|
|
| def visualize_shapes(shapes):
|
| """可视化所有解析出的形状"""
|
| display, start_display, add_menu, add_function = init_display()
|
|
|
|
|
| def random_color():
|
| return Quantity_Color(*np.random.rand(3), Quantity_TOC_RGB)
|
|
|
|
|
| def display_compound(compound, color=None):
|
| explorer = TopExp_Explorer(compound, TopAbs_SOLID)
|
| while explorer.More():
|
| solid = explorer.Current()
|
| display.DisplayShape(solid, color=color or random_color())
|
| explorer.Next()
|
|
|
| for idx, shape in enumerate(shapes):
|
| shape_type = StepParser.analyze_shape(shape)
|
| print(f"Shape {idx}: {shape_type}")
|
|
|
| try:
|
|
|
| if shape_type == "Compound":
|
| display_compound(shape)
|
| else:
|
| display.DisplayShape(shape, color=random_color())
|
| except Exception as e:
|
| print(f"Error displaying shape {idx}: {str(e)}")
|
|
|
| display.FitAll()
|
| start_display()
|
|
|
| def display_bounding_box(display, bbox, color="white"):
|
| """将包围盒转换为线框显示"""
|
| min_corner = bbox.CornerMin()
|
| max_corner = bbox.CornerMax()
|
|
|
|
|
| pnts = [
|
| gp_Pnt(min_corner.X(), min_corner.Y(), min_corner.Z()),
|
| gp_Pnt(max_corner.X(), min_corner.Y(), min_corner.Z()),
|
| gp_Pnt(max_corner.X(), max_corner.Y(), min_corner.Z()),
|
| gp_Pnt(min_corner.X(), max_corner.Y(), min_corner.Z()),
|
| gp_Pnt(min_corner.X(), min_corner.Y(), max_corner.Z()),
|
| gp_Pnt(max_corner.X(), min_corner.Y(), max_corner.Z()),
|
| gp_Pnt(max_corner.X(), max_corner.Y(), max_corner.Z()),
|
| gp_Pnt(min_corner.X(), max_corner.Y(), max_corner.Z())
|
| ]
|
|
|
|
|
| edges = []
|
| indices = [(0, 1), (1, 2), (2, 3), (3, 0),
|
| (4, 5), (5, 6), (6, 7), (7, 4),
|
| (0, 4), (1, 5), (2, 6), (3, 7)]
|
|
|
| for i, j in indices:
|
| edge = BRepBuilderAPI_MakeEdge(pnts[i], pnts[j]).Edge()
|
| display.DisplayShape(edge, color=color) |