Пример #1
0
    def derivedExecute(self,obj):
        self.assureProperties(obj)
        
        # cache stuff
        objectShape = screen(obj.Object).Shape
        placements = lattice2BaseFeature.getPlacementsList(screen(obj.PlacementsTo), obj)

        outputIsLattice = lattice2BaseFeature.isObjectLattice(screen(obj.Object))

        # Pre-collect base placement list, if base is a lattice. For speed.
        if outputIsLattice:
            objectPlms = lattice2BaseFeature.getPlacementsList(screen(obj.Object),obj)
        
        placements = DereferenceArray(obj, placements, screen(obj.PlacementsFrom), obj.Referencing)
        
        # initialize output containers and loop variables
        outputShapes = [] #output list of shapes
        outputPlms = [] #list of placements
        copy_method_index = ShapeCopy.getCopyTypeIndex(obj.Copying)

        
        # the essence
        for plm in placements:

            if outputIsLattice:
                for objectPlm in objectPlms:
                    outputPlms.append(plm.multiply(objectPlm))
            else:
                outputShape = ShapeCopy.copyShape(objectShape, copy_method_index, plm)
                #outputShape.Placement = plm.multiply(outputShape.Placement) # now handled by copyShape
                outputShapes.append(outputShape)
            
        if outputIsLattice:
            return outputPlms
        else:
            # Output shape or compound (complex logic involving OutputCompounding property)
            #first, autosettle the OutputCompounding.
            if obj.OutputCompounding == "(autosettle)":
                if hasattr(screen(obj.PlacementsTo),"ExposePlacement") and screen(obj.PlacementsTo).ExposePlacement == False:
                    obj.OutputCompounding = "always"
                else:
                    obj.OutputCompounding = "only if many"
            #now, set the result shape
            if len(outputShapes) == 1 and obj.OutputCompounding == "only if many":
                sh = outputShapes[0]
                sh = ShapeCopy.transformCopy(sh)
                obj.Shape = sh
            else:
                obj.Shape = Part.makeCompound(outputShapes)
            return None
Пример #2
0
    def derivedExecute(self,obj):
        self.assureProperties(obj)
        
        # cache stuff
        objectShape = obj.Object.Shape
        placements = lattice2BaseFeature.getPlacementsList(obj.PlacementsTo, obj)

        outputIsLattice = lattice2BaseFeature.isObjectLattice(obj.Object)

        # Pre-collect base placement list, if base is a lattice. For speed.
        if outputIsLattice:
            objectPlms = lattice2BaseFeature.getPlacementsList(obj.Object,obj)
        
        placements = DereferenceArray(obj, placements, obj.PlacementsFrom, obj.Referencing)
        
        # initialize output containers and loop variables
        outputShapes = [] #output list of shapes
        outputPlms = [] #list of placements
        copy_method_index = ShapeCopy.getCopyTypeIndex(obj.Copying)

        
        # the essence
        for plm in placements:

            if outputIsLattice:
                for objectPlm in objectPlms:
                    outputPlms.append(plm.multiply(objectPlm))
            else:
                outputShape = ShapeCopy.copyShape(objectShape, copy_method_index, plm)
                #outputShape.Placement = plm.multiply(outputShape.Placement) # now handled by copyShape
                outputShapes.append(outputShape)
            
        if outputIsLattice:
            return outputPlms
        else:
            # Output shape or compound (complex logic involving OutputCompounding property)
            #first, autosettle the OutputCompounding.
            if obj.OutputCompounding == "(autosettle)":
                if hasattr(obj.PlacementsTo,"ExposePlacement") and obj.PlacementsTo.ExposePlacement == False:
                    obj.OutputCompounding = "always"
                else:
                    obj.OutputCompounding = "only if many"
            #now, set the result shape
            if len(outputShapes) == 1 and obj.OutputCompounding == "only if many":
                sh = outputShapes[0]
                sh = ShapeCopy.transformCopy(sh)
                obj.Shape = sh
            else:
                obj.Shape = Part.makeCompound(outputShapes)
            return None
Пример #3
0
def DereferenceArray(obj,placements, lnkFrom, refmode):
    '''common implementation of treatment Referencing property. Returns a list of placements to use directly.
    obj - feature being executed (used for error reporting; can be None)
    placements - the array, converted into a list of placements.
    lnkFrom - object linked as a lattice of 'from' placements. Can be None, if mode is not 'Use PlacemenetsFrom'
    refmode - a string - enum property item'''
        
    plmDeref = App.Placement() #inverse placement of reference (reference is a substitute of origin)
    if lnkFrom is not None  and  refmode != "Use PlacementsFrom":
        lattice2Executer.warning(obj,"Referencing mode is '"+refmode+"', doesn't need PlacementsFrom link to be set. The link is set, but it will be ignored.")
    if refmode == "Origin":
        return placements
    elif refmode == "First item":
        plmDeref = placements[0].inverse()
    elif refmode == "Last item":
        plmDeref = placements[0].inverse()
    elif refmode == "Use PlacementsFrom":
        if lnkFrom is None:
            raise ValueError("Referencing mode is 'Move from to', but PlacementsFrom link is not set.")
        placementsFrom = lattice2BaseFeature.getPlacementsList(lnkFrom, obj)
        if len(placementsFrom) == 1:
            plmDeref = placementsFrom[0].inverse()
        elif len(placementsFrom) == len(placements):
            return [lattice2BaseFeature.makeMoveFromTo(placementsFrom[i], placements[i]) for i in range(0, len(placements))]
        else:
            lattice2Executer.warning(obj,"Lengths of arrays linked as PlacementsTo and PlacementsFrom must equal, or PlacementsFrom can be one placement. Violation: lengths are "+str(len(placements))+ " and "+str(len(placementsFrom)))
    else:
        raise ValueError("Referencing mode not implemented: "+refmode)
    
    return [plm.multiply(plmDeref) for plm in placements]
Пример #4
0
    def execute(self, obj):

        if self.clone(obj):
            return
        if not obj.LatticePlacement:
            return

        if lattice2BF.isObjectLattice(obj.LatticePlacement) is True:
            pls = lattice2BF.getPlacementsList(obj.LatticePlacement)
            obj.RebarPlacements = pls
            self.build_shape(obj)
            obj.Amount = len(obj.RebarPlacements)
            obj.TotalLength = obj.Amount * obj.BaseRebar.Length

            # set Visibility of BaseRebar
            # this should be done in the Gui Command,
            # but this dos not yet exist TODO
            # set view of base rebar to off
            # if reinforcement shape is not a null shape
            # TODO may be use another color for base rebar
            if FreeCAD.GuiUp:
                if obj.Shape.isNull() is not True:
                    obj.BaseRebar.ViewObject.Visibility = False
        else:
            FreeCAD.Console.PrintError(
                "The object provided: {} is not a Lattice2 object\n".format(
                    obj.Name))
Пример #5
0
def DereferenceArray(obj,placements, lnkFrom, refmode):
    '''common implementation of treatment Referencing property. Returns a list of placements to use directly.
    obj - feature being executed (used for error reporting; can be None)
    placements - the array, converted into a list of placements.
    lnkFrom - object linked as a lattice of 'from' placements. Can be None, if mode is not 'Use PlacemenetsFrom'
    refmode - a string - enum property item'''
        
    plmDeref = App.Placement() #inverse placement of reference (reference is a substitute of origin)
    if lnkFrom is not None  and  refmode != "Use PlacementsFrom":
        lattice2Executer.warning(obj,"Referencing mode is '"+refmode+"', doesn't need PlacementsFrom link to be set. The link is set, but it will be ignored.")
    if refmode == "Origin":
        return placements
    elif refmode == "First item":
        plmDeref = placements[0].inverse()
    elif refmode == "Last item":
        plmDeref = placements[0].inverse()
    elif refmode == "Use PlacementsFrom":
        if lnkFrom is None:
            raise ValueError("Referencing mode is 'Move from to', but PlacementsFrom link is not set.")
        placementsFrom = lattice2BaseFeature.getPlacementsList(lnkFrom, obj)
        if len(placementsFrom) == 1:
            plmDeref = placementsFrom[0].inverse()
        elif len(placementsFrom) == len(placements):
            return [lattice2BaseFeature.makeMoveFromTo(placementsFrom[i], placements[i]) for i in range(0, len(placements))]
        else:
            lattice2Executer.warning(obj,"Lengths of arrays linked as PlacementsTo and PlacementsFrom must equal, or PlacementsFrom can be one placement. Violation: lengths are "+str(len(placements))+ " and "+str(len(placementsFrom)))
    else:
        raise ValueError("Referencing mode not implemented: "+refmode)
    
    return [plm.multiply(plmDeref) for plm in placements]
Пример #6
0
    def derivedExecute(self, host):
        self.assureGenerator(host)

        self.generator.execute()
        values = [float(strv) for strv in host.Values]

        input = lattice2BaseFeature.getPlacementsList(host.Placement1Ref)
        if host.Placement2Ref is not None:
            input.extend(
                lattice2BaseFeature.getPlacementsList(host.Placement2Ref))

        if len(input) != 2:
            raise ValueError("Need exactly 2 placements. {n} provided.".format(
                n=len(input)))

        plm1, plm2 = input

        # construct interpolation functions
        #  prepare lists of input samples

        def plmByVal(val):
            return plm1.sclerp(plm2, val, host.Shorten)

        output = [plmByVal(val) for val in values]

        ## update reference placement
        #ref = host.ReferencePlacementOption
        #if ref == 'external':
        #    pass
        #elif ref == 'origin':
        #    self.setReferencePlm(host, None)
        #elif ref == 'inherit':
        #    self.setReferencePlm(host, lattice2BaseFeature.getReferencePlm(host.Base))
        #elif ref == 'SpanStart':
        #    self.setReferencePlm(host, plmByVal(float(host.SpanStart)))
        #elif ref == 'SpanEnd':
        #    self.setReferencePlm(host, plmByVal(float(host.SpanEnd)))
        #elif ref == 'at custom value':
        #    self.setReferencePlm(host, plmByVal(float(host.ReferenceValue)))
        #elif ref == 'first placement':
        #    self.setReferencePlm(host, output[0])
        #elif ref == 'last placement':
        #    self.setReferencePlm(host, output[-1])
        #else:
        #    raise NotImplementedError("Reference option not implemented: " + ref)
        #
        return output
Пример #7
0
    def applyTransformed(self, selfobj, baseshape, transforms, mts):
        featurelist = []
        has_bodies = False
        has_features = False
        for lnk in selfobj.FeaturesToCopy:
            if lnk.isDerivedFrom('PartDesign::Body'):
                featurelist.extend(
                    getBodySequence(lnk, skipfirst=selfobj.SkipFirstInBody))
                has_bodies = True
            else:
                featurelist.append(lnk)
                has_features = True

        #check cross-links
        if selfobj.Referencing == 'Use PlacementsFrom':
            body_ref = bodyOf(selfobj.PlacementsFrom)
        else:
            body_ref = bodyOf(selfobj)
            for feature in featurelist:
                if bodyOf(feature) is not body_ref:
                    raise ScopeError(
                        'Reference placement and the feature are not in the same body (use Shapebinder or Ghost to bring the placement in).'
                    )

        placements = lattice2BaseFeature.getPlacementsList(
            selfobj.PlacementsTo, selfobj)
        placements = DereferenceArray(selfobj, placements,
                                      selfobj.PlacementsFrom,
                                      selfobj.Referencing)
        if selfobj.Referencing == 'First item' and transforms is None:
            placements.pop(
                0)  #to not repeat the feature where it was applied already
        elif selfobj.Referencing == 'Last item' and transforms is None:
            placements.pop(
            )  #to not repeat the feature where it was applied already
        if not transforms is None:
            newplacements = []
            for transform in transforms:
                newplacements += [
                    transform.multiply(plm) for plm in placements
                ]
            placements = newplacements
        for feature in featurelist:
            try:
                baseshape = applyFeature(baseshape, feature, placements, mts)
            except FeatureUnsupportedError as err:
                if not selfobj.IgnoreUnsupported:
                    raise
                else:
                    App.Console.PrintLog(
                        '{name} is unsupported, skipped.\n'.format(
                            name=feature.Name))
        return baseshape
Пример #8
0
 def derivedExecute(self,obj):
     old_pos = App.Vector()
     try:
         old_pos = lattice2BaseFeature.getPlacementsList(obj, suppressWarning= True)[0].Base
     except Exception:
         pass #retrieving position may fail if the object is recomputed for the very first time
     
     ori = App.Rotation(obj.Yaw, obj.Pitch, obj.Roll)
     
     plm =  App.Placement(old_pos, ori)
     
     return [plm]
Пример #9
0
def ExplodeArray(feature):
    plms = lattice2BaseFeature.getPlacementsList(feature)
    features_created = []
    for i in range(len(plms)):
        af = makeArrayFilter(name='Placment')
        af.Label = u'Placement' + str(i)
        af.Base = feature
        af.FilterType = 'specific items'
        af.items = str(i)
        af.ExposePlacement = True
        af.ViewObject.DontUnhideOnDelete = True
        features_created.append(af)
    return features_created
Пример #10
0
def ExplodeArray(feature):
    plms = lattice2BaseFeature.getPlacementsList(feature)
    features_created = []
    for i in range(len(plms)):
        af = makeArrayFilter(name = 'Placment')
        af.Label = u'Placement' + unicode(i)
        af.Base = feature
        af.FilterType = 'specific items'
        af.items = str(i)
        af.ExposePlacement = True
        af.ViewObject.DontUnhideOnDelete = True
        features_created.append(af)
    return features_created
Пример #11
0
    def derivedExecute(self, obj):
        old_pos = App.Vector()
        try:
            old_pos = lattice2BaseFeature.getPlacementsList(
                obj, suppressWarning=True)[0].Base
        except Exception:
            pass  #retrieving position may fail if the object is recomputed for the very first time

        ori = App.Rotation(obj.Yaw, obj.Pitch, obj.Roll)

        plm = App.Placement(old_pos, ori)

        return [plm]
Пример #12
0
 def derivedExecute(self,obj):
     old_pos = App.Vector()
     try:
         old_pos = lattice2BaseFeature.getPlacementsList(obj, suppressWarning= True)[0].Base
     except Exception:
         pass #retrieving position may fail if the object is recomputed for the very first time
     
     import lattice2GeomUtils
     
     ori = lattice2GeomUtils.makeOrientationFromLocalAxesUni(obj.Priority, obj.XDir_wanted * 1.0, obj.YDir_wanted * 1.0, obj.ZDir_wanted * 1.0) # multiply vectors by 1.0 to copy them, to block mutation
     
     plm =  App.Placement(old_pos, ori)
     
     obj.XDir_actual = ori.multVec(App.Vector(1,0,0))
     obj.YDir_actual = ori.multVec(App.Vector(0,1,0))
     obj.ZDir_actual = ori.multVec(App.Vector(0,0,1))
     
     return [plm]
Пример #13
0
    def derivedExecute(self, obj):
        old_pos = App.Vector()
        try:
            old_pos = lattice2BaseFeature.getPlacementsList(
                obj, suppressWarning=True)[0].Base
        except Exception:
            pass  #retrieving position may fail if the object is recomputed for the very first time

        import lattice2GeomUtils

        ori = lattice2GeomUtils.makeOrientationFromLocalAxesUni(
            obj.Priority, obj.XDir_wanted * 1.0, obj.YDir_wanted * 1.0,
            obj.ZDir_wanted *
            1.0)  # multiply vectors by 1.0 to copy them, to block mutation

        plm = App.Placement(old_pos, ori)

        obj.XDir_actual = ori.multVec(App.Vector(1, 0, 0))
        obj.YDir_actual = ori.multVec(App.Vector(0, 1, 0))
        obj.ZDir_actual = ori.multVec(App.Vector(0, 0, 1))

        return [plm]
Пример #14
0
    def execute(self, selfobj):

        self.updatedProperties = set()
        try:
            if LBF.isObjectLattice(selfobj.Object):
                plms = LBF.getPlacementsList(selfobj.Object)
                self.assignProp(selfobj, "App::PropertyInteger", "NumberOfPlacements", len(plms))
                for i in range(min(len(plms), 10)):
                    self.assignProp(selfobj, "App::PropertyPlacement", "Placement" + str(i), plms[i])
            else:
                sh = selfobj.Object.Shape

                self.assignProp(selfobj, "App::PropertyString", "ShapeType", sh.ShapeType)

                if (
                    sh.ShapeType == "Compound"
                    or sh.ShapeType == "CompSolid"
                    or sh.ShapeType == "Shell"
                    or sh.ShapeType == "Wire"
                ):
                    self.assignProp(
                        selfobj, "App::PropertyInteger", sh.ShapeType + "NumChildren", len(sh.childShapes(False, False))
                    )
                if sh.ShapeType == "Compound":
                    max_depth = 0
                    num_leaves = 0
                    last_leaf = None
                    for (child, msg, it) in LCE.CompoundExplorer(sh):
                        if it.curDepth() > max_depth:
                            max_depth = it.curDepth()
                        if msg == LCE.CompoundExplorer.MSG_LEAF:
                            last_leaf = child
                            num_leaves += 1
                    self.assignProp(selfobj, "App::PropertyInteger", "CompoundNestingDepth", max_depth)
                    self.assignProp(selfobj, "App::PropertyInteger", "CompoundNumLeaves", num_leaves)
                    if num_leaves == 1:
                        self.assignProp(
                            selfobj, "App::PropertyString", "ShapeType", sh.ShapeType + "(" + last_leaf.ShapeType + ")"
                        )
                        sh = last_leaf

                self.transplant_all_attributes(
                    selfobj, sh, "Shape", withdraw_set=set(["ShapeType", "Content", "Module", "TypeId"])
                )

                if sh.ShapeType == "Face":
                    typelist = [
                        "BSplineSurface",
                        "BezierSurface",
                        "Cone",
                        "Cylinder",
                        "OffsetSurface",
                        "Plane",
                        "PlateSurface",
                        "RectangularTrimmedSurface",
                        "Sphere",
                        "SurfaceOfExtrusion",
                        "SurfaceOfRevolution",
                        "Toroid",
                    ]
                    surf = sh.Surface
                    for typename in typelist:
                        if type(surf) is getattr(Part, typename):
                            break
                        typename = None
                    self.assignProp(selfobj, "App::PropertyString", "FaceType", typename)

                    self.transplant_all_attributes(selfobj, surf, "Face")
                elif sh.ShapeType == "Edge":
                    typelist = [
                        "Arc",
                        "ArcOfCircle",
                        "ArcOfEllipse",
                        "ArcOfHyperbola",
                        "ArcOfParabola",
                        "BSplineCurve",
                        "BezierCurve",
                        "Circle",
                        "Ellipse",
                        "Hyperbola",
                        "Line",
                        "OffsetCurve",
                        "Parabola",
                    ]
                    crv = sh.Curve
                    for typename in typelist:
                        if type(crv) is getattr(Part, typename):
                            break
                        typename = None
                    self.assignProp(selfobj, "App::PropertyString", "EdgeType", typename)

                    self.transplant_all_attributes(selfobj, crv, "Edge")

                elif sh.ShapeType == "Vertex":
                    self.assignProp(selfobj, "App::PropertyVector", "VertexPosition", sh.Point)
        finally:
            # remove properties that haven't been updated
            for propname in selfobj.PropertiesList:
                if selfobj.getGroupOfProperty(propname) == "info":
                    if not (propname in self.updatedProperties):
                        selfobj.removeProperty(propname)
Пример #15
0
    def execute(self,obj):
        base = obj.ShapeLink.Shape
        if obj.CompoundTraversal == "Use as a whole":
            baseChildren = [base]
        else:
            if base.ShapeType != 'Compound':
                base = Part.makeCompound([base])
            if obj.CompoundTraversal == "Recursive":
                baseChildren = LCE.AllLeaves(base)
            else:
                baseChildren = base.childShapes()
        
        N = len(baseChildren)
        
        orients = []
        if obj.OrientMode == "global":
            orients = [App.Placement()]*N
        elif obj.OrientMode == "local of compound":
            orients = [obj.ShapeLink.Placement]*N
        elif obj.OrientMode == "local of child":
            orients = [child.Placement for child in baseChildren]
        elif obj.OrientMode == "use OrientLink":
            orients = LBF.getPlacementsList(obj.OrientLink, context= obj)
            if len(orients) == N:
                pass
            elif len(orients)>N:
                Executer.warning(obj, "Array of placements linked in OrientLink has more placements ("+str(len(orients))+") than bounding boxes to be constructed ("+str(len(baseChildren))+"). Extra placements will be dropped.")
            elif len(orients)==1:
                orients = [orients[0]]*N
            else:
                raise ValueError(obj.Name+": Array of placements linked in OrientLink has not enough placements ("+str(len(orients))+") than bounding boxes to be constructed ("+str(len(baseChildren))+").")
        else:
            raise ValueError(obj.Name+": OrientMode "+obj.OrientMode+" not implemented =(")
        
        # mark placements with no rotation
        for i in range(N):
            Q = orients[i].Rotation.Q
            # Quaternions for zero rotation are either (0,0,0,1) or (0,0,0,-1). For non-zero
            # rotations, some of first three values will be nonzero, and fourth value will 
            # not be equal to 1. While it's enough to compare absolute value of fourth value
            # to 1, precision is seriously lost in such comparison, so we are checking if 
            # fisrt three values are zero instead.
            if abs(Q[0])+abs(Q[1])+abs(Q[2]) < ParaConfusion:
                orients[i] = None
        
        boxes_shapes = []
        for i in range(N):
            child = baseChildren[i]
            if orients[i] is not None:
                child = child.copy()
                child.transformShape(orients[i].inverse().toMatrix())

            if obj.Precision:
                bb = getPrecisionBoundBox(child)
            else:
                bb = child.BoundBox
                
            bb = scaledBoundBox(bb, obj.ScaleFactor)
            bb.enlarge(obj.Padding)

            bb_shape = boundBox2RealBox(bb)
            if orients[i] is not None:
                bb_shape.transformShape(orients[i].toMatrix())
            boxes_shapes.append(bb_shape)
            
        #Fill in read-only properties
        if N == 1:
            obj.Size = App.Vector(bb.XLength,bb.YLength,bb.ZLength)
        
            cnt = bb.Center
            if orients[0] is not None:
                cnt = orients[0].multVec(cnt)
            obj.Center = cnt
        else:
            obj.Size = App.Vector()
            obj.Center = App.Vector()
        
        if obj.CompoundTraversal == "Use as a whole":
            assert(N==1)
            obj.Shape = boxes_shapes[0]
        else:
            obj.Shape = Part.makeCompound(boxes_shapes)
Пример #16
0
    def execute(self, obj):
        base = screen(obj.ShapeLink).Shape
        if obj.CompoundTraversal == "Use as a whole":
            baseChildren = [base]
        else:
            if base.ShapeType != 'Compound':
                base = Part.makeCompound([base])
            if obj.CompoundTraversal == "Recursive":
                baseChildren = LCE.AllLeaves(base)
            else:
                baseChildren = base.childShapes()

        N = len(baseChildren)

        orients = []
        if obj.OrientMode == "global":
            orients = [App.Placement()] * N
        elif obj.OrientMode == "local of compound":
            orients = [screen(obj.ShapeLink).Placement] * N
        elif obj.OrientMode == "local of child":
            orients = [child.Placement for child in baseChildren]
        elif obj.OrientMode == "use OrientLink":
            orients = LBF.getPlacementsList(screen(obj.OrientLink),
                                            context=obj)
            if len(orients) == N:
                pass
            elif len(orients) > N:
                Executer.warning(
                    obj,
                    "Array of placements linked in OrientLink has more placements ("
                    + str(len(orients)) +
                    ") than bounding boxes to be constructed (" +
                    str(len(baseChildren)) +
                    "). Extra placements will be dropped.")
            elif len(orients) == 1:
                orients = [orients[0]] * N
            else:
                raise ValueError(
                    obj.Name +
                    ": Array of placements linked in OrientLink has not enough placements ("
                    + str(len(orients)) +
                    ") than bounding boxes to be constructed (" +
                    str(len(baseChildren)) + ").")
        else:
            raise ValueError(obj.Name + ": OrientMode " + obj.OrientMode +
                             " not implemented =(")

        # mark placements with no rotation
        for i in range(N):
            Q = orients[i].Rotation.Q
            # Quaternions for zero rotation are either (0,0,0,1) or (0,0,0,-1). For non-zero
            # rotations, some of first three values will be nonzero, and fourth value will
            # not be equal to 1. While it's enough to compare absolute value of fourth value
            # to 1, precision is seriously lost in such comparison, so we are checking if
            # first three values are zero instead.
            if abs(Q[0]) + abs(Q[1]) + abs(Q[2]) < ParaConfusion:
                orients[i] = None

        from lattice2ShapeCopy import shallowCopy
        boxes_shapes = []
        for i in range(N):
            child = baseChildren[i]
            if orients[i] is not None:
                child = shallowCopy(child)
                child.Placement = orients[i].inverse().multiply(
                    child.Placement)

            if obj.Precision:
                bb = getPrecisionBoundBox(child)
            else:
                bb = child.BoundBox

            bb = scaledBoundBox(bb, obj.ScaleFactor)
            bb.enlarge(obj.Padding)

            bb_shape = boundBox2RealBox(bb)
            if orients[i] is not None:
                bb_shape.transformShape(orients[i].toMatrix(), True)
            boxes_shapes.append(bb_shape)

        #Fill in read-only properties
        if N == 1:
            obj.Size = App.Vector(bb.XLength, bb.YLength, bb.ZLength)

            cnt = bb.Center
            if orients[0] is not None:
                cnt = orients[0].multVec(cnt)
            obj.Center = cnt
        else:
            obj.Size = App.Vector()
            obj.Center = App.Vector()

        if obj.CompoundTraversal == "Use as a whole":
            assert (N == 1)
            obj.Shape = boxes_shapes[0]
        else:
            obj.Shape = Part.makeCompound(boxes_shapes)
Пример #17
0
    def derivedExecute(self,obj):
        
        self.initNewProperties(obj)
        
        outputIsLattice = lattice2BaseFeature.isObjectLattice(screen(obj.Object))
        
        if not lattice2BaseFeature.isObjectLattice(screen(obj.Object)):
            if obj.ObjectTraversal == "Direct children only":
                objectShapes = screen(obj.Object).Shape.childShapes()
                if screen(obj.Object).Shape.ShapeType != "Compound":
                    lattice2Executer.warning(obj,"shape supplied as object is not a compound. It is going to be downgraded one level down (e.g, if it is a wire, the edges are going to be enumerated as children).")
            elif obj.ObjectTraversal == "Recursive":
                objectShapes = LCE.AllLeaves(screen(obj.Object).Shape)
            else:
                raise ValueError("Traversal mode not implemented: "+obj.ObjectTraversal)
        else:
            objectPlms = lattice2BaseFeature.getPlacementsList(screen(obj.Object), obj)
        placements = lattice2BaseFeature.getPlacementsList(screen(obj.PlacementsTo), obj)

        
        # Precompute referencing
        placements = DereferenceArray(obj, placements, screen(obj.PlacementsFrom), obj.Referencing)
                
        # initialize output containers and loop variables
        outputShapes = [] #output list of shapes
        outputPlms = [] #list of placements
        iChild = 0
        numChildren = len(objectPlms) if outputIsLattice else len(objectShapes) 
        copy_method_index = ShapeCopy.getCopyTypeIndex(obj.Copying)
        
        # the essence
        for iPlm in range(len(placements)):
            if iChild == numChildren:
                if obj.LoopObjectSequence:
                    iChild = 0
                else:
                    break
            
            plm = placements[iPlm]
             
            if outputIsLattice:
                objectPlm = objectPlms[iChild]
                outputPlms.append(plm.multiply(objectPlm))
            else:
                outputShape = ShapeCopy.copyShape(objectShapes[iChild], copy_method_index, plm)
                # outputShape.Placement = plm.multiply(outputShape.Placement) #now done by shape copy routine
                outputShapes.append(outputShape)
            
            iChild += 1
            
        if len(placements) > numChildren and not obj.LoopObjectSequence:
            lattice2Executer.warning(obj,"There are fewer children to populate, than placements to be populated (%1, %2). Extra placements will be dropped.".replace("%1", str(numChildren)).replace("%2",str(len(placements))))
            
        if len(placements) < numChildren:
            lattice2Executer.warning(obj,"There are more children to populate, than placements to be populated (%1, %2). Extra children will be dropped.".replace("%1", str(numChildren)).replace("%2",str(len(placements))))
            
        if outputIsLattice:
            return outputPlms
        else:
            obj.Shape = Part.makeCompound(outputShapes)
            return None
Пример #18
0
    def derivedExecute(self, obj):
        base_is_lattice = LBF.isObjectLattice(obj.Object)
        pivot_is_lattice = LBF.isObjectLattice(
            obj.Pivot[0]) if obj.Pivot else True
        flipX = obj.FlipX
        flipY = obj.FlipY
        flipZ = obj.FlipZ

        # collect mirror pivot placements
        pivots = None
        em = 0  #editormode of PivotPlacement property. 0 = editable, 1 = read-only, 2 = hidden
        if obj.Pivot:
            em = 1  #read-only
            if pivot_is_lattice:
                pivots = LBF.getPlacementsList(obj.Pivot[0])
            else:
                pivot_shape = resolveSingleSublink(obj.Pivot)
                if pivot_shape.ShapeType == 'Edge' and type(
                        pivot_shape.Curve) is Part.Line:
                    dir = pivot_shape.Curve.Direction
                    base = pivot_shape.CenterOfMass
                    if flipX != flipY:
                        raise ValueError(
                            "Unsupported combination of flips for mirroring against line. FlipX and FlipY must either be both on or both off."
                        )
                    rot = makeOrientationFromLocalAxes(dir)
                    pivots = [App.Placement(base, rot)]
                elif pivot_shape.ShapeType == 'Face' and type(
                        pivot_shape.Surface) is Part.Plane:
                    dir = pivot_shape.Surface.Axis
                    base = pivot_shape.CenterOfMass
                    if flipX != flipY:
                        raise ValueError(
                            "Unsupported combination of flips for mirroring against line. FlipX and FlipY must either be both on or both off."
                        )
                    rot = makeOrientationFromLocalAxes(dir)
                    pivots = [App.Placement(base, rot)]
                elif pivot_shape.ShapeType == 'Vertex':
                    base = pivot_shape.Point
                    pivots = [App.Placement(base, obj.PivotPlacement.Rotation)]
                    em = 0  #editable
                else:
                    raise TypeError("Unsupported geometry for use as mirror")
            if len(pivots) == 1:
                obj.PivotPlacement = pivots[0]
            else:
                em = 2  #hidden
        else:
            pivots = [obj.PivotPlacement]
            em = 0
        obj.setEditorMode('PivotPlacement', em)

        # collect objects to be mirrored
        loop = False
        whole = obj.ObjectTraversal == 'Use whole'
        children = []
        if base_is_lattice:
            children = LBF.getPlacementsList(obj.Object)
        else:
            if obj.ObjectTraversal == 'Use whole':
                children = [obj.Object.Shape]
                loop = True
            elif obj.ObjectTraversal == 'Direct children only':
                children = obj.Object.Shape.childShapes()
            elif obj.ObjectTraversal == 'Use whole':
                children = LCE.AllLeaves(obj.Object.Shape)
            else:
                raise ValueError(
                    "Traversal mode not implemented: {mode}".format(
                        mode=obj.ObjectTraversal))

        if len(pivots) != len(children) and not loop and not whole:
            lattice2Executer.warning(
                obj,
                "{label}: Number of children ({nch}) doesn't match the number of pivot placements ({npiv})"
                .format(label=obj.Label, nch=len(children), npiv=len(pivots)))
            n = min(len(pivots), len(children))
        else:
            n = len(pivots)

        # actual mirroring!
        result = []
        for i in range(n):
            piv = pivots[i]
            ichild = i % len(children)
            if base_is_lattice:
                if whole:
                    for plm in children:
                        result.append(
                            mirrorPlacement(plm, piv, flipX, flipY, flipZ))
                else:
                    result.append(
                        mirrorPlacement(children[ichild], piv, flipX, flipY,
                                        flipZ))
            else:
                result.append(
                    mirrorShape(children[ichild], piv, flipX, flipY, flipZ))

        # write out the result
        if base_is_lattice:
            return result
        else:
            if n == 1:
                result = ShapeCopy.transformCopy(result[0])
            else:
                result = Part.Compound(result)
            obj.Shape = result
            return None
Пример #19
0
    def execute(self,selfobj):
        
        self.updatedProperties = set()
        try:
            if LBF.isObjectLattice(screen(selfobj.Object)):
                plms = LBF.getPlacementsList(screen(selfobj.Object))
                self.assignProp(selfobj,"App::PropertyInteger","NumberOfPlacements",len(plms))
                for i in range(    min(  len(plms), 10  )    ):
                    self.assignProp(selfobj,"App::PropertyPlacement","Placement"+str(i),plms[i])
            else:
                sh = screen(selfobj.Object).Shape
                
                self.assignProp(selfobj,"App::PropertyString","ShapeType", sh.ShapeType)
                
                if sh.ShapeType == "Compound" or sh.ShapeType == "CompSolid" or sh.ShapeType == "Shell" or sh.ShapeType == "Wire":
                    self.assignProp(selfobj,"App::PropertyInteger",sh.ShapeType+"NumChildren",len(sh.childShapes(False,False)))
                if sh.ShapeType == "Compound":
                    max_depth = 0
                    num_leaves = 0
                    last_leaf = None
                    for (child, msg, it) in LCE.CompoundExplorer(sh):
                        if it.curDepth() > max_depth:
                            max_depth = it.curDepth()
                        if msg == LCE.CompoundExplorer.MSG_LEAF:
                            last_leaf = child
                            num_leaves += 1
                    self.assignProp(selfobj,"App::PropertyInteger","CompoundNestingDepth", max_depth)
                    self.assignProp(selfobj,"App::PropertyInteger","CompoundNumLeaves", num_leaves)
                    if num_leaves == 1:
                        self.assignProp(selfobj,"App::PropertyString","ShapeType", sh.ShapeType + "(" + last_leaf.ShapeType + ")")
                        sh = last_leaf

                self.transplant_all_attributes(selfobj,sh,"Shape", withdraw_set= set(["ShapeType", "Content", "Module", "TypeId"]))
                        
                if sh.ShapeType == "Face":
                    typelist = ["BSplineSurface",
                                "BezierSurface",
                                "Cone",
                                "Cylinder",
                                "OffsetSurface",
                                "Plane",
                                "PlateSurface",
                                "RectangularTrimmedSurface",
                                "Sphere",
                                "SurfaceOfExtrusion",
                                "SurfaceOfRevolution",
                                "Toroid",
                                ]
                    surf = sh.Surface
                    for typename in typelist:
                        if type(surf) is getattr(Part, typename):
                            break
                        typename = None
                    self.assignProp(selfobj,"App::PropertyString","FaceType",typename)
                    
                    self.transplant_all_attributes(selfobj,surf,"Face")
                elif sh.ShapeType == "Edge":
                    typelist = ["Arc",
                                "ArcOfCircle",
                                "ArcOfEllipse",
                                "ArcOfHyperbola",
                                "ArcOfParabola",
                                "BSplineCurve",
                                "BezierCurve",
                                "Circle",
                                "Ellipse",
                                "Hyperbola",
                                "Line",
                                "OffsetCurve",
                                "Parabola",
                                ]
                    crv = sh.Curve
                    for typename in typelist:
                        if type(crv) is getattr(Part, typename):
                            break
                        typename = None
                    self.assignProp(selfobj,"App::PropertyString","EdgeType",typename)
                    
                    self.transplant_all_attributes(selfobj,crv,"Edge")
                        
                elif sh.ShapeType == "Vertex":
                    self.assignProp(selfobj,"App::PropertyVector","VertexPosition",sh.Point)
        finally:
            #remove properties that haven't been updated
            for propname in selfobj.PropertiesList:
                if selfobj.getGroupOfProperty(propname) == "info":
                    if not (propname in self.updatedProperties):
                        selfobj.removeProperty(propname)
Пример #20
0
    def derivedExecute(self,obj):
        
        self.initNewProperties(obj)
        
        outputIsLattice = lattice2BaseFeature.isObjectLattice(obj.Object)
        
        if not lattice2BaseFeature.isObjectLattice(obj.Object):
            if obj.ObjectTraversal == "Direct children only":
                objectShapes = obj.Object.Shape.childShapes()
                if obj.Object.Shape.ShapeType != "Compound":
                    lattice2Executer.warning(obj,"shape supplied as object is not a compound. It is going to be downgraded one level down (e.g, if it is a wire, the edges are going to be enumerated as children).")
            elif obj.ObjectTraversal == "Recursive":
                objectShapes = LCE.AllLeaves(obj.Object.Shape)
            else:
                raise ValueError("Traversal mode not implemented: "+obj.ObjectTraversal)
        else:
            objectPlms = lattice2BaseFeature.getPlacementsList(obj.Object, obj)
        placements = lattice2BaseFeature.getPlacementsList(obj.PlacementsTo, obj)

        
        # Precompute referencing
        placements = DereferenceArray(obj, placements, obj.PlacementsFrom, obj.Referencing)
                
        # initialize output containers and loop variables
        outputShapes = [] #output list of shapes
        outputPlms = [] #list of placements
        iChild = 0
        numChildren = len(objectPlms) if outputIsLattice else len(objectShapes) 
        copy_method_index = ShapeCopy.getCopyTypeIndex(obj.Copying)
        
        # the essence
        for iPlm in range(len(placements)):
            if iChild == numChildren:
                if obj.LoopObjectSequence:
                    iChild = 0
                else:
                    break
            
            plm = placements[iPlm]
             
            if outputIsLattice:
                objectPlm = objectPlms[iChild]
                outputPlms.append(plm.multiply(objectPlm))
            else:
                outputShape = ShapeCopy.copyShape(objectShapes[iChild], copy_method_index, plm)
                # outputShape.Placement = plm.multiply(outputShape.Placement) #now done by shape copy routine
                outputShapes.append(outputShape)
            
            iChild += 1
            
        if len(placements) > numChildren and not obj.LoopObjectSequence:
            lattice2Executer.warning(obj,"There are fewer children to populate, than placements to be populated (%1, %2). Extra placements will be dropped.".replace("%1", str(numChildren)).replace("%2",str(len(placements))))
            
        if len(placements) < numChildren:
            lattice2Executer.warning(obj,"There are more children to populate, than placements to be populated (%1, %2). Extra children will be dropped.".replace("%1", str(numChildren)).replace("%2",str(len(placements))))
            
        if outputIsLattice:
            return outputPlms
        else:
            obj.Shape = Part.makeCompound(outputShapes)
            return None