def __init__(self, filename, layer_name='layer-00'): logger.info("StepOcafExporter instantiated with " "filename : %s" % filename) check_exporter_filename(filename, step_extensions) check_overwrite(filename) self.filename = filename self.h_doc = h_doc = Handle_TDocStd_Document() # logger.info("Empty Doc?", h_doc.IsNull()) if h_doc.IsNull(): logger.info("Empty Doc?") # Create the application app = _XCAFApp.XCAFApp_Application_GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool().ShapeTool(doc.Main()) l_colors = XCAFDoc_DocumentTool().ColorTool(doc.Main()) l_layers = XCAFDoc_DocumentTool().LayerTool(doc.Main()) _ = TDF_LabelSequence() _ = TDF_LabelSequence() # TopoDS_Shape aShape; self.shape_tool = h_shape_tool.GetObject() self.top_label = self.shape_tool.NewShape() self.colors = l_colors.GetObject() self.layers = l_layers.GetObject() self.current_color = Quantity_Color(Quantity_NOC_RED) self.current_layer = self.layers.AddLayer( TCollection_ExtendedString(layer_name)) self.layer_names = {}
def __init__(self, name="name", tol=1.0E-10): self.name = name self.step = STEPCAFControl_Writer() self.step.SetNameMode(True) self.doc = TDocStd_Document(TCollection_ExtendedString("")) self.x_app = XCAFApp_Application.GetApplication() self.x_app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), self.doc) self.shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) Interface_Static_SetCVal("write.step.schema", "AP214") Interface_Static_SetCVal('write.step.unit', 'mm')
def __init__(self, title): # Create the application and document doc = TDocStd_Document(TCollection_ExtendedString(title)) app = XCAFApp_Application_GetApplication() app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc) self.app = app self.doc = doc # Initialize tools self.shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) self.shape_tool.SetAutoNaming(True) self.color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) self.layer_tool = XCAFDoc_DocumentTool_LayerTool(doc.Main()) self.l_materials = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) self.allChildLabels = []
def saveDoc(self, filename="foo.caf"): """Save doc to file (for educational purposes) (not working yet) https://www.opencascade.com/doc/occt-7.4.0/overview/html/occt_user_guides__ocaf.html#occt_ocaf_11 """ frmte = TCollection_ExtendedString("Xml-XCAF") #frmta = TCollection_AsciiString("MDTV-CAF") self.app.DefineFormat(TCollection_AsciiString("DocumentFormat"), TCollection_AsciiString("MDTV-CAF"), TCollection_AsciiString("caf"), XmlXCAFDrivers_DocumentRetrievalDriver(), XmlXCAFDrivers_DocumentStorageDriver(frmte)) logger.debug("Saving doc to file") savefilename = TCollection_ExtendedString(filename) self.app.SaveAs(self.doc, savefilename)
def export_STEPFile_single(shape, filename, tol=1.0E-6): """ Exports a .stp file containing the input shapes Parameters ---------- shape : TopoDS_Shape filename : string The output filename """ step = STEPCAFControl_Writer() step.SetNameMode(True) step.SetPropsMode(True) h_doc = TDocStd_Document() x_app = XCAFApp_Application.GetApplication().GetObject() x_app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) shape_tool = h_shape_tool.GetObject() Interface_Static_SetCVal("write.step.schema", "AP214") # transfer shapes print(filename) shape_tool.AddShape(shape) step.Transfer(h_doc, STEPControl_AsIs) status = step.Write(filename) assert(status == IFSelect_RetDone)
def test_write_step_file(self): ''' Exports a colored box into a STEP file ''' ### initialisation h_doc = Handle_TDocStd_Document() assert (h_doc.IsNull()) # Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) l_Colors = XCAFDoc_DocumentTool_ColorTool(doc.Main()) shape_tool = h_shape_tool.GetObject() colors = l_Colors.GetObject() ### create the shape to export test_shape = BRepPrimAPI_MakeBox(100., 100., 100.).Shape() ### add shape shp_label = shape_tool.AddShape(test_shape) ### set a color for this shape r = 1 g = b = 0.5 red_color = Quantity_Color(r, g, b, 0) colors.SetColor(shp_label, red_color, XCAFDoc_ColorGen) # write file WS = XSControl_WorkSession() writer = STEPCAFControl_Writer(WS.GetHandle(), False) writer.Transfer(h_doc, STEPControl_AsIs) status = writer.Write("./test_io/test_ocaf_generated.stp") assert status assert os.path.isfile("./test_io/test_ocaf_generated.stp")
def test_write_step_file(self) -> None: """Exports a colored box into a STEP file""" ### initialisation doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc")) self.assertTrue(doc is not None) # Get root assembly shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main()) colors = XCAFDoc_DocumentTool.ColorTool(doc.Main()) ### create the shape to export test_shape = BRepPrimAPI_MakeBox(100.0, 100.0, 100.0).Shape() ### add shape shp_label = shape_tool.AddShape(test_shape) ### set a color for this shape r = 1.0 g = b = 0.5 red_color = Quantity_Color(r, g, b, Quantity_TypeOfColor.Quantity_TOC_RGB) colors.SetColor(shp_label, red_color, XCAFDoc_ColorGen) # write file WS = XSControl_WorkSession() writer = STEPCAFControl_Writer(WS, False) writer.Transfer(doc, STEPControl_AsIs) status = writer.Write("./test_io/test_ocaf_generated.stp") self.assertTrue(status) self.assertTrue(os.path.isfile("./test_io/test_ocaf_generated.stp"))
def read_step_file_shapes(filename): _shapes = [] # create an handle to a document h_doc = TDocStd_Document() # Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetNameMode(True) status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: step_reader.Transfer(doc) labels = TDF_LabelSequence() shape_tool = h_shape_tool.GetObject() h_shape_tool.GetObject().GetFreeShapes(labels) print("Number of shapes at root :%i" % labels.Length()) for i in range(labels.Length()): label = labels.Value(i + 1) a_shape = h_shape_tool.GetObject().GetShape(label) _shapes.append(a_shape) return _shapes
def test_read_step_file(self) -> None: """Reads the previous step file""" # create an handle to a document doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc")) # Get root assembly shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main()) l_colors = XCAFDoc_DocumentTool.ColorTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile("./test_io/test_ocaf.stp") if status == IFSelect_RetDone: step_reader.Transfer(doc) labels = TDF_LabelSequence() color_labels = TDF_LabelSequence() shape_tool.GetFreeShapes(labels) self.assertEqual(labels.Length(), 1) sub_shapes_labels = TDF_LabelSequence() self.assertFalse(shape_tool.IsAssembly(labels.Value(1))) shape_tool.GetSubShapes(labels.Value(1), sub_shapes_labels) self.assertEqual(sub_shapes_labels.Length(), 0) l_colors.GetColors(color_labels) self.assertEqual(color_labels.Length(), 1) label_shp = labels.Value(1) a_shape = shape_tool.GetShape(label_shp) self.assertFalse(a_shape.IsNull())
def __init__(self, binary=True): if binary: self._fmt = 'BinXCAF' self._ext = '.xbf' else: self._fmt = 'XmlXCAF' self._ext = '.xml' # Get application self._app = XCAFApp_Application.GetApplication() if binary: binxcafdrivers.DefineFormat(self._app) else: xmlxcafdrivers.DefineFormat(self._app) # Initialize document fmt = TCollection_ExtendedString(self._fmt) self._doc = TDocStd_Document(fmt) self._app.InitDocument(self._doc) # Exchange data self._shape = None self._step_writer = None self._step_fp = None self._init_tool()
def test_create_app(self): ''' Creates an OCAF app and an empty document ''' # create an handle to a document h_doc = Handle_TDocStd_Document() assert (h_doc.IsNull()) # Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc)
def set_name(self, name): """ Set label name. :param str name: The name. :return: None. """ txt = TCollection_ExtendedString(name) TDataStd_Name.Set_(self._label, txt)
def createDoc(self): """Create XCAF doc with an empty assembly at entry 0:1:1:1. This is done only once in __init__.""" # Create the application and document with empty rootLabel title = "Main document" doc = TDocStd_Document(TCollection_ExtendedString(title)) app = XCAFApp_Application_GetApplication() app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc) shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) # type(doc.Main()) = <class 'OCC.Core.TDF.TDF_Label'> # 0:1 doc.Main().EntryDumpToString() # 0:1:1 shape_tool is at this label entry # 0:1:2 color_tool at this entry # 0:1:1:1 rootLabel created at this entry rootLabel = shape_tool.NewShape() self.setLabelName(rootLabel, "Top") return doc
def read_file(self, fname): """Read STEP file and return <TDocStd_Document>.""" # Create the application, empty document and shape_tool doc = TDocStd_Document(TCollection_ExtendedString("STEP")) app = XCAFApp_Application_GetApplication() app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc) self.shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) self.shape_tool.SetAutoNaming(True) # Read file and return populated doc step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(fname) if status == IFSelect_RetDone: step_reader.Transfer(doc) return doc
def read_step_file_with_attribute2(filename): """ Read a step file and returns a shape (geometrical information). This uses the XDE of OCCD and will also be able to extract the attribute information such as colour or name or layer. """ h_doc = Handle_TDocStd_Document() # print "Empty Doc?", h_doc.IsNull() ### Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) ### Get tools, here only enable the colour attribute doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) h_colour_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) # l_Layers = XCAFDoc_DocumentTool_LayerTool(doc.Main()) # l_materials = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) shape_tool = h_shape_tool.GetObject() colour_tool = h_colour_tool.GetObject() ### Read files STEPReader = STEPCAFControl_Reader() STEPReader.SetColorMode(True) # STEPReader.SetLayerMode(True) # STEPReader.SetNameMode(True) # STEPReader.SetMatMode(True) status = STEPReader.ReadFile(filename) STEPReader.Reader().PrintCheckLoad(True, 0) if status == IFSelect_RetDone: STEPReader.Transfer(doc.GetHandle()) ### Get root assembly shapeLabels = TDF_LabelSequence() shape_tool.GetFreeShapes(shapeLabels) # print ('Number of shapes at root :%i'%shapeLabels.Length()) ### Here we only have one solid in the model so we directly use the first solid ### If there are more, please use the for loop to get all solids shape = shape_tool.GetShape(shapeLabels.Value(1)) topo = Topo(shape) # for i in range(shapeLabels.Length()): # #print(Labels.Value(i+1).Tag()) # shape=shape_tool.GetShape(shapeLabels.Value(i+1)) # shapes.append(shape) return [topo, colour_tool]
def save_as(self, fn): """ Save the document. :param str fn: The filename. :return: *True* if sucessfully saved, *False* if not. :rtype: bool """ if not fn.endswith(self._ext): fn += self._ext txt = TCollection_ExtendedString(fn) status = self._app.SaveAs(self._doc, txt) return status == PCDM_SS_OK
def set_layer(self, layer_name): r"""set the current layer name if the layer has already been set before, that TDF_Label will be used Parameters ---------- layer_name: str name of the layer """ if layer_name in self.layer_names: self.current_layer = self.layer_names[layer_name] else: self.current_layer = self.layers.AddLayer( TCollection_ExtendedString(layer_name)) self.layer_names[layer_name] = self.current_layer
def saveStep(self): """Export self.doc to STEP file.""" prompt = 'Choose filename for step file.' fnametuple = QFileDialog.getSaveFileName( None, prompt, './', "STEP files (*.stp *.STP *.step)") fname, _ = fnametuple if not fname: print("Save step cancelled.") return # Reconstruct XCAFDoc related code from stepXD.StepImporter labels = TDF_LabelSequence() shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) shape_tool.GetShapes(labels) logger.info('Number of labels at root : %i', labels.Length()) try: rootlabel = labels.Value(1) # First label at root except RuntimeError: return name = rootlabel.GetLabelName() logger.info('Name of root label: %s', name) isAssy = shape_tool.IsAssembly(rootlabel) logger.info("First label at root holds an assembly? %s", isAssy) # Modify self.doc by adding active part to rootlabel. #Standard_Boolean expand = Standard_False; //default #TDF_Label aLabel = myAssembly->AddComponent (aShape [,expand]); newLabel = shape_tool.AddComponent(rootlabel, self.activePart, True) #set a name to newlabel (as a reminder using OCAF), use: #TCollection_ExtendedString aName ...; #// contains the desired name for this Label (ASCII) #TDataStd_Name::Set (aLabel, aName); newName = TCollection_ExtendedString( self._nameDict[self.activePartUID]) TDataStd_Name.Set(newLabel, newName) logger.info('Name of new part: %s', newName) #myAssembly->UpdateAssemblies(); shape_tool.UpdateAssemblies() # initialize the STEP exporter step_writer = STEPCAFControl_Writer() # transfer shapes and write file step_writer.Transfer(self.doc) status = step_writer.Write(fname) assert status == IFSelect_RetDone
def open(self, fn): """ Open a document. :param str fn: The filename. :return: *True* if opened, *False* if not. :rtype: bool """ if not fn.endswith(self._ext): fn += self._ext txt = TCollection_ExtendedString(fn) status, self._doc = self._app.Open(txt, self._doc) if status != PCDM_RS_OK: return False self._init_tool() return True
def test_read_step_file(self): ''' Reads the previous step file ''' # create an handle to a document h_doc = Handle_TDocStd_Document() # Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) l_colors = XCAFDoc_DocumentTool_ColorTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile("./test_io/test_ocaf.stp") if status == IFSelect_RetDone: step_reader.Transfer(doc.GetHandle()) labels = TDF_LabelSequence() color_labels = TDF_LabelSequence() shape_tool = h_shape_tool.GetObject() h_shape_tool.GetObject().GetFreeShapes(labels) assert (labels.Length() == 1) sub_shapes_labels = TDF_LabelSequence() assert (not shape_tool.IsAssembly(labels.Value(1))) shape_tool.GetSubShapes(labels.Value(1), sub_shapes_labels) assert (sub_shapes_labels.Length() == 0) l_colors.GetObject().GetColors(color_labels) assert (color_labels.Length() == 1) label_shp = labels.Value(1) a_shape = h_shape_tool.GetObject().GetShape(label_shp) assert (not a_shape.IsNull())
from OCC.Core.XCAFApp import XCAFApp_Application from OCC.Core.XCAFDoc import (XCAFDoc_DocumentTool_ShapeTool, XCAFDoc_DocumentTool_ColorTool, XCAFDoc_DocumentTool_LayerTool, XCAFDoc_DocumentTool_MaterialTool) from OCC.Core.STEPCAFControl import STEPCAFControl_Reader from OCC.Core.IFSelect import IFSelect_RetDone from OCC.Core.TDF import TDF_LabelSequence from OCC.Display.SimpleGui import init_display filename = '../assets/models/as1_pe_203.stp' _shapes = [] # create an handle to a document doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc")) # Get root assembly shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) l_colors = XCAFDoc_DocumentTool_ColorTool(doc.Main()) l_layers = XCAFDoc_DocumentTool_LayerTool(doc.Main()) l_materials = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(filename) if status == IFSelect_RetDone:
def setLabelName(self, label, name): TDataStd_Name.Set(label, TCollection_ExtendedString(name))
def test_create_doc(self) -> None: """Creates an OCAF app and an empty document""" # create an handle to a document doc = TDocStd_Document(TCollection_ExtendedString("MDTV-CAF")) self.assertFalse(doc is None)
def read_file(self): r"""Read file""" logger.info("Reading STEP file") h_doc = Handle_TDocStd_Document() # Create the application app = _XCAFApp.XCAFApp_Application_GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool().ShapeTool(doc.Main()) color_tool = XCAFDoc_DocumentTool().ColorTool(doc.Main()) layer_tool = XCAFDoc_DocumentTool().LayerTool(doc.Main()) _ = XCAFDoc_DocumentTool().MaterialTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(str(self.filename)) if status == IFSelect_RetDone: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(doc.GetHandle()) labels = TDF_LabelSequence() _ = TDF_LabelSequence() # TopoDS_Shape a_shape; _ = h_shape_tool.GetObject() h_shape_tool.GetObject().GetFreeShapes(labels) logger.info('Number of shapes at root :%i' % labels.Length()) # for i in range(labels.Length()): # a_shape = h_shape_tool.GetObject().GetShape(labels.Value(i+1)) # logger.debug("%i - type : %s" % (i, a_shape.ShapeType())) # sub_shapes_labels = TDF_LabelSequence() # print("Is Assembly?", shape_tool.IsAssembly(labels.Value(i + 1))) # # sub_shapes = shape_tool.getsubshapes(labels.Value(i+1), # sub_shapes_labels) # # sub_shapes = shape_tool.FindSubShape(labels.Value(i + 1), # a_shape, labels.Value(i + 1)) # print('Number of subshapes in the assembly : %i' % # sub_shapes_labels.Length()) # # color_tool.GetObject().GetColors(color_labels) # logger.info('Number of colors : %i' % color_labels.Length()) for i in range(labels.Length()): # print i label = labels.Value(i + 1) logger.debug("Label : %s" % label) a_shape = h_shape_tool.GetObject().GetShape(labels.Value(i + 1)) # string_seq = TColStd_HSequenceOfExtendedString() # string_seq is an TColStd_HSequenceOfExtendedString string_seq = layer_tool.GetObject().GetLayers(a_shape) color = Quantity_Color() _ = color_tool.GetObject().GetColor(a_shape, XCAFDoc_ColorSurf, color) logger.info("The shape type is : %i" % a_shape.ShapeType()) if a_shape.ShapeType() == TopAbs_COMPOUND: logger.info("The shape type is TopAbs_COMPOUND") topo = Topo(a_shape) logger.info("Nb of compounds : %i" % topo.number_of_compounds) logger.info("Nb of solids : %i" % topo.number_of_solids) logger.info("Nb of shells : %i" % topo.number_of_shells) for solid in topo.solids: logger.info("Adding solid to the shapes list") self._shapes.append(solid) elif a_shape.ShapeType() == TopAbs_SOLID: logger.info("The shape type is TopAbs_SOLID") self._shapes.append(a_shape) self._colors.append(color) self._layers.append(string_seq) return True
def to_string(_string): from OCC.Core.TCollection import TCollection_ExtendedString return TCollection_ExtendedString(_string)
def test_create_doc(self): ''' Creates an OCAF app and an empty document ''' # create an handle to a document doc = TDocStd_Document(TCollection_ExtendedString("MDTV-CAF")) self.assertFalse(doc.IsNull())
def read_step_file_with_names_colors(filename): """ Returns list of tuples (topods_shape, label, color) Use OCAF. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) # the list: output_shapes = {} # create an handle to a document doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc")) # Get root assembly shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) #layer_tool = XCAFDoc_DocumentTool_LayerTool(doc.Main()) #mat_tool = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) 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(filename) if status == IFSelect_RetDone: step_reader.Transfer(doc) locs = [] def _get_sub_shapes(lab, loc): #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) l_subss = TDF_LabelSequence() shape_tool.GetSubShapes(lab, l_subss) #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() print("Name :", name) if shape_tool.IsAssembly(lab): l_c = TDF_LabelSequence() shape_tool.GetComponents(lab, l_c) for i in range(l_c.Length()): label = l_c.Value(i + 1) if shape_tool.IsReference(label): #print("\n######## reference label :", label) label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) #print(" loc :", loc) #trans = loc.Transformation() #print(" tran form :", trans.Form()) #rot = trans.GetRotation() #print(" rotation :", rot) #print(" X :", rot.X()) #print(" Y :", rot.Y()) #print(" Z :", rot.Z()) #print(" W :", rot.W()) #tran = trans.TranslationPart() #print(" translation :", tran) #print(" X :", tran.X()) #print(" Y :", tran.Y()) #print(" Z :", tran.Z()) locs.append(loc) #print(">>>>") #lvl += 1 _get_sub_shapes(label_reference, loc) #lvl -= 1 #print("<<<<") locs.pop() elif shape_tool.IsSimpleShape(lab): #print("\n######## simpleshape label :", lab) shape = shape_tool.GetShape(lab) #print(" all ass locs :", locs) loc = TopLoc_Location() for l in locs: #print(" take loc :", l) loc = loc.Multiplied(l) #trans = loc.Transformation() #print(" FINAL loc :") #print(" tran form :", trans.Form()) #rot = trans.GetRotation() #print(" rotation :", rot) #print(" X :", rot.X()) #print(" Y :", rot.Y()) #print(" Z :", rot.Z()) #print(" W :", rot.W()) #tran = trans.TranslationPart() #print(" translation :", tran) #print(" X :", tran.X()) #print(" Y :", tran.Y()) #print(" Z :", tran.Z()) 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)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) shape_disp = BRepBuilderAPI_Transform( shape, loc.Transformation()).Shape() if not shape_disp in output_shapes: output_shapes[shape_disp] = [lab.GetLabelName(), c] for i in range(l_subss.Length()): lab_subs = l_subss.Value(i + 1) #print("\n######## simpleshape subshape label :", lab) shape_sub = shape_tool.GetShape(lab_subs) c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color colorSet = False if (color_tool.GetInstanceColor(shape_sub, 0, c) or color_tool.GetInstanceColor(shape_sub, 1, c) or color_tool.GetInstanceColor(shape_sub, 2, c)): color_tool.SetInstanceColor(shape_sub, 0, c) color_tool.SetInstanceColor(shape_sub, 1, c) color_tool.SetInstanceColor(shape_sub, 2, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab_subs, 0, c) or color_tool.GetColor(lab_subs, 1, c) or color_tool.GetColor(lab_subs, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) shape_to_disp = BRepBuilderAPI_Transform( shape_sub, loc.Transformation()).Shape() # position the subshape to display if not shape_to_disp in output_shapes: output_shapes[shape_to_disp] = [lab_subs.GetLabelName(), 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) _get_shapes() return output_shapes
def to_string(_string): return TCollection_ExtendedString(_string)
from OCC.Core.TDF import TDF_LabelSequence, TDF_Label, TDF_Tool from OCC.Core.TDataStd import Handle_TDataStd_Name, TDataStd_Name_GetID from OCC.Core.TCollection import TCollection_ExtendedString, TCollection_AsciiString from OCC.Core.Quantity import Quantity_Color from OCC.Core.TopLoc import TopLoc_Location from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Transform from OCC.Display.SimpleGui import init_display filename = '../assets/models/as1-oc-214.stp' # create an handle to a document h_doc = Handle_TDocStd_Document() # Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) h_color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) h_layer_tool = XCAFDoc_DocumentTool_LayerTool(doc.Main()) h_mat_tool = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(filename)
def read_step_file_with_names_colors(filename): """ Returns list of tuples (topods_shape, label, color) Use OCAF. """ # the list: output_shapes = [] # create an handle to a document doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc")) # Get root assembly shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) #layer_tool = XCAFDoc_DocumentTool_LayerTool(doc.Main()) #mat_tool = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: step_reader.Transfer(doc) shape_tool.SetAutoNaming(True) #lvl = 0 locs = [] #cnt = 0 def _get_label_name(lab): entry = TCollection_AsciiString() TDF_Tool.Entry(lab, entry) n = TDataStd_Name() lab.FindAttribute(TDataStd_Name_GetID(), n) if n: return n.Get().PrintToString() return "No Name" def _get_sub_shapes(lab, loc): #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) l_subss = TDF_LabelSequence() shape_tool.GetSubShapes(lab, l_subss) #print("Nb subshapes :", l_subss.Length()) l_comps = TDF_LabelSequence() shape_tool.GetComponents(lab, l_comps) #print("Nb components :", l_comps.Length()) #print() if shape_tool.IsAssembly(lab): l_c = TDF_LabelSequence() shape_tool.GetComponents(lab, l_c) for i in range(l_c.Length()): label = l_c.Value(i + 1) if shape_tool.IsReference(label): #print("\n######## reference label :", label) label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) #print(" loc :", loc) #trans = loc.Transformation() #print(" tran form :", trans.Form()) #rot = trans.GetRotation() #print(" rotation :", rot) #print(" X :", rot.X()) #print(" Y :", rot.Y()) #print(" Z :", rot.Z()) #print(" W :", rot.W()) #tran = trans.TranslationPart() #print(" translation :", tran) #print(" X :", tran.X()) #print(" Y :", tran.Y()) #print(" Z :", tran.Z()) locs.append(loc) #print(">>>>") #lvl += 1 _get_sub_shapes(label_reference, loc) #lvl -= 1 #print("<<<<") locs.pop() elif shape_tool.IsSimpleShape(lab): #print("\n######## simpleshape label :", lab) shape = shape_tool.GetShape(lab) #print(" all ass locs :", locs) loc = TopLoc_Location() for i in range(len(locs)): #print(" take loc :", locs[i]) loc = loc.Multiplied(locs[i]) #trans = loc.Transformation() #print(" FINAL loc :") #print(" tran form :", trans.Form()) #rot = trans.GetRotation() #print(" rotation :", rot) #print(" X :", rot.X()) #print(" Y :", rot.Y()) #print(" Z :", rot.Z()) #print(" W :", rot.W()) #tran = trans.TranslationPart() #print(" translation :", tran) #print(" X :", tran.X()) #print(" Y :", tran.Y()) #print(" Z :", tran.Z()) shape = BRepBuilderAPI_Transform(shape, loc.Transformation()).Shape() c = Quantity_Color() # colorSet = False # if (color_tool.GetInstanceColor(shape, 0, c) or # color_tool.GetInstanceColor(shape, 1, c) or # color_tool.GetInstanceColor(shape, 2, c)): # for i in (0, 1, 2): # color_tool.SetInstanceColor(shape, i, c) # colorSet = True # n = c.Name(c.Red(), c.Green(), c.Blue()) # #print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # if not colorSet: color_tool.GetColor(lab, 0, c) color_tool.GetColor(lab, 1, c) color_tool.GetColor(lab, 2, c) #for i in (0, 1, 2): # color_tool.SetInstanceColor(shape, i, c) #n = c.Name(c.Red(), c.Green(), c.Blue()) #print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # for i in range(l_subss.Length()): # lab = l_subss.Value(i+1) # print("\n######## simpleshape subshape label :", lab) # shape_sub = shape_tool.GetShape(lab) # c = Quantity_Color() # colorSet = False # if (color_tool.GetInstanceColor(shape_sub, 0, c) or # color_tool.GetInstanceColor(shape_sub, 1, c) or # color_tool.GetInstanceColor(shape_sub, 2, c)): # for i in (0, 1, 2): # color_tool.SetInstanceColor(shape_sub, i, c) # colorSet = True # n = c.Name(c.Red(), c.Green(), c.Blue()) # #print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # if not colorSet: # if (color_tool.GetColor(lab, 0, c) or # color_tool.GetColor(lab, 1, c) or # color_tool.GetColor(lab, 2, c)): # for i in (0, 1, 2): # color_tool.SetInstanceColor(shape, i, c) # n = c.Name(c.Red(), c.Green(), c.Blue()) # #print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) output_shapes.append([shape, _get_label_name(lab), 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() root = labels.Value(1) _get_sub_shapes(root, None) _get_shapes() return output_shapes