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, 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 find_components(self, comps): """Discover components from comps (LabelSequence) of an assembly. Components of an assembly are, by definition, references which refer to either a shape or another assembly. Components are essentially 'instances' of the referred shape or assembly, and carry a location vector specifing the location of the referred shape or assembly. """ for j in range(comps.Length()): c_label = comps.Value(j + 1) # component label <class 'TDF_Label'> c_name = c_label.GetLabelName() c_entry = c_label.EntryDumpToString() ref_label = TDF_Label() # label of referred shape (or assembly) is_ref = self.shape_tool.GetReferredShape(c_label, ref_label) if is_ref: # just in case all components are not references ref_entry = ref_label.EntryDumpToString() ref_name = ref_label.GetLabelName() indent = "\t" * self.indent self.output += f"{self.uid}{indent}[{c_entry}] {c_name}" self.output += f" => [{ref_entry}] {ref_name}\n" self.uid += 1 if self.shape_tool.IsAssembly(ref_label): self.indent += 1 ref_comps = TDF_LabelSequence() # Components of Assy subchilds = False _ = self.shape_tool.GetComponents(ref_label, ref_comps, subchilds) if ref_comps.Length(): self.find_components(ref_comps) self.indent -= 1
def addComponent(self, shape, name, color): """Add new shape to top assembly of self.doc & return uid""" labels = TDF_LabelSequence() shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(self.doc.Main()) shape_tool.GetShapes(labels) try: rootLabel = labels.Value(1) # First label at root except RuntimeError as e: print(e) return newLabel = shape_tool.AddComponent(rootLabel, shape, True) # Get referrred label and apply color to it refLabel = TDF_Label() # label of referred shape isRef = shape_tool.GetReferredShape(newLabel, refLabel) if isRef: color_tool.SetColor(refLabel, color, XCAFDoc_ColorGen) self.setLabelName(newLabel, name) logger.info('Part %s added to root label', name) shape_tool.UpdateAssemblies() self.doc = self.doc_linter() # This gets color to work self.parse_doc() entry = newLabel.EntryDumpToString() uid = entry + '.0' # this should work OK since it is new return uid
def replaceShape(self, uid, modshape): """Replace referred shape with modshape of component with uid The modified part is a located instance of a referred shape stored at doc root. The user doesn't have access to this root shape. In order to modify this referred shape, the modified instance shape is moved back to the original location at doc root, then saved.""" shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(self.doc.Main()) # shape is stored at label entry '0:1:1:n' n = int(self.label_dict[uid]['ref_entry'].split(':')[-1]) color = self.part_dict[uid]['color'] labels = TDF_LabelSequence() shape_tool.GetShapes(labels) label = labels.Value(n) # nth label at root # If shape instance was moved from its root location to its instance # location, 'unmove' it to relocate it back to the root location. if self.part_dict[uid]['loc']: modshape.Move(self.part_dict[uid]['loc'].Inverted()) # Replace oldshape in self.doc shape_tool.SetShape(label, modshape) color_tool.SetColor(modshape, color, XCAFDoc_ColorGen) shape_tool.UpdateAssemblies() self.parse_doc() # generate new part_dict
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 _get_shapes(): labels = TDF_LabelSequence() shape_tool.GetFreeShapes(labels) print("Number of shapes at root: ", labels.Length()) for i in range(labels.Length()): root_item = labels.Value(i + 1) print('Root item: ', root_item) _get_sub_shapes(root_item, None)
def get_shapes(self): """ Get a list containing all top-level shapes. :return: List of top-level shapes. :rtype: list(afem.exchange.xde.XdeLabel) """ labels = TDF_LabelSequence() self._tool.GetShapes(labels) return [XdeLabel(label) for label in labels]
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)
def getShapes(): labels = TDF_LabelSequence() h_shape_tool.GetObject().GetFreeShapes(labels) global cnt cnt += 1 print() print("Number of shapes at root :", labels.Length()) print() root = labels.Value(1) getSubShapes(root, None)
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)
def dump(self): """Return assembly structure in indented outline form. Format of lines: Component Name [entry] => Referred Label Name [entry] Components are shown indented w/r/t line above.""" if self.fname: self.output += f"Assembly structure of file: {self.fname}\n\n" else: self.output += "Assembly structure of doc:\n\n" self.indent = 0 # Find root label of step doc labels = TDF_LabelSequence() self.shape_tool.GetShapes(labels) nbr = labels.Length() rootlabel = labels.Value(1) # First label at root # Get information from root label name = rootlabel.GetLabelName() entry = rootlabel.EntryDumpToString() uid = self.get_uid_from_entry(entry) is_assy = self.shape_tool.IsAssembly(rootlabel) if is_assy: # If 1st label at root holds an assembly, it is the Top Assy. # Through this label, the entire assembly is accessible. # There is no need to explicitly examine other labels at root. self.output += f"{uid}\t[{entry}] {name}\t" self.indent += 2 top_comps = TDF_LabelSequence() # Components of Top Assy subchilds = False is_assy = self.shape_tool.GetComponents(rootlabel, top_comps, subchilds) self.output += f"Number of labels at root = {nbr}\n" if top_comps.Length(): self.find_components(top_comps) return self.output
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())
def change_label_name(self, uid, name): """Change the name of component with uid.""" entry, _ = uid.split('.') entry_parts = entry.split(':') if len(entry_parts) == 4: # first label at root j = 1 k = None elif len(entry_parts) == 5: # part is a component of label at root j = int(entry_parts[3]) # number of label at root k = int(entry_parts[4]) # component number shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(self.doc.Main()) labels = TDF_LabelSequence() # labels at root of self.doc shape_tool.GetShapes(labels) label = labels.Value(j) comps = TDF_LabelSequence() # Components of root_label subchilds = False is_assy = shape_tool.GetComponents(label, comps, subchilds) target_label = comps.Value(k) self.setLabelName(target_label, name) shape_tool.UpdateAssemblies() print(f"Name {name} set for part with uid = {uid}.") self.parse_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 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 load_stp_cmpnt(self): """Get OCAF document from STEP file and add (as component) to doc root. This is the way to load step files containing a single shape at root.""" prompt = 'Select STEP file to import' fnametuple = QFileDialog.getOpenFileName( None, prompt, './', "STEP files (*.stp *.STP *.step)") fname, _ = fnametuple logger.debug("Load file name: %s", fname) if not fname: print("Load step cancelled") return tmodel = TreeModel("DOC") step_shape_tool = tmodel.shape_tool step_color_tool = tmodel.color_tool 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: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(tmodel.doc) # Get root label of step data labels = TDF_LabelSequence() step_shape_tool.GetShapes(labels) for j in range(labels.Length()): label = labels.Value(j + 1) shape = step_shape_tool.GetShape(label) color = Quantity_Color() name = label.GetLabelName() step_color_tool.GetColor(shape, XCAFDoc_ColorSurf, color) isSimpleShape = step_shape_tool.IsSimpleShape(label) if isSimpleShape: _ = self.addComponent(shape, name, color)
def getSubShapes(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 getSubShapes(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: 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()) # n = c.Name(c.Red(), c.Green(), c.Blue()) # print(' color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # Display shape display.DisplayColoredShape(shape, c) for i in range(l_subss.Length()): lab = l_subss.Value(i + 1) print("\n######## simpleshape subshape label :", lab) shape = shape_tool.GetShape(lab) 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: 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()) # n = c.Name(c.Red(), c.Green(), c.Blue()) # print(' color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # Display shape display.DisplayColoredShape(shape, c)
def findComponents(self, label, comps): # Discover Components of an Assembly logger.debug("") logger.debug("Finding components of label (entry = %s)" % label.EntryDumpToString()) for j in range(comps.Length()): logger.debug("loop %i of %i" % (j + 1, comps.Length())) cLabel = comps.Value(j + 1) cShape = self.shape_tool.GetShape(cLabel) logger.debug("Label %i - type : %s" % (j + 1, type(cLabel))) logger.debug("Entry: %s" % cLabel.EntryDumpToString()) name = self.getName(cLabel) logger.debug("Part name: %s" % name) logger.debug("Is Assembly? %s" % self.shape_tool.IsAssembly(cLabel)) logger.debug("Is Component? %s" % self.shape_tool.IsComponent(cLabel)) logger.debug("Is Simple Shape? %s" % self.shape_tool.IsSimpleShape(cLabel)) logger.debug("Is Reference? %s" % self.shape_tool.IsReference(cLabel)) refLabel = TDF_Label() isRef = self.shape_tool.GetReferredShape(cLabel, refLabel) if isRef: refShape = self.shape_tool.GetShape(refLabel) refLabelEntry = refLabel.EntryDumpToString() logger.debug("Entry of referred shape: %s" % refLabelEntry) refName = self.getName(refLabel) logger.debug("Name of referred shape: %s" % refName) logger.debug("Is Assembly? %s" % self.shape_tool.IsAssembly(refLabel)) logger.debug("Is Component? %s" % self.shape_tool.IsComponent(refLabel)) logger.debug("Is Simple Shape? %s" % self.shape_tool.IsSimpleShape(refLabel)) logger.debug("Is Reference? %s" % self.shape_tool.IsReference(refLabel)) if self.shape_tool.IsSimpleShape(refLabel): tempAssyLocStack = list(self.assyLocStack) tempAssyLocStack.reverse() for loc in tempAssyLocStack: cShape.Move(loc) color = self.getColor(refShape) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': cShape }) elif self.shape_tool.IsAssembly(refLabel): name = self.getName(cLabel) # Instance name aLoc = TopLoc_Location() aLoc = self.shape_tool.GetLocation(cLabel) self.assyLocStack.append(aLoc) newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, self.assyUidStack[-1], { 'a': True, 'l': aLoc, 'c': None, 's': None }) self.assyUidStack.append(newAssyUID) rComps = TDF_LabelSequence() # Components of Assy subchilds = False isAssy = self.shape_tool.GetComponents( refLabel, rComps, subchilds) logger.debug("Assy name: %s" % name) logger.debug("Is Assembly? %s" % isAssy) logger.debug("Number of components: %s" % rComps.Length()) if rComps.Length(): self.findComponents(refLabel, rComps) self.assyUidStack.pop() self.assyLocStack.pop() return
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: step_reader.Transfer(doc) labels = TDF_LabelSequence() color_labels = TDF_LabelSequence() shape_tool.GetFreeShapes(labels) print("Number of shapes at root :%i" % labels.Length()) for i in range(labels.Length()): 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) print("Number of subshapes in the assemly :%i" % sub_shapes_labels.Length()) l_colors.GetColors(color_labels) print("Number of colors=%i" % color_labels.Length())
def _get_sub_shapes(lab, loc): 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): label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) locs.append(loc) _get_sub_shapes(label_reference, loc) locs.pop() elif shape_tool.IsSimpleShape(lab): shape = shape_tool.GetShape(lab) loc = TopLoc_Location() for l in locs: loc = loc.Multiplied(l) 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) 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 parse_doc(self): """Generate new part_dict & label_dict. part_dict (dict of dicts) is used primarily for 3D display part_dict = {uid: {'shape': , 'name': , 'color': , 'loc': }} label_dict (dict of dicts) is used primarily for tree view display label_dict = {uid: {'entry': , 'name': , 'parent_uid': , 'ref_entry': , 'is_assy': }} """ # Initialize dictionaries & list self._share_dict = {'0:1:1': 0} # {entry: ser_nbr} self.part_dict = {} self.label_dict = {} # Temporary use during unpacking self.parent_uid_stack = [] # uid of parent (topmost first) self.assy_entry_stack = ['0:1:1'] # [entries of containing assemblies] self.assy_loc_stack = [] # applicable <TopLoc_Location> locations shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(self.doc.Main()) # Find root label of self.doc labels = TDF_LabelSequence() shape_tool.GetShapes(labels) root_label = labels.Value(1) # First label at root nbr = labels.Length() # number of labels at root logger.debug('Number of labels at doc root : %i', nbr) # Get root label information # The first label at root holds an assembly, it is the Top Assy. # Through this label, the entire assembly is accessible. # There is no need to explicitly examine other labels at root. root_name = root_label.GetLabelName() root_entry = root_label.EntryDumpToString() root_uid = self.get_uid_from_entry(root_entry) loc = shape_tool.GetLocation(root_label) # <TopLoc_Location> self.assy_loc_stack.append(loc) self.assy_entry_stack.append(root_entry) self.label_dict = { root_uid: { 'entry': root_entry, 'name': root_name, 'parent_uid': None, 'ref_entry': None, 'is_assy': True } } self.parent_uid_stack.append(root_uid) top_comps = TDF_LabelSequence() # Components of Top Assy subchilds = False is_assy = shape_tool.GetComponents(root_label, top_comps, subchilds) if top_comps.Length(): # if is_assy: logger.debug("") logger.debug("Parsing components of label entry %s)", root_entry) self.parse_components(top_comps, shape_tool, color_tool) else: print("Something is wrong.")
def test_NCollection_Sequence(self) -> None: """ Check that python proxy for NCollection_Sequence is ok """ l = TDF_LabelSequence() self.assertEqual(l.Size(), 0) self.assertEqual(len(l), 0)
def findComponents(self, label, comps): """Discover components from comps (LabelSequence) of an assembly (label). Components of an assembly are, by definition, references which refer to either a shape or another assembly. Components are essentially 'instances' of the referred shape or assembly, and carry a location vector specifing the location of the referred shape or assembly. """ logger.debug("") logger.debug("Finding components of label entry %s)", label.EntryDumpToString()) for j in range(comps.Length()): logger.debug("loop %i of %i", j+1, comps.Length()) cLabel = comps.Value(j+1) # component label <class 'OCC.Core.TDF.TDF_Label'> cShape = self.shape_tool.GetShape(cLabel) logger.debug("Component number %i", j+1) logger.debug("Component entry: %s", cLabel.EntryDumpToString()) name = self.getName(cLabel) logger.debug("Component name: %s", name) refLabel = TDF_Label() # label of referred shape (or assembly) isRef = self.shape_tool.GetReferredShape(cLabel, refLabel) if isRef: # I think all components are references, but just in case... refShape = self.shape_tool.GetShape(refLabel) refLabelEntry = refLabel.EntryDumpToString() logger.debug("Entry referred to: %s", refLabelEntry) refName = self.getName(refLabel) logger.debug("Name of referred item: %s", refName) if self.shape_tool.IsSimpleShape(refLabel): logger.debug("Referred item is a Shape") logger.debug("Name of Shape: %s", refName) tempAssyLocStack = list(self.assyLocStack) tempAssyLocStack.reverse() for loc in tempAssyLocStack: cShape.Move(loc) color = self.getColor(refShape) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': cShape}) elif self.shape_tool.IsAssembly(refLabel): logger.debug("Referred item is an Assembly") logger.debug("Name of Assembly: %s", refName) name = self.getName(cLabel) # Instance name aLoc = TopLoc_Location() # Location vector is carried by component aLoc = self.shape_tool.GetLocation(cLabel) self.assyLocStack.append(aLoc) newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, self.assyUidStack[-1], {'a': True, 'l': aLoc, 'c': None, 's': None}) self.assyUidStack.append(newAssyUID) rComps = TDF_LabelSequence() # Components of Assy subchilds = False isAssy = self.shape_tool.GetComponents(refLabel, rComps, subchilds) logger.debug("Assy name: %s", name) logger.debug("Is Assembly? %s", isAssy) logger.debug("Number of components: %s", rComps.Length()) if rComps.Length(): self.findComponents(refLabel, rComps) self.assyUidStack.pop() self.assyLocStack.pop()
def read_file(self): """Build tree = treelib.Tree() to facilitate displaying the CAD model and constructing the tree view showing the assembly/component relationships. Each node of self.tree contains the following: (Name, UID, ParentUID, {Data}) where the Data keys are: 'a' (isAssy?), 'l' (TopLoc_Location), 'c' (Quantity_Color), 's' (TopoDS_Shape) """ logger.info("Reading STEP file") tmodel = TreeModel("STEP") self.shape_tool = tmodel.shape_tool self.color_tool = tmodel.color_tool step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(self.filename) if status == IFSelect_RetDone: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(tmodel.doc) labels = TDF_LabelSequence() self.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 = self.getName(rootlabel) logger.info('Name of root label: %s', name) isAssy = self.shape_tool.IsAssembly(rootlabel) logger.info("First label at root holds an assembly? %s", isAssy) if isAssy: # If first label at root holds an assembly, it is the Top Assembly. # Through this label, the entire assembly is accessible. # there is no need to examine other labels at root explicitly. topLoc = TopLoc_Location() topLoc = self.shape_tool.GetLocation(rootlabel) self.assyLocStack.append(topLoc) entry = rootlabel.EntryDumpToString() logger.debug("Entry: %s", entry) logger.debug("Top assy name: %s", name) # Create root node for top assy newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, None, {'a': True, 'l': None, 'c': None, 's': None}) self.assyUidStack.append(newAssyUID) topComps = TDF_LabelSequence() # Components of Top Assy subchilds = False isAssy = self.shape_tool.GetComponents(rootlabel, topComps, subchilds) logger.debug("Is Assembly? %s", isAssy) logger.debug("Number of components: %s", topComps.Length()) logger.debug("Is Reference? %s", self.shape_tool.IsReference(rootlabel)) if topComps.Length(): self.findComponents(rootlabel, topComps) else: # Labels at root can hold solids or compounds (which are 'crude' assemblies) # Either way, we will need to create a root node in self.tree newAssyUID = self.getNewUID() self.tree.create_node(os.path.basename(self.filename), newAssyUID, None, {'a': True, 'l': None, 'c': None, 's': None}) self.assyUidStack = [newAssyUID] for j in range(labels.Length()): label = labels.Value(j+1) name = self.getName(label) isAssy = self.shape_tool.IsAssembly(label) logger.debug("Label %i is assembly?: %s", j+1, isAssy) shape = self.shape_tool.GetShape(label) color = self.getColor(shape) isSimpleShape = self.shape_tool.IsSimpleShape(label) logger.debug("Is Simple Shape? %s", isSimpleShape) shapeType = shape.ShapeType() logger.debug("The shape type is: %i", shapeType) if shapeType == 0: logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_COMPOUND") topo = TopologyExplorer(shape) #topo = aocutils.topology.Topo(shape) logger.debug("Nb of compounds : %i", topo.number_of_compounds()) logger.debug("Nb of solids : %i", topo.number_of_solids()) logger.debug("Nb of shells : %i", topo.number_of_shells()) newAssyUID = self.getNewUID() for i, solid in enumerate(topo.solids()): name = "P%s" % str(i+1) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': solid}) elif shapeType == 2: logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_SOLID") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': shape}) elif shapeType == 3: logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_SHELL") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': shape}) return tmodel.doc # <class 'OCC.Core.TDocStd.TDocStd_Document'>
def parse_components(self, comps, shape_tool, color_tool): """Parse components from comps (LabelSequence). Components of an assembly are, by definition, references which refer to either a simple shape or a compound shape (an assembly). Components are essentially 'instances' of the referred shape or assembly and carry a location vector specifing the location of the referred shape or assembly.""" for j in range(comps.Length()): logger.debug("Assy_entry_stack: %s", self.assy_entry_stack) logger.debug("loop %i of %i", j + 1, comps.Length()) c_label = comps.Value(j + 1) # component label <class 'TDF_Label'> c_name = c_label.GetLabelName() c_entry = c_label.EntryDumpToString() c_uid = self.get_uid_from_entry(c_entry) c_shape = shape_tool.GetShape(c_label) logger.debug("Component number %i", j + 1) logger.debug("Component name: %s", c_name) logger.debug("Component entry: %s", c_entry) ref_label = TDF_Label() # label of referred shape (or assembly) is_ref = shape_tool.GetReferredShape(c_label, ref_label) if is_ref: # I think all components are references ref_name = ref_label.GetLabelName() ref_shape = shape_tool.GetShape(ref_label) ref_entry = ref_label.EntryDumpToString() self.label_dict[c_uid] = { 'entry': c_entry, 'name': c_name, 'parent_uid': self.parent_uid_stack[-1], 'ref_entry': ref_entry } if shape_tool.IsSimpleShape(ref_label): self.label_dict[c_uid].update({'is_assy': False}) temp_assy_loc_stack = list(self.assy_loc_stack) # Multiply locations in stack sequentially to a result if len(temp_assy_loc_stack) > 1: res_loc = temp_assy_loc_stack.pop(0) for loc in temp_assy_loc_stack: res_loc = res_loc.Multiplied(loc) c_shape.Move(res_loc) elif len(temp_assy_loc_stack) == 1: res_loc = temp_assy_loc_stack.pop() c_shape.Move(res_loc) else: res_loc = None # It is possible for this component to both specify a # location 'c_loc' and refer directly to a top level shape. # If this component *does* specify a location 'c_loc', # it will be applied to the referred shape without being # included in temp_assy_loc_stack. But in order to keep # track of the total location from the root shape to the # instance, it needs to be accounted for (by mutiplying # res_loc by it) before saving it to part_dict. c_loc = None c_loc = shape_tool.GetLocation(c_label) if c_loc: loc = res_loc.Multiplied(c_loc) color = Quantity_Color() color_tool.GetColor(ref_shape, XCAFDoc_ColorSurf, color) self.part_dict[c_uid] = { 'shape': c_shape, 'color': color, 'name': c_name, 'loc': loc } elif shape_tool.IsAssembly(ref_label): self.label_dict[c_uid].update({'is_assy': True}) logger.debug("Referred item is an Assembly") # Location vector is carried by component aLoc = TopLoc_Location() aLoc = shape_tool.GetLocation(c_label) self.assy_loc_stack.append(aLoc) self.assy_entry_stack.append(ref_entry) self.parent_uid_stack.append(c_uid) r_comps = TDF_LabelSequence() # Components of Assy subchilds = False isAssy = shape_tool.GetComponents(ref_label, r_comps, subchilds) logger.debug("Assy name: %s", ref_name) logger.debug("Is Assembly? %s", isAssy) logger.debug("Number of components: %s", r_comps.Length()) if r_comps.Length(): logger.debug("") logger.debug("Parsing components of label entry %s)", ref_entry) self.parse_components(r_comps, shape_tool, color_tool) else: print( f"I was wrong: All components are *not* references {c_uid}" ) self.assy_entry_stack.pop() self.assy_loc_stack.pop() self.parent_uid_stack.pop()
def load_stp_undr_top(self): """Paste step root label under 1st label at self.doc root Add a simple component to the first label at self.doc root. Set the component name to be the name of the step file. Then assign the label of the referred shape to 'targetLabel'. Finally, copy step root label onto 'targetLabel'. This works when copying file 'as1-oc-214.stp' to 0:1:1:2 (n=2) but does not get part color at higher values of n. Also doesn't work with file 'as1_pe_203.stp' loaded at any value of n. ??? """ prompt = 'Select STEP file to import' fnametuple = QFileDialog.getOpenFileName( None, prompt, './', "STEP files (*.stp *.STP *.step)") fname, _ = fnametuple # fname = /path/to/some/filename.ext base = os.path.basename(fname) # filename.ext filename, ext = os.path.splitext(base) logger.debug("Load file name: %s", fname) if not fname: print("Load step cancelled") return # Get the step data tmodel = TreeModel("STEP") step_shape_tool = tmodel.shape_tool step_color_tool = tmodel.color_tool 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: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(tmodel.doc) # Delint tmodel.doc & make new tools step_doc = self.doc_linter(tmodel.doc) step_shape_tool = XCAFDoc_DocumentTool_ShapeTool(step_doc.Main()) step_color_tool = XCAFDoc_DocumentTool_ColorTool(step_doc.Main()) # Get root label of step data step_labels = TDF_LabelSequence() step_shape_tool.GetShapes(step_labels) steprootLabel = step_labels.Value(1) # Make a simple box and add it as a component myBody = BRepPrimAPI_MakeBox(4, 4, 4).Shape() _ = self.addComponent(myBody, filename, Quantity_ColorRGBA()) step_shape_tool.UpdateAssemblies() # Get target label of self.doc labels = TDF_LabelSequence() # labels at root shape_tool = XCAFDoc_DocumentTool_ShapeTool(self.doc.Main()) color_tool = XCAFDoc_DocumentTool_ColorTool(self.doc.Main()) shape_tool.GetShapes(labels) n = labels.Length() # number of labels at root print(n) targetLabel = labels.Value(n) # of ref shape of comp just added # Copy source label to target label self.copy_label(steprootLabel, targetLabel) shape_tool.UpdateAssemblies() # Repair self.doc by cycling through save/load self.doc = self.doc_linter() # Build new self.part_dict & tree view self.parse_doc()
def read_file(self): """Build self.tree (treelib.Tree()) containing CAD data read from a step file. Each node of self.tree contains the following: (Name, UID, ParentUID, {Data}) where the Data keys are: 'a' (isAssy?), 'l' (TopLoc_Location), 'c' (Quantity_Color), 's' (TopoDS_Shape) """ logger.info("Reading STEP file") doc = TDocStd_Document(TCollection_ExtendedString("STEP")) # Create the application app = XCAFApp_Application_GetApplication() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), doc) # Get root shapes shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) shape_tool.SetAutoNaming(True) self.color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) layer_tool = 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(self.filename) if status == IFSelect_RetDone: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(doc) # Test round trip by writing doc back to another file. logger.info("Doing a 'short-circuit' Round Trip test") doctype = type(doc) # <class 'OCC.Core.TDocStd.TDocStd_Document'> logger.info(f"Writing {doctype} back to another STEP file") self.testRTStep(doc) # Save doc to file (for educational purposes) (not working yet) logger.debug("Saving doc to file") savefilename = TCollection_ExtendedString('../doc.txt') app.SaveAs(doc, savefilename) labels = TDF_LabelSequence() color_labels = TDF_LabelSequence() shape_tool.GetShapes(labels) self.shape_tool = shape_tool logger.info('Number of labels at root : %i' % labels.Length()) try: label = labels.Value(1) # First label at root except RuntimeError: return name = self.getName(label) logger.info('Name of root label: %s' % name) isAssy = shape_tool.IsAssembly(label) logger.info("First label at root holds an assembly? %s" % isAssy) if isAssy: # If first label at root holds an assembly, it is the Top Assembly. # Through this label, the entire assembly is accessible. # No need to examine other labels at root explicitly. topLoc = TopLoc_Location() topLoc = shape_tool.GetLocation(label) self.assyLocStack.append(topLoc) entry = label.EntryDumpToString() logger.debug("Entry: %s" % entry) logger.debug("Top assy name: %s" % name) # Create root node for top assy newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, None, { 'a': True, 'l': None, 'c': None, 's': None }) self.assyUidStack.append(newAssyUID) topComps = TDF_LabelSequence() # Components of Top Assy subchilds = False isAssy = shape_tool.GetComponents(label, topComps, subchilds) logger.debug("Is Assembly? %s" % isAssy) logger.debug("Number of components: %s" % topComps.Length()) logger.debug("Is Reference? %s" % shape_tool.IsReference(label)) if topComps.Length(): self.findComponents(label, topComps) else: # Labels at root can hold solids or compounds (which are 'crude' assemblies) # Either way, we will need to create a root node in self.tree newAssyUID = self.getNewUID() self.tree.create_node(os.path.basename(self.filename), newAssyUID, None, { 'a': True, 'l': None, 'c': None, 's': None }) self.assyUidStack = [newAssyUID] for j in range(labels.Length()): label = labels.Value(j + 1) name = self.getName(label) isAssy = shape_tool.IsAssembly(label) logger.debug("Label %i is assembly?: %s" % (j + 1, isAssy)) shape = shape_tool.GetShape(label) color = self.getColor(shape) isSimpleShape = self.shape_tool.IsSimpleShape(label) logger.debug("Is Simple Shape? %s" % isSimpleShape) shapeType = shape.ShapeType() logger.debug("The shape type is: %i" % shapeType) if shapeType == 0: logger.debug( "The shape type is OCC.Core.TopAbs.TopAbs_COMPOUND") topo = TopologyExplorer(shape) #topo = aocutils.topology.Topo(shape) logger.debug("Nb of compounds : %i" % topo.number_of_compounds()) logger.debug("Nb of solids : %i" % topo.number_of_solids()) logger.debug("Nb of shells : %i" % topo.number_of_shells()) newAssyUID = self.getNewUID() for i, solid in enumerate(topo.solids()): name = "P%s" % str(i + 1) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': solid }) elif shapeType == 2: logger.debug( "The shape type is OCC.Core.TopAbs.TopAbs_SOLID") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': shape }) elif shapeType == 3: logger.debug( "The shape type is OCC.Core.TopAbs.TopAbs_SHELL") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': shape }) return True
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 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