import os
from OCC.Core.IFSelect import IFSelect_RetDone
from OCC.Core.STEPCAFControl import STEPCAFControl_Reader
from OCC.Core.TCollection import TCollection_ExtendedString
from OCC.Core.TDocStd import TDocStd_Document
from OCC.Core.VrmlAPI import VrmlAPI_Writer
from OCC.Core.VrmlData import VrmlData_WorldInfo
from OCC.Core.XCAFDoc import XCAFDoc_ShapeTool, XCAFDoc_DocumentTool, XCAFDoc_DocumentTool_ShapeTool
from OCC.Core.XCAFApp import XCAFApp_Application_GetApplication
from OCC.Core.XCAFDoc import XCAFDoc_DocumentTool_ShapeTool, xcafdoc
from OCC.Core.BRep import BRep_Tool
from OCC.Core.TDF import TDF_LabelSequence, TDF_Label, TDF_ChildIterator, TDF_AttributeIterator, TDF_Tool, TDF_AttributeMap, TDF_Attribute, TDF_ChildIDIterator
from OCC.Core.TCollection import TCollection_AsciiString
from OCC.Core.TDataStd import TDataStd_TreeNode
from OCC.Core.Standard import Standard_GUID #, Standard_Handle
from OCC.Core.TNaming import TNaming_UsedShapes
from OCC.Extend.TopologyUtils import TopologyExplorer
from OCC.Extend.TopologyUtils import is_edge, is_wire, discretize_edge, discretize_wire
from OCC.Extend.DataExchange import read_step_file_with_names_colors, read_step_file
from OCC.Display.WebGl.x3dom_renderer import X3DExporter, X3DomRenderer
from OCC.Core.TopAbs import topabs
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
import xml.etree.ElementTree as ET
from IPython.display import HTML
import x3d.x3d as X3D
import re
x3d.py package loaded, have fun with X3D Graphics!
#stp_filename = 'VentilatorAP203' #'as1_pe_203'
stp_filename = 'as1-oc-214'
#stp_filename = 'as1_pe_203'
stp_path = os.path.join('assets', stp_filename + '.stp')
# load the STEP file
doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc"))
step_reader = STEPCAFControl_Reader()
step_reader.SetColorMode(True)
step_reader.SetLayerMode(True)
step_reader.SetNameMode(True)
step_reader.SetMatMode(True)
step_reader.SetGDTMode(True)
status = step_reader.ReadFile(stp_path)
if status == IFSelect_RetDone:
step_reader.Transfer(doc)
else:
raise IOError("STEP file could not be read.")
doc
<class 'TDocStd_Document'>
##Copyright 2018 Thomas Paviot (tpaviot@gmail.com)
##(C) 2020 Andreas Plesch
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC. If not, see <http://www.gnu.org/licenses/>.
import os
from OCC.Core.TopoDS import TopoDS_Shape
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
from OCC.Core.StlAPI import stlapi_Read, StlAPI_Writer
from OCC.Core.BRep import BRep_Builder
from OCC.Core.gp import gp_Pnt, gp_Dir, gp_Pnt2d
from OCC.Core.Bnd import Bnd_Box2d
from OCC.Core.TopoDS import TopoDS_Compound
from OCC.Core.IGESControl import IGESControl_Reader, IGESControl_Writer
from OCC.Core.STEPControl import STEPControl_Reader, STEPControl_Writer, STEPControl_AsIs
from OCC.Core.Interface import Interface_Static_SetCVal
from OCC.Core.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Core.TDocStd import TDocStd_Document
from OCC.Core.XCAFDoc import (XCAFDoc_DocumentTool_ShapeTool,
XCAFDoc_DocumentTool_ColorTool)
from OCC.Core.STEPCAFControl import STEPCAFControl_Reader
from OCC.Core.TDF import TDF_LabelSequence, TDF_Label
from OCC.Core.TCollection import TCollection_ExtendedString
from OCC.Core.Quantity import Quantity_Color, Quantity_TOC_RGB
from OCC.Core.TopLoc import TopLoc_Location
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Transform
from OCC.Extend.TopologyUtils import (discretize_edge, get_sorted_hlr_edges,
list_of_shapes_to_compound)
try:
import svgwrite
HAVE_SVGWRITE = True
except ImportError:
HAVE_SVGWRITE = False
def read_document_with_names_colors(doc):
""" Returns list of tuples (topods_shape, label, color)
Use OCAF.
"""
output_shapes = {}
scene = []
visited = {}
DEFset = set()
# Get root assembly
shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main())
color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main())
locs = []
def _get_sub_shapes(lab, loc, parent):
#global cnt, lvl
#cnt += 1
#print("\n[%d] level %d, handling LABEL %s\n" % (cnt, lvl, _get_label_name(lab)))
#print()
#print(lab.DumpToString())
#print()
#print("Is Assembly :", shape_tool.IsAssembly(lab))
#print("Is Free :", shape_tool.IsFree(lab))
#print("Is Shape :", shape_tool.IsShape(lab))
#print("Is Compound :", shape_tool.IsCompound(lab))
#print("Is Component :", shape_tool.IsComponent(lab))
#print("Is SimpleShape :", shape_tool.IsSimpleShape(lab))
#print("Is Reference :", shape_tool.IsReference(lab))
#users = TDF_LabelSequence()
#users_cnt = shape_tool.GetUsers(lab, users)
#print("Nr Users :", users_cnt)
#print("Nb subshapes :", l_subss.Length())
#l_comps = TDF_LabelSequence()
#shape_tool.GetComponents(lab, l_comps)
#print("Nb components :", l_comps.Length())
#print()
name = lab.GetLabelName()
labelString = lab.EntryDumpToString()
if labelString in visited:
return
visited[labelString] = lab
if shape_tool.IsAssembly(lab):
node = {
'node' : 'Group',
'DEF' : labelString,
'name' : name,
'children' : []
}
l_c = TDF_LabelSequence()
shape_tool.GetComponents(lab, l_c)
for i in range(l_c.Length()):
label = l_c.Value(i+1)
print("Group Name DEF :", name, labelString )
if shape_tool.IsReference(label):
print("######## component label :", label.GetLabelName() )
loc = shape_tool.GetLocation(label)
print(" Transform loc DEF :", loc.HashCode(100))
trafo = {
'node' : 'Transform',
'DEF' : label.EntryDumpToString(),
'name' : 'reference location',
'transform' : loc,
'children': []
}
locs.append(loc)
print("loc chain depth :", len(locs))
label_reference = TDF_Label()
shape_tool.GetReferredShape(label, label_reference)
print("######## Transform USE to DEF ==> referenced label :", label_reference.GetLabelName() )
reference_entry = label_reference.EntryDumpToString()
if reference_entry not in DEFset:
DEFset.add(reference_entry)
_get_sub_shapes(label_reference, loc, trafo['children'])
else:
trafo['children'].append({
'node' : 'Transform',
'USE' : reference_entry,
'refname' : label_reference.GetLabelName()
})
locs.pop()
node['children'].append(trafo)
elif shape_tool.IsSimpleShape(lab):
print("Transform DEF Shape Name :", name, labelString )
shape = shape_tool.GetShape(lab)
#print(" all ass locs :", locs)
# loc = TopLoc_Location()
# for l in locs:
# loc = loc.Multiplied(l)
c = _set_color(lab, shape)
n = c.Name(c.Red(), c.Green(), c.Blue())
print(' instance color Name & RGB: ', n, c.Red(), c.Green(), c.Blue())
labloc = shape_tool.GetLocation(lab)
print(" Shape Transform: ", labloc.HashCode(100))
node = {
'node' : 'Transform',
'DEF' : labelString,
'name' : name,
}
#shape_disp = BRepBuilderAPI_Transform(shape, loc.Transformation()).Shape()
#shape_disp = shape
#if not shape_disp in output_shapes:
# output_shapes[shape_disp] = [lab.GetLabelName(), c]
##subshapes
l_subss = TDF_LabelSequence()
shape_tool.GetSubShapes(lab, l_subss)
if (l_subss.Length() == 0 and labloc.IsIdentity()): # does not need transform
node['node'] = 'Shape'
node['shape'] = lab
node['name'] = name+'-shape'
node['color'] = f"{c.Red()} {c.Green()} {c.Blue()}"
else: # needs grouping or has transform
node['transform'] = labloc
node['children'] = []
node['transformhash'] = labloc.HashCode(100)
node['children'].append({
'node' : 'Shape',
'shape' : lab,
'name' : name+'-shape',
'color' : f"{c.Red()} {c.Green()} {c.Blue()}"
})
for i in range(l_subss.Length()):
lab_subs = l_subss.Value(i+1)
print("######## Transform DEF simpleshape subshape label :", lab.GetLabelName())
shape_sub = shape_tool.GetShape(lab_subs)
c = _set_color(lab_subs, shape_sub)
n = c.Name(c.Red(), c.Green(), c.Blue())
print(' shape color Name & RGB: ', n, c.Red(), c.Green(), c.Blue())
subloc = shape_tool.GetLocation(lab_subs)
print(" subshape Transform: ", subloc.HashCode(100))
node['children'].append({
'node' : 'SubShape',
'shape' : lab_subs,
'DEF' : lab_subs.EntryDumpToString(),
'name' : lab_subs.GetLabelName()+'-subshape',
'color' : f"{c.Red()} {c.Green()} {c.Blue()}",
'trafo' : subloc
})
#shape_to_disp = BRepBuilderAPI_Transform(shape_sub, loc.Transformation()).Shape()
#shape_to_disp = shape_sub
# position the subshape to display
#if not shape_to_disp in output_shapes:
# output_shapes[shape_to_disp] = [lab_subs.GetLabelName(), c]
parent.append(node)
def _set_color(lab, shape):
c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color
colorSet = False
if (color_tool.GetInstanceColor(shape, 0, c) or
color_tool.GetInstanceColor(shape, 1, c) or
color_tool.GetInstanceColor(shape, 2, c)):
colorSet = True
if not colorSet:
if (color_tool.GetColor(lab, 0, c) or
color_tool.GetColor(lab, 1, c) or
color_tool.GetColor(lab, 2, c)):
colorSet = True
if colorSet:
color_tool.SetInstanceColor(shape, 0, c)
color_tool.SetInstanceColor(shape, 1, c)
color_tool.SetInstanceColor(shape, 2, c)
return c
def _get_shapes():
labels = TDF_LabelSequence()
shape_tool.GetFreeShapes(labels)
#global cnt
#cnt += 1
print()
print("Number of shapes at root :", labels.Length())
print()
for i in range(labels.Length()):
root_item = labels.Value(i+1)
_get_sub_shapes(root_item, None, scene)
_get_shapes()
print('DONE')
return scene
scene=read_document_with_names_colors(doc)
Number of shapes at root : 1 Group Name DEF : as1 0:1:1:1 ######## component label : rod-assembly_1 Transform loc DEF : 25 loc chain depth : 1 ######## Transform USE to DEF ==> referenced label : rod-assembly Group Name DEF : rod-assembly 0:1:1:2 ######## component label : nut_1 Transform loc DEF : 73 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : nut Transform DEF Shape Name : nut 0:1:1:3 instance color Name & RGB: 412 1.0 0.0 0.0 Shape Transform: 1 Group Name DEF : rod-assembly 0:1:1:2 ######## component label : nut_2 Transform loc DEF : 21 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : nut Group Name DEF : rod-assembly 0:1:1:2 ######## component label : rod_1 Transform loc DEF : 29 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : rod Transform DEF Shape Name : rod 0:1:1:4 instance color Name & RGB: 79 1.0 0.5 0.0 Shape Transform: 1 Group Name DEF : as1 0:1:1:1 ######## component label : l-bracket-assembly_1 Transform loc DEF : 17 loc chain depth : 1 ######## Transform USE to DEF ==> referenced label : l-bracket-assembly Group Name DEF : l-bracket-assembly 0:1:1:5 ######## component label : nut-bolt-assembly_1 Transform loc DEF : 81 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : nut-bolt-assembly Group Name DEF : nut-bolt-assembly 0:1:1:6 ######## component label : bolt_1 Transform loc DEF : 49 loc chain depth : 3 ######## Transform USE to DEF ==> referenced label : bolt Transform DEF Shape Name : bolt 0:1:1:7 instance color Name & RGB: 22 0.0 0.0 1.0 Shape Transform: 1 Group Name DEF : nut-bolt-assembly 0:1:1:6 ######## component label : nut_3 Transform loc DEF : 65 loc chain depth : 3 ######## Transform USE to DEF ==> referenced label : nut Group Name DEF : l-bracket-assembly 0:1:1:5 ######## component label : nut-bolt-assembly_2 Transform loc DEF : 45 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : nut-bolt-assembly Group Name DEF : l-bracket-assembly 0:1:1:5 ######## component label : nut-bolt-assembly_3 Transform loc DEF : 13 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : nut-bolt-assembly Group Name DEF : l-bracket-assembly 0:1:1:5 ######## component label : l-bracket_1 Transform loc DEF : 37 loc chain depth : 2 ######## Transform USE to DEF ==> referenced label : l-bracket Transform DEF Shape Name : l-bracket 0:1:1:8 instance color Name & RGB: 229 0.0 1.0 0.0 Shape Transform: 1 Group Name DEF : as1 0:1:1:1 ######## component label : plate_1 Transform loc DEF : 61 loc chain depth : 1 ######## Transform USE to DEF ==> referenced label : plate Transform DEF Shape Name : plate 0:1:1:9 instance color Name & RGB: 512 0.800000011920929 1.0 0.0 Shape Transform: 1 Group Name DEF : as1 0:1:1:1 ######## component label : l-bracket-assembly_2 Transform loc DEF : 57 loc chain depth : 1 ######## Transform USE to DEF ==> referenced label : l-bracket-assembly DONE
scene
[{'node': 'Group', 'DEF': '0:1:1:1', 'name': 'as1', 'children': [{'node': 'Transform', 'DEF': '0:1:1:1:1', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Group', 'DEF': '0:1:1:2', 'name': 'rod-assembly', 'children': [{'node': 'Transform', 'DEF': '0:1:1:2:1', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Shape', 'DEF': '0:1:1:3', 'name': 'nut-shape', 'shape': <class 'TDF_Label'>, 'color': '1.0 0.0 0.0'}]}, {'node': 'Transform', 'DEF': '0:1:1:2:2', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Transform', 'USE': '0:1:1:3', 'refname': 'nut'}]}, {'node': 'Transform', 'DEF': '0:1:1:2:3', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Shape', 'DEF': '0:1:1:4', 'name': 'rod-shape', 'shape': <class 'TDF_Label'>, 'color': '1.0 0.5 0.0'}]}]}]}, {'node': 'Transform', 'DEF': '0:1:1:1:2', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Group', 'DEF': '0:1:1:5', 'name': 'l-bracket-assembly', 'children': [{'node': 'Transform', 'DEF': '0:1:1:5:1', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Group', 'DEF': '0:1:1:6', 'name': 'nut-bolt-assembly', 'children': [{'node': 'Transform', 'DEF': '0:1:1:6:1', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Shape', 'DEF': '0:1:1:7', 'name': 'bolt-shape', 'shape': <class 'TDF_Label'>, 'color': '0.0 0.0 1.0'}]}, {'node': 'Transform', 'DEF': '0:1:1:6:2', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Transform', 'USE': '0:1:1:3', 'refname': 'nut'}]}]}]}, {'node': 'Transform', 'DEF': '0:1:1:5:2', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Transform', 'USE': '0:1:1:6', 'refname': 'nut-bolt-assembly'}]}, {'node': 'Transform', 'DEF': '0:1:1:5:3', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Transform', 'USE': '0:1:1:6', 'refname': 'nut-bolt-assembly'}]}, {'node': 'Transform', 'DEF': '0:1:1:5:4', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Shape', 'DEF': '0:1:1:8', 'name': 'l-bracket-shape', 'shape': <class 'TDF_Label'>, 'color': '0.0 1.0 0.0'}]}]}]}, {'node': 'Transform', 'DEF': '0:1:1:1:3', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Shape', 'DEF': '0:1:1:9', 'name': 'plate-shape', 'shape': <class 'TDF_Label'>, 'color': '0.800000011920929 1.0 0.0'}]}, {'node': 'Transform', 'DEF': '0:1:1:1:4', 'name': 'reference location', 'transform': <class 'TopLoc_Location'>, 'children': [{'node': 'Transform', 'USE': '0:1:1:5', 'refname': 'l-bracket-assembly'}]}]}]