示例#1
0
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
示例#2
0
# 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)
if status == IFSelect_RetDone:
    step_reader.Transfer(doc.GetHandle())

shape_tool = h_shape_tool.GetObject()
shape_tool.SetAutoNaming(True)

color_tool = h_color_tool.GetObject()

lvl = 0
示例#3
0
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
示例#4
0
    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
示例#5
0
    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()
示例#6
0
    def OCC_read_file(self, filename):
        #######################################################################
        ## HR 14/7/20
        ## All python-occ intialisation for 3D view
        ## Adapted from src/Extend/DataExchange.py script from python-occ, here:
        ## https://github.com/tpaviot/pythonocc-core

        # Changed to odict to allow direct mapping to step_dict (see later)
        output_shapes = odict()

        # 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)
            print('Transfer done')

        locs = []

        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 _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)

        # HR 15/7/20
        #
        # Want to link existing node IDs from create_tree() with OCC
        # First try: assume file-read order is same for both...
        # ...and also OCC only gets "simple parts", i.e. leaves...
        # ...which is corrected for below
        #
        # MUST CORRECT IN FUTURE TO BE SINGLE FILE-READ METHOD...
        # ...FOR BOTH GRAPH AND OCC/SHAPE DATA

        _get_shapes()
        self.shapes = output_shapes
        # return self.output_shapes
        # Get all TopoDS_Solid objects in OCC dict
        OCC_list = [
            k for k in self.shapes.keys() if type(k) in self.topo_types
        ]
        # Get all leaves in step_dict (could also just get list from leaves method)
        tree_list = [k for k in self.step_dict.keys() if k in self.leaves]

        # Map master IDs to OCC objects
        self.OCC_dict = dict(zip(tree_list, OCC_list))
示例#7
0
    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