Beispiel #1
0
    def __readBlocksData(self):
        '''
        read block data from file
        '''
        import Base , os
        filename = os.path.join(Base.__currentProjectPath__ , 'data.df')
        if not os.path.exists(filename):
            Base.showErrorMessageBox('FileNotFound', '\'data.df\' file was not found in project path.')
            return
        
        from loadDataTools import ParseDFInputGraphData
        self.dataParser = ParseDFInputGraphData()
        
        if not self.dataParser.parse(str(filename)):
            showErrorMessageBox('Data Error' , 'the schema of file is incorrected')
            self.__mainWidget.ui.loadDataLabel.setText('faild')
            return

        self.__mainWidget.ui.loadDataLabel.setText('sucessed')

        print 'DF data parse successfully'    
        self.__mainWidget.enableConfigPanel(True)
        
        from DDADatabase import df_inputDatabase
        data = df_inputDatabase
        self.__mainWidget.ui.blockNumLineE.setText(str(len(df_inputDatabase.blockMatCollections)))
        print df_inputDatabase.blockMatCollections
        self.__mainWidget.ui.jointNumLineE.setText(str(len(df_inputDatabase.jointMatCollections)))
        print df_inputDatabase.jointMatCollections
        self.dataParser = None
        
        self.__setDefaultParameters()
Beispiel #2
0
    def drawCircle(self , center , radius , shapeType):
        import FreeCAD
        p = FreeCAD.Placement()
        vec = self.getPointInBaseVectorType(center)
#        vec = self.getPointInTupleType(center)
        p.move(vec)
        Base.addCircle2Document(vec , radius , placement=p , face=False, fname =shapeType)
Beispiel #3
0
 def __configMats(self):
     
     if self.__matsWidget.setEarthquakeMaxSteps(self.__mainWidget.ui.stepsNumSpinB.value()):
         self.__matsWidget.show()
     else:
         import Base
         Base.showErrorMessageBox("DataError", "The sum of Earthquake steps and earthquake start step numer is bigger than total steps for DDA analysis.\nPlease modify total step number.")
Beispiel #4
0
    def showGraph4File(self):
        import DDADisplay
        DDADisplay.clearDocument()
        
        Base.DDAObserver.lock = True
        
        from DDADatabase import dl_database as database
        boundaryNodes = database.boundaryNodes
        if len(boundaryNodes)>0:
            Base.addPolyLine2Document('BoundaryLine', ifStore2Database=False)
            print 'draw boundary lines : ' , len(boundaryNodes)

        points = database.fixedPoints
        if len(points)>0:
            Base.addCircles2Document('FixedPoint')
            print 'draw fixed points : ' , len(points)

        points = database.measuredPoints
        if len(points)>0:
            Base.addCircles2Document('MeasuredPoint')
            print 'draw measured points : ' , len(points)

        points = database.loadingPoints
        if len(points)>0:
            Base.addCircles2Document('LoadingPoint')
        print 'draw loading points : ' , len(points)

        points = database.holePoints
        if len(points)>0:
            Base.addCircles2Document('HolePoint')
        print 'draw hole points : ' , len(points)
        
        Base.DDAObserver.lock = False
Beispiel #5
0
    def drawPolygon(self , points , shapeType , materialIndex = 0):
        p = plane.getRotation()
        vertices = range(len(points))
        for i in range(len(points)):
#            vertices[i] = (points[i].x , points[i].y , -1)
            vertices[i] = (points[i][1] , points[i][2] , -1)
            
#        import checkConcave_and_triangulate as triangulate
#        assert triangulate.IfConcave(vertices)
                
        if shapeType == 'Block':
            Base.addPolygons2Document(vertices , placement=p , fname = 'Block' )#, materialIndex = 1)#materialIndex)
Beispiel #6
0
    def storeEarthquakeData(self):
        import Base
        import os
        if not self.ifEarthquakeDataOK():
            Base.showErrorMessageBox('Data Error', 'There are some errors for earthquake configuration.\nPlease check earthquake data.')
        lines = open(self.ui.earthquakeFilenameLabel.text(), 'rb').readlines()

        resultFile = open(os.path.join(Base.__currentProjectPath__, 'earthquake.df'),'wb')
        resultFile.write('%d %f %f\n'%(self.ui.startStepsSpinB.value()+len(lines)-1 \
                         , self.ui.gravitySpinB.value(), self.ui.timeSpinB.value()))
        resultFile.write('0 0 0\n'*self.ui.startStepsSpinB.value())
        resultFile.write(''.join(lines[1:]))
        resultFile.close()
        return True
Beispiel #7
0
    def __calculateDF(self):
        '''
        save parameters to self.current_path/parameters.df , and then start calculation
        '''
        self.__saveParameters2File()

        print 'Calculation button pressed'
        
        def __calc():
            import FreeCADGui
            FreeCADGui.runCommand('DDA_DFCalc')
            import DDAGui
            DDAGui.setInterval4Calculation(self.__mainWidget.ui.spinB_framesInterval.value())
            
        import Base
        Base.delaycommand(__calc)        
Beispiel #8
0
    def __readParameters(self):
        '''
        read parameters from file
        '''
        import Base
        filename = os.path.join(Base.__currentProjectPath__ , 'parameters.df')
        if not os.path.exists(filename):
            Base.showErrorMessageBox('FileNotFound', '\'parameters.df\' file was not found in project path.')
            return

        from loadDataTools import ParseDFInputParameters
        parasParser = ParseDFInputParameters()
        
        if not parasParser.parse(str(filename)):
            showErrorMessageBox('Data Error' , 'the schema of file is incorrected')
            self.__mainWidget.ui.loadParasLabel.setText('faild')
            return        
        self.__mainWidget.ui.loadParasLabel.setText('sucessed')

        self.__storePara2Panel()
Beispiel #9
0
 def selectEarthquakeFile(self):
     import PySide, Base
     fileDialog = PySide.QtGui.QFileDialog(None,'Select earthquake data file'\
                     , Base.__currentProjectPath__)
     fileDialog.setFileMode(PySide.QtGui.QFileDialog.ExistingFile)
     filename = None
     if fileDialog.exec_():
         filename = fileDialog.selectedFiles()[0]
     else:
         return
     
     lines = open(filename, 'rb').readlines()
     if len(lines)>self.__totalSteps+1: # first line is schema
         import Base
         Base.showErrorMessageBox('DataError'\
            , 'The number of earthquake data steps is bigger than total steps.')
         return False 
     print 'selected earthquake file: ', filename
     nums = lines[0].split()
     try:
         steps, gravity, timeInterval = \
                      int(nums[0]) \
                     ,float(nums[1]) \
                     ,float(nums[2])
         self.checkEarthquakeDataValid(lines[1:])
     except:
         import Base
         Base.showErrorMessageBox('DataError'\
            , 'Earthquake data is unvalid')
         return False
         
     if steps==None or gravity==None or timeInterval==None:
         import Base
         Base.showErrorMessageBox('DataError'\
            , 'Earthquake data is unvalid')
         return False
     
     if steps>self.__totalSteps:
         import Base
         Base.showErrorMessageBox('DataError'\
            , 'The number of earthquake steps is bigger than the number of total steps for DDA analysis.')
         return False
         
     
     self.ui.totalStepsSpinB.setValue(steps-1)
     self.ui.startStepsSpinB.setMaximum(self.__totalSteps-steps+1)
     self.ui.earthquakeFilenameLabel.setText(filename)
     self.setEarthquakeParas(0, gravity, timeInterval)
Beispiel #10
0
 def drawPolygons(self , blocks):
     from loadDataTools import Block
     p = plane.getRotation()
     pts = []
     for block in blocks:
         pts.extend(block.vertices)
     Base.initPolygonSets()
     Base.addPolygons2Document(pts, placement=p, fname='Block')
     Base.polygonsAddedDone()
Beispiel #11
0
    def Activated(self, name="None"):
        FreeCAD.Console.PrintMessage( 'Creator activing\n')
        if FreeCAD.activeDDACommand:
            FreeCAD.activeDDACommand.finish()
        self.doc = FreeCAD.ActiveDocument
        self.view = FreeCADGui.ActiveDocument.ActiveView
        self.featureName = name
        
        if not self.doc:
            FreeCAD.Console.PrintMessage( 'FreeCAD.ActiveDocument get failed\n')
            self.finish()
        else:
            FreeCAD.activeDDACommand = self  # FreeCAD.activeDDACommand 在不同的时间会接收不同的命令
            import Base
            Base.__currentStage__ = 'DF' 
            #self.ui.show()

        # Hide Panel
        Base.setCurrentDDACommand(self)
        self.__mainWidget.show()
        
        # clear Dcoument 
        import DDADisplay
        DDADisplay.clearDocument()
Beispiel #12
0
def offset(height, width, orientation=0, position=5):
    '''
    This function return an offset point calculated with height width and orientation
    :param height: part's height
    :param width: part's width
    :param orientation: orientation between 0 to 2
    :param position: from 1 to 9 equal numpad positions
    :return: Base.Vector of the offset
    '''
    out = Base.Vector(0, 0, 0)

    #TODO dashed and dashdot line style doesn't work properly

    if position == 1:
        if orientation == 2:
            out = Base.Vector(-width / 2, -height / 2, 0)
        else:
            out = Base.Vector(0, -height / 2, -width / 2)
        #self.beam.setSolid()

    elif position == 2:
        if orientation == 2:
            out = Base.Vector(0, -height / 2, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, -height / 2, 0)
            #self.beam.setDashDot()

    elif position == 3:
        if orientation == 2:
            out = Base.Vector(width / 2, -height / 2, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, -height / 2, width / 2)
            #self.beam.setDashed()

    elif position == 4:
        if orientation == 2:
            out = Base.Vector(-width / 2, 0, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, 0, -width / 2)
            #self.beam.setSolid()

    elif position == 5:
        if orientation == 2:
            out = Base.Vector(0, 0, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, 0, 0)
            #self.beam.setDashDot()

    elif position == 6:
        if orientation == 2:
            out = Base.Vector(width / 2, 0, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, 0, width / 2)
            #self.beam.setDashed()

    elif position == 7:
        if orientation == 2:
            out = Base.Vector(-width / 2, height / 2, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, height / 2, -width / 2)
            #self.beam.setSolid()

    elif position == 8:
        if orientation == 2:
            out = Base.Vector(0, height / 2, 0)
            #self.beam.setSolid()
        else:
            out = Base.Vector(0, height / 2, 0)
            #self.beam.setDashDot()

    elif position == 9:
        if orientation == 2:
            out = Base.Vector(width / 2, height / 2, 0)
        else:
            out = Base.Vector(0, height / 2, width / 2)
            #self.beam.setDashed()
    return out
Beispiel #13
0
    def Create(doc, constraint, solver, rigid1, rigid2):
        c = constraint

        if c.Type == "sphereCenterIdent" or c.Type == "pointIdentity":
            dep1 = DependencyPointIdentity(c, "point")
            dep2 = DependencyPointIdentity(c, "point")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)

            vert1 = getPos(ob1, c.SubElement1)
            vert2 = getPos(ob2, c.SubElement2)
            dep1.refPoint = vert1
            dep2.refPoint = vert2

        elif c.Type == "pointOnLine":
            dep1 = DependencyPointOnLine(c, "point")
            dep2 = DependencyPointOnLine(c, "pointAxis")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)

            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = getPos(ob2, c.SubElement2)

            axis2 = getAxis(ob2, c.SubElement2)
            dep2.refAxisEnd = dep2.refPoint.add(axis2)

        elif c.Type == "pointOnPlane":
            dep1 = DependencyPointOnPlane(c, "point")
            dep2 = DependencyPointOnPlane(c, "plane")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)

            dep1.refPoint = getPos(ob1, c.SubElement1)

            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            normal2 = a2plib.getPlaneNormal(plane2.Surface)
            #shift refPoint of plane by offset
            try:
                offs = c.offset
            except:
                offs = 0.0
            offsetVector = Base.Vector(normal2)
            offsetVector.multiply(offs)
            dep2.refPoint = dep2.refPoint.add(offsetVector)

            dep2.refAxisEnd = dep2.refPoint.add(normal2)

        elif c.Type == "circularEdge":
            dep1 = DependencyCircularEdge(c, "pointAxis")
            dep2 = DependencyCircularEdge(c, "pointAxis")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)

            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = getPos(ob2, c.SubElement2)

            axis1 = getAxis(ob1, c.SubElement1)
            axis2 = getAxis(ob2, c.SubElement2)

            if dep2.direction == "opposed":
                axis2.multiply(-1.0)
            dep1.refAxisEnd = dep1.refPoint.add(axis1)
            dep2.refAxisEnd = dep2.refPoint.add(axis2)
            #
            if abs(dep2.offset) > solver.mySOLVER_SPIN_ACCURACY * 1e-1:
                offsetAdjustVec = Base.Vector(axis2.x, axis2.y, axis2.z)
                offsetAdjustVec.multiply(dep2.offset)
                dep2.refPoint = dep2.refPoint.add(offsetAdjustVec)
                dep2.refAxisEnd = dep2.refAxisEnd.add(offsetAdjustVec)

        elif c.Type == "planesParallel":
            dep1 = DependencyParallelPlanes(c, "pointNormal")
            dep2 = DependencyParallelPlanes(c, "pointNormal")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            plane1 = getObjectFaceFromName(ob1, c.SubElement1)
            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep1.refPoint = plane1.Faces[0].BoundBox.Center
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            normal1 = a2plib.getPlaneNormal(plane1.Surface)
            normal2 = a2plib.getPlaneNormal(plane2.Surface)

            if dep2.direction == "opposed":
                normal2.multiply(-1.0)
            dep1.refAxisEnd = dep1.refPoint.add(normal1)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)

        elif c.Type == "angledPlanes":
            dep1 = DependencyAngledPlanes(c, "pointNormal")
            dep2 = DependencyAngledPlanes(c, "pointNormal")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            plane1 = getObjectFaceFromName(ob1, c.SubElement1)
            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep1.refPoint = plane1.Faces[0].BoundBox.Center
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            normal1 = a2plib.getPlaneNormal(plane1.Surface)
            normal2 = a2plib.getPlaneNormal(plane2.Surface)
            dep1.refAxisEnd = dep1.refPoint.add(normal1)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)

        elif c.Type == "plane":
            dep1 = DependencyPlane(c, "pointNormal")
            dep2 = DependencyPlane(c, "pointNormal")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            plane1 = getObjectFaceFromName(ob1, c.SubElement1)
            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep1.refPoint = plane1.Faces[0].BoundBox.Center
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            normal1 = a2plib.getPlaneNormal(plane1.Surface)
            normal2 = a2plib.getPlaneNormal(plane2.Surface)
            if dep2.direction == "opposed":
                normal2.multiply(-1.0)
            dep1.refAxisEnd = dep1.refPoint.add(normal1)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)
            #
            if abs(dep2.offset) > solver.mySOLVER_SPIN_ACCURACY * 1e-1:
                offsetAdjustVec = Base.Vector(normal2.x, normal2.y, normal2.z)
                offsetAdjustVec.multiply(dep2.offset)
                dep2.refPoint = dep2.refPoint.add(offsetAdjustVec)
                dep2.refAxisEnd = dep2.refAxisEnd.add(offsetAdjustVec)

        elif c.Type == "axial":
            dep1 = DependencyAxial(c, "pointAxis")
            dep2 = DependencyAxial(c, "pointAxis")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = getPos(ob2, c.SubElement2)
            axis1 = getAxis(ob1, c.SubElement1)
            axis2 = getAxis(ob2, c.SubElement2)
            if dep2.direction == "opposed":
                axis2.multiply(-1.0)

            dep1.refPoint = dep1.adjustRefPoints(ob1, c.SubElement1,
                                                 dep1.refPoint, axis1)
            dep2.refPoint = dep2.adjustRefPoints(ob2, c.SubElement2,
                                                 dep2.refPoint, axis2)

            dep1.refAxisEnd = dep1.refPoint.add(axis1)
            dep2.refAxisEnd = dep2.refPoint.add(axis2)

        elif c.Type == "axisParallel":
            dep1 = DependencyAxisParallel(c, "pointAxis")
            dep2 = DependencyAxisParallel(c, "pointAxis")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = getPos(ob2, c.SubElement2)
            axis1 = getAxis(ob1, c.SubElement1)
            axis2 = getAxis(ob2, c.SubElement2)
            if dep2.direction == "opposed":
                axis2.multiply(-1.0)

            dep1.refAxisEnd = dep1.refPoint.add(axis1)
            dep2.refAxisEnd = dep2.refPoint.add(axis2)

        elif c.Type == "axisPlaneParallel":
            dep1 = DependencyAxisPlaneParallel(c, "pointAxis")
            dep2 = DependencyAxisPlaneParallel(c, "pointNormal")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            axis1 = getAxis(ob1, c.SubElement1)
            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            axis1Normalized = Base.Vector(axis1)
            axis1Normalized.normalize()
            dep1.refAxisEnd = dep1.refPoint.add(axis1Normalized)

            normal2 = a2plib.getPlaneNormal(plane2.Surface)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)

        elif c.Type == "axisPlaneAngle":
            dep1 = DependencyAxisPlaneAngle(c, "pointAxis")
            dep2 = DependencyAxisPlaneAngle(c, "pointNormal")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            axis1 = getAxis(ob1, c.SubElement1)
            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            axis1Normalized = Base.Vector(axis1)
            axis1Normalized.normalize()
            dep1.refAxisEnd = dep1.refPoint.add(axis1Normalized)

            normal2 = a2plib.getPlaneNormal(plane2.Surface)
            if dep2.direction == "opposed":
                normal2.multiply(-1.0)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)

        elif c.Type == "axisPlaneVertical" or c.Type == "axisPlaneNormal":  # axisPlaneVertical for compat.
            dep1 = DependencyAxisPlaneNormal(c, "pointAxis")
            dep2 = DependencyAxisPlaneNormal(c, "pointNormal")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)
            axis1 = getAxis(ob1, c.SubElement1)
            plane2 = getObjectFaceFromName(ob2, c.SubElement2)
            dep1.refPoint = getPos(ob1, c.SubElement1)
            dep2.refPoint = plane2.Faces[0].BoundBox.Center

            axis1Normalized = Base.Vector(axis1)
            axis1Normalized.normalize()
            dep1.refAxisEnd = dep1.refPoint.add(axis1Normalized)

            normal2 = a2plib.getPlaneNormal(plane2.Surface)
            if dep2.direction == "opposed":
                normal2.multiply(-1.0)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)

        elif c.Type == "CenterOfMass":
            dep1 = DependencyCenterOfMass(c, "point")
            dep2 = DependencyCenterOfMass(c, "point")

            ob1 = doc.getObject(c.Object1)
            ob2 = doc.getObject(c.Object2)

            if c.SubElement1.startswith('Face'):
                plane1 = getObjectFaceFromName(ob1, c.SubElement1)
                dep1.refPoint = plane1.Faces[0].CenterOfMass
            elif c.SubElement1.startswith('Edge'):
                plane1 = Part.Face(
                    Part.Wire(getObjectEdgeFromName(ob1, c.SubElement1)))
                dep1.refPoint = plane1.CenterOfMass
            if c.SubElement2.startswith('Face'):
                plane2 = getObjectFaceFromName(ob2, c.SubElement2)
                dep2.refPoint = plane2.Faces[0].CenterOfMass
            elif c.SubElement2.startswith('Edge'):
                plane2 = Part.Face(
                    Part.Wire(getObjectEdgeFromName(ob2, c.SubElement2)))
                dep2.refPoint = plane2.CenterOfMass

            normal1 = a2plib.getPlaneNormal(plane1.Surface)
            normal2 = a2plib.getPlaneNormal(plane2.Surface)

            if dep2.direction == "opposed":
                normal2.multiply(-1.0)
            dep1.refAxisEnd = dep1.refPoint.add(normal1)
            dep2.refAxisEnd = dep2.refPoint.add(normal2)
            #  to be improved: toggle direction even if offset == 0.0
            if abs(dep2.offset) > solver.mySOLVER_SPIN_ACCURACY * 1e-1:
                offsetAdjustVec = Base.Vector(normal2.x, normal2.y, normal2.z)
                offsetAdjustVec.multiply(dep2.offset)
                dep2.refPoint = dep2.refPoint.add(offsetAdjustVec)
                dep2.refAxisEnd = dep2.refAxisEnd.add(offsetAdjustVec)

        else:
            raise NotImplementedError(
                "Constraint type {} was not implemented!".format(c.Type))

        # Assignments
        dep1.currentRigid = rigid1
        dep1.dependedRigid = rigid2
        dep1.foreignDependency = dep2

        dep2.currentRigid = rigid2
        dep2.dependedRigid = rigid1
        dep2.foreignDependency = dep1

        rigid1.dependencies.append(dep1)
        rigid2.dependencies.append(dep2)
Beispiel #14
0
def FreeCADv(v):
    if not isinstance(v, Vector3):
        raise Exception('Converting ' + str(type(v)) + ' to Base.Vector!')
    return Base.Vector(v.x, v.y, v.z)
Beispiel #15
0
#print(lightSource.CameraPixelIndicesArePointInMyPlane(camera, 3, 17))

# Run a scan and save the image

polygons = GetVisibilityPolygons(lightSource, room)
PlotPolygons(polygons)
#SaveCameraImageLights(camera, room, polygons, "/home/ensab/rrlOwncloud/RepRapLtd/Engineering/External-Projects/Scantastic/Scanner-Dev/Simulator/scan")
#SaveCameraImageRoom(camera, room, roomLight, "/home/ensab/rrlOwncloud/RepRapLtd/Engineering/External-Projects/Scantastic/Scanner-Dev/Simulator/scan")
'''

# Realistic (?) simulation

# Make the room

a = Part.makeBox(4200, 3400, 2000)
a.translate(Base.Vector(-2100, 0, -500))
b = Part.makeBox(4000, 3600, 3000)
b.translate(Base.Vector(-2000, -300, -400))
room = a.cut(b)

calibration1 = Part.makeBox(500, 500, 2000)
calibration2 = Part.makeBox(500, 500, 2000)
calibration1.rotate(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 25)
calibration2.rotate(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 37)
calibration2.translate(Base.Vector(-400, 2500, -500))
calibration1.translate(Base.Vector(300, 2200, -500))
room = room.fuse(calibration1)
room = room.fuse(calibration2)

#roomLight = ScannerPart(offset = Vector3(200, 200, 1000), parent = world)
    def objArc(self, d, cx, cy, rx, ry, st, en, closed, node, mat):
        """
    We ignore the path d, and produce a nice arc object.
    We distinguish two cases. If it looks like a circle, we produce ArcOfCircle,
    else we produce ArcOfEllipse.

    To find the arc end points, we use the value() property of the Circle and Ellipse
    objects. With Circle we have to take care of mirror and rotation ourselves.

    If closed, we connect the two ends to the center with lines. The connections
    are secured with constraints.
    Radii are currently not secured with constraints.
    """
        ### CAUTION: Keep in sync with objEllipse() above.
        # print("objArc: st,en,closed", st, en, closed)
        self._matrix_from_svg(mat)
        c = self._from_svg(cx, cy, bbox=False)
        ori = self._from_svg(0, 0, bbox=False)
        vrx = self._from_svg(rx, 0, bbox=False) - ori
        vry = self._from_svg(0, ry, bbox=False) - ori
        i = self.ske.GeometryCount
        (st_idx, en_idx) = (1, 2)
        majAxisIdx = None

        if abs(vrx.Length - vry.Length) < epsilon:
            # it is a circle.
            self.bbox.add(c + vrx + vry)
            self.bbox.add(c - vrx - vry)
            ce = Part.Circle(Center=c,
                             Normal=Base.Vector(0, 0, 1),
                             Radius=vrx.Length)

            # Circles are immune to rotation and mirorring. Apply this manually.
            if self.yflip:
                (st, en) = (-en, -st)  ## coord system is mirrored.
            else:
                (st, en) = (en, st)  ## hmm.
                print("FIXME: ArcOfCircle() with yflip=False needs debugging.")
            r = Base.Matrix()
            r.rotateZ(st)
            pst = r.multiply(vrx)
            st = pst.getAngle(Base.Vector(
                1, 0, 0))  # ce.rotateZ() is a strange beast.
            pst = pst + c
            r = Base.Matrix()
            r.rotateZ(en)
            pen = r.multiply(vrx)
            en = pen.getAngle(Base.Vector(
                1, 0, 0))  # ce.rotateZ() is a strange beast.
            pen = pen + c

            self.ske.addGeometry([Part.ArcOfCircle(ce, st, en)])
            self.stats['objArc'] += 1

        else:
            # major axis is defined by Center and S1,
            # major radius is the distance between Center and S1,
            # minor radius is the distance between S2 and the major axis.
            s1 = self._from_svg(cx + rx, cy, bbox=False)
            s2 = self._from_svg(cx, cy + ry, bbox=False)
            (V1, V2, V3, V4) = self._ellipse_vertices2d(c, s1, s2)
            self.bbox.add(V1)
            self.bbox.add(V2)
            self.bbox.add(V3)
            self.bbox.add(V4)
            i = int(self.ske.GeometryCount)
            ce = Part.Ellipse(S1=V1, S2=V2, Center=c)
            self.ske.addGeometry([Part.ArcOfEllipse(ce, st, en)])
            if self.expose_int: self.ske.exposeInternalGeometry(i)
            majAxisIdx = i + 1  # CAUTION: is that a safe assumption?
            self.stats['objArc'] += 1
            ## CAUTION: with yflip=True sketcher reverses the endpoints of
            ##          an ArcOfEllipse to: en=1, st=2
            ##          ArcOfCircle seems unaffected.
            if self.yflip: (st_idx, en_idx) = (2, 1)
            r = Base.Matrix()
            r.rotateZ(st)
            pst = r.multiply(vrx) + c
            r = Base.Matrix()
            r.rotateZ(en)
            pen = r.multiply(vrx) + c

        j = self.ske.GeometryCount
        if closed:
            self.ske.addGeometry([
                Part.LineSegment(ce.value(en), c),
                Part.LineSegment(c, ce.value(st))
            ])

            if True:  # when debugging deformations, switch off constriants first.
                self.ske.addConstraint([
                    Sketcher.Constraint('Coincident', i + 0, en_idx, j + 0,
                                        1),  # arc with line
                    Sketcher.Constraint('Coincident', j + 1, 2, i + 0,
                                        st_idx),  # line with arc
                    Sketcher.Constraint('Coincident', j + 0, 2, j + 1,
                                        1),  # line with line
                    Sketcher.Constraint('Coincident', j + 0, 2, i + 0, 3)
                ])  # line with center

        if False:  # some debugging circles.
            self.ske.addGeometry(
                [
                    # Part.Circle(Center=pst, Normal=Base.Vector(0,0,1), Radius=2),
                    # Part.Circle(Center=pen, Normal=Base.Vector(0,0,1), Radius=3),
                    # Part.Circle(Center=ce.value(st), Normal=Base.Vector(0,0,1), Radius=4),
                    Part.Circle(Center=ce.value(en),
                                Normal=Base.Vector(0, 0, 1),
                                Radius=5)
                ],
                True)

        # we return the start, end and center points, as triple (sketcher_index, sketcher_index_point, Vector)
        return ((i + 0, st_idx, ce.value(st)), (i + 0, en_idx, ce.value(en)),
                (i + 0, 3, c), majAxisIdx)
Beispiel #17
0
 def discretize(self, nS, nP):
     """ Discretize the surface.
     @param nS Number of sections
     @param nP Number of points per section
     """
     self.obj.addProperty(
         "App::PropertyInteger", "nSections", "Ship",
         str(Translator.translate("Number of sections"))).nSections = nS
     self.obj.addProperty(
         "App::PropertyIntegerList", "nPoints", "Ship",
         str(
             Translator.translate(
                 "List of number of points per sections (accumulated histogram)"
             ))).nPoints = [0]
     self.obj.addProperty(
         "App::PropertyFloatList", "xSection", "Ship",
         str(Translator.translate(
             "List of sections x coordinate"))).xSection = []
     self.obj.addProperty(
         "App::PropertyVectorList", "mSections", "Ship",
         str(Translator.translate(
             "List of sections points"))).mSections = []
     nPoints = [0]
     xSection = []
     mSections = []
     # Get bounds
     shape = self.obj.Shape
     bbox = shape.BoundBox
     x0 = bbox.XMin
     x1 = bbox.XMax
     y0 = bbox.YMin
     y1 = bbox.YMax
     z0 = bbox.ZMin
     z1 = bbox.ZMax
     # Create a set of planes to perfom edges sections
     planes = []
     dz = (z1 - z0) / (nP - 1)
     for j in range(0, nP):
         z = z0 + j * dz
         rX = x1 - x0
         rY = max(y1 - y0, abs(y1), abs(y0))
         planes.append(
             Part.makePlane(4 * rX, 4 * rY,
                            Base.Vector(-2 * rX, -2 * rY, z),
                            Base.Vector(0, 0, 1)))
     # Division are performed at x axis
     dx = (x1 - x0) / (nS - 1.0)
     for i in range(0, nS):
         section = []
         x = x0 + i * dx
         xSection.append(x)
         percen = i * 100 / (nS - 1)
         FreeCAD.Console.PrintMessage('%d%%\n' % (percen))
         # Slice the surface to get curves
         wires = shape.slice(Vector(1.0, 0.0, 0.0), x)
         if not wires:
             if (i != 0) or (i != nS - 1):
                 msg = 'Found empty section at x=%g\n' % (x)
                 msg = Translator.translate(msg)
                 FreeCAD.Console.PrintWarning(msg)
                 FreeCAD.Console.PrintWarning(
                     '\tThis may happens if a bad defined (or really complex) surface has been provided.\n'
                 )
                 FreeCAD.Console.PrintWarning(
                     '\tPlease, ensure that this section is correct, or fix surfaces and create a new ship.\n'
                 )
                 nPoints.append(0)
                 continue
         # Desarrollate wires into edges list
         edges = []
         for j in range(0, len(wires)):
             wire = wires[j].Edges
             for k in range(0, len(wire)):
                 edges.append(wire[k])
         # Slice curves to get points
         points = []
         for k in range(0, nP):
             planePoints = []
             for j in range(0, len(edges)):
                 aux = self.lineFaceSection(edges[j], planes[k])
                 for l in range(0, len(aux)):
                     planePoints.append(Vector(aux[l].X, aux[l].Y,
                                               aux[l].Z))
             if not planePoints:  # No section found, symmetry plane point will used
                 planePoints.append(Vector(x, 0, z0 + k * dz))
             # Get Y coordinates
             auxY = []
             for l in range(0, len(planePoints)):
                 auxY.append(planePoints[l].y)
             # Sort them
             auxY.sort()
             # And store
             for l in range(0, len(planePoints)):
                 points.append(
                     Vector(planePoints[l].x, auxY[l], planePoints[l].z))
         # Store points
         section = points[:]
         nPoints.append(len(section))
         for j in range(0, len(section)):
             mSections.append(section[j])
     # Save data
     for i in range(1, len(nPoints)):
         nPoints[i] = nPoints[i] + nPoints[i - 1]
     self.obj.nPoints = nPoints[:]
     self.obj.xSection = xSection[:]
     self.obj.mSections = mSections[:]
     msg = '%d Discretization points performed\n' % (len(mSections))
     msg = Translator.translate(msg)
     FreeCAD.Console.PrintMessage(msg)
Beispiel #18
0
def design_base(wall_t, wall_width, base_width, base_thickness, base_length,
                span_length, key_depth, folder_path):
    x = span_length / 2 + base_length
    s = base_width - wall_width
    y = s / 3
    y = y + (wall_width / 2)
    point = []
    point.append(Base.Vector(-x, y, 0))
    point.append(Base.Vector(-x + base_length, y, 0))
    point.append(Base.Vector(-x + base_length, wall_width / 2, 0))
    point.append(Base.Vector(-x + base_length + span_length, wall_width / 2,
                             0))
    point.append(Base.Vector(-x + base_length + span_length, y, 0))
    point.append(Base.Vector(x, y, 0))
    point.append(Base.Vector(x, y - base_width, 0))
    point.append(Base.Vector(x - base_length, y - base_width, 0))
    point.append(Base.Vector(x - base_length, -wall_width / 2, 0))
    point.append(Base.Vector(x - base_length - span_length, -wall_width / 2,
                             0))
    point.append(Base.Vector(x - base_length - span_length, y - base_width, 0))
    point.append(
        Base.Vector(x - base_length - span_length - base_length,
                    y - base_width, 0))
    edg = list()
    for i in range(0, 11):
        edg.append(Part.makeLine(point[i], point[i + 1]))
    edg.append(Part.makeLine(point[11], point[0]))
    w = Part.Wire(edg)
    f = Part.Face(w)
    P = f.extrude(FreeCAD.Vector(0, 0, base_thickness))
    nsolid = P
    cylinders = bolt_holes(wall_t, span_length, base_length, base_width,
                           base_thickness)
    for i in cylinders:
        nsolid = nsolid.cut(i)
    filepath = folder_path + "/barrier_base.stp"
    nsolid.exportStep(filepath)
    keys = design_key(span_length, base_length, base_width, key_depth,
                      wall_width, wall_t)
    compound = Part.makeCompound([keys[0], nsolid])
    compound = Part.makeCompound([compound, keys[1]])
    compound.exportStep(folder_path + "/barrier_foundation.stp")
Beispiel #19
0
def cmpPos(doc=None):  ## compare exported positions with the selected doc
    if doc is None:
        doc = FreeCAD.ActiveDocument
    # rmvSuffix(doc)
    full_content = []
    positions_content = []
    sketch_content = []
    sketch_content_header = []
    #if doc is not None:
    if len(doc.FileName) == 0:
        docFn = 'File Not Saved'
    else:
        docFn = doc.FileName
    line = 'title: ' + doc.Name
    full_content.append(line + '\n')
    line = 'FileN: ' + docFn
    full_content.append(line + '\n')
    #print(line)
    line = 'date :' + str(datetime.datetime.now())
    full_content.append(line + '\n')
    #print(line)
    line = '3D models Placement ---------------'
    full_content.append(line + '\n')
    #print(line)
    for o in doc.Objects:
        # print(o.Name,o.Label,o.TypeId)
        if (hasattr(o, 'Shape') or o.TypeId == 'App::Link') and (hasattr(
                o, 'Placement')) and (o.TypeId != 'App::Line') and (
                    o.TypeId != 'App::Plane'):
            if 'Sketch' not in o.Label and 'Pcb' not in o.Label:
                #oPlacement = 'Placement [Pos=('+"{0:.3f}".format(o.Placement.Base.x)+','+"{0:.3f}".format(o.Placement.Base.y)+','+"{0:.3f}".format(o.Placement.Base.z)+\
                #'), Yaw-Pitch-Roll=('+"{0:.3f}".format(o.Placement.Rotation.toEuler()[0])+','+"{0:.3f}".format(o.Placement.Rotation.toEuler()[1])+','+"{0:.3f}".format(o.Placement.Rotation.toEuler()[2])+')]'
                #oPlacement = 'Placement [Pos=('+"{0:.2f}".format(o.Placement.Base.x)+','+"{0:.2f}".format(o.Placement.Base.y)+','+"{0:.2f}".format(o.Placement.Base.z)+\
                #'), Yaw-Pitch-Roll=('+"{0:.2f}".format(o.Placement.Rotation.toEuler()[0])+','+"{0:.2f}".format(o.Placement.Rotation.toEuler()[1])+','+"{0:.2f}".format(o.Placement.Rotation.toEuler()[2])+')]'
                #oPlacement=oPlacement.replace('-0.00','0.00')
                #line=o.Label[:o.Label.find('_')]+','+oPlacement
                # line=o.Label[:o.Label.find('_')]+','+ str(o.Placement.toMatrix())
                # positions_content.append(line+'\n')
                # print (line)
                rMtx = roundMatrix(o.Placement.toMatrix())
                line = o.Label[:o.Label.find('_')] + ', P.Mtx(' + str(
                    rMtx) + ')'
                positions_content.append(line + '\n')
                #print (line)
        if o.Label == 'PCB_Sketch':
            line = 'Sketch geometry -------------------'
            sketch_content_header.append(line + '\n')
            #print('Sketch geometry -------------------')
            if hasattr(o, 'Geometry'):
                for e in o.Geometry:
                    if not e.Construction:
                        line = str(roundEdge(e))
                        sketch_content.append(line + '\n')
                        #print (e)
            sketch_content.sort()
            sketch_content[:0] = sketch_content_header
            #sketch_content_header.extend(sketch_content)
            #sketch_content=[]
            #sketch_content=sketch_content_header
            line = '-----------------------------------'
            sketch_content.append(line + '\n')
            #print(line)
        if o.Label == 'Pcb':
            line = 'Pcb Volume -------------------'
            sketch_content.append(line + '\n')
            #print(line)
            vol = o.Shape.Volume
            vol = decimals(vol, 3)
            line = 'Pcb Volume = ' + str(vol)
            sketch_content.append(line + '\n')
            #print (line)
            line = '-----------------------------------'
            sketch_content.append(line + '\n')
            #print(line)
    positions_content.sort()
    full_content.extend(positions_content)
    full_content.extend(sketch_content)
    line = 'END of List -----------------------'
    full_content.append(line + '\n')
    #print(line)
    testing = False
    pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/kicadStepUp")
    if not pg.IsEmpty():
        lastPath = pg.GetString('lastPath')
    if len(lastPath) == 0:
        home = expanduser("~")
        pg.SetString('lastPath', home)
    else:
        home = lastPath
    #home = expanduser("~")
    #home = r'C:\Cad\Progetti_K\board-revision\SolidWorks-2018-09-03_fede'
    if not testing:
        Filter = ""
        name, Filter = PySide.QtGui.QFileDialog.getOpenFileName(
            None,
            "Open 3D models & footprint positions Report file\nto compare positions with the Active Document...",
            home, "*.rpt")
        #path, fname = os.path.split(name)
        #fname=os.path.splitext(fname)[0]
        #fpth = os.path.dirname(os.path.abspath(__file__))
        if name:
            lastPath = os.path.dirname(os.path.abspath(name))
            pg.SetString('lastPath', lastPath)
    else:
        if os.path.isdir("d:/Temp/"):
            name = 'd:/Temp/ex2.rpt'
        elif os.path.isdir("c:/Temp/"):
            name = 'c:/Temp/ex2.rpt'
    #say(name)
    if os.path.exists(name):
        with open(name) as a:
            a_content = a.readlines()
        b_content = full_content
        #print (a_content);print ('-----------b_c----------');print (b_content);stop
        diff = difflib.unified_diff(a_content, b_content)
        diff_content = []
        diff_list = []
        sk_add = []
        sk_sub = []
        header = "***** Unified diff ************"
        diff_content.append(header + os.linesep)
        #print(header)
        header1 = "Line no" + 5 * ' ' + 'previous' + 5 * ' ' + 'updated'
        #print("Line no"+'\t'+'file1'+'\t'+'file2')
        #print(header1)
        diff_content.append(header1 + os.linesep)
        for i, line in enumerate(diff):
            if line.startswith("-"):
                if not line.startswith("---") and not line.startswith("-title") \
                        and not line.startswith("-FileN") and not line.startswith("-date "):
                    #print(i,'\t\t'+line)
                    #print('Ln '+str(i)+(8-(len(str(i))))*' '),(line),
                    diff_content.append('Ln ' + str(i) +
                                        (8 - len(str(i))) * ' ' + line)
                    if line.startswith('-<Line'):
                        points = line.replace('-<Line segment (',
                                              '').replace(') >', '')
                        p1 = points[:points.find(')')].split(',')
                        p2 = points[points.rfind('(') + 1:-1].split(',')
                        sk_sub.append(
                            PLine(
                                Base.Vector(round(float(p1[0]), 3),
                                            round(float(p1[1]), 3),
                                            round(float(p1[2]), 3)),
                                Base.Vector(float(p2[0]), float(p2[1]),
                                            float(p2[2]))))
                    elif line.startswith('-ArcOfCircle'):
                        data = line.replace('-ArcOfCircle (Radius : ',
                                            '').replace('))\n', '')
                        data = data.split(':')
                        radius = data[0].split(',')[0]
                        pos = data[1][data[1].find('(') +
                                      1:data[1].find(')')].split(',')
                        dir = data[2][data[2].find('(') +
                                      1:data[2].rfind(')')].split(',')
                        par = data[3][data[3].find('(') + 1:].split(',')
                        #print (radius,pos,dir,par);stop
                        sk_sub.append(
                            Part.ArcOfCircle(
                                Part.Circle(
                                    FreeCAD.Vector(round(float(pos[0]), 3),
                                                   round(float(pos[1]), 3),
                                                   round(float(pos[2]), 3)),
                                    FreeCAD.Vector(float(dir[0]),
                                                   float(dir[1]),
                                                   float(dir[2])),
                                    round(float(radius), 3)),
                                round(float(par[0]), 5),
                                round(float(par[1]), 5)))
                    elif line.startswith('-Circle'):
                        data = line.replace('-Circle (Radius : ',
                                            '').replace('))\n', '')
                        data = data.split(':')
                        radius = data[0].split(',')[0]
                        pos = data[1][data[1].find('(') +
                                      1:data[1].find(')')].split(',')
                        dir = data[2][data[2].find('(') + 1:].split(',')
                        print(radius, pos, dir)
                        sk_sub.append(
                            Part.Circle(
                                FreeCAD.Vector(round(float(pos[0]), 3),
                                               round(float(pos[1]), 3),
                                               round(float(pos[2]), 3)),
                                FreeCAD.Vector(float(dir[0]), float(dir[1]),
                                               float(dir[2])),
                                round(float(radius), 3)))
            elif line.startswith("+"):
                if not line.startswith("+++") and not line.startswith("+title") \
                        and not line.startswith("+FileN") and not line.startswith("+date "):
                    #print(i,'\t\t'+line)
                    #print('Ln '+str(i)+(8-(len(str(i))))*' '),(line),
                    diff_content.append('Ln ' + str(i) +
                                        (8 - len(str(i))) * ' ' + line)
                    diff_list.append(line[1:])
                    if line.startswith('+<Line'):
                        points = line.replace('+<Line segment (',
                                              '').replace(') >', '')
                        p1 = points[:points.find(')')].split(',')
                        p2 = points[points.rfind('(') + 1:-1].split(',')
                        sk_add.append(
                            PLine(
                                Base.Vector(float(p1[0]), float(p1[1]),
                                            float(p1[2])),
                                Base.Vector(float(p2[0]), float(p2[1]),
                                            float(p2[2]))))
                    #    sk_add.append(line.replace('+<Line segment ','').replace(' >',''))
                    elif line.startswith('+ArcOfCircle'):
                        data = line.replace('+ArcOfCircle (Radius : ',
                                            '').replace('))\n', '')
                        data = data.split(':')
                        radius = data[0].split(',')[0]
                        pos = data[1][data[1].find('(') +
                                      1:data[1].find(')')].split(',')
                        dir = data[2][data[2].find('(') +
                                      1:data[2].rfind(')')].split(',')
                        par = data[3][data[3].find('(') + 1:].split(',')
                        #print (radius,pos,dir,par);stop
                        sk_add.append(
                            Part.ArcOfCircle(
                                Part.Circle(
                                    FreeCAD.Vector(float(pos[0]),
                                                   float(pos[1]),
                                                   float(pos[2])),
                                    FreeCAD.Vector(float(dir[0]),
                                                   float(dir[1]),
                                                   float(dir[2])),
                                    float(radius)), float(par[0]),
                                float(par[1])))
                    elif line.startswith('+Circle'):
                        data = line.replace('+Circle (Radius : ',
                                            '').replace('))\n', '')
                        data = data.split(':')
                        radius = data[0].split(',')[0]
                        pos = data[1][data[1].find('(') +
                                      1:data[1].find(')')].split(',')
                        dir = data[2][data[2].find('(') + 1:].split(',')
                        print(radius, pos, dir)
                        sk_add.append(
                            Part.Circle(
                                FreeCAD.Vector(float(pos[0]), float(pos[1]),
                                               float(pos[2])),
                                FreeCAD.Vector(float(dir[0]), float(dir[1]),
                                               float(dir[2])), float(radius)))
        #for d in (diff_content):
        #    print (d)
        #for d in (diff_list):
        #    print(d)
        #diff_content = a_content + b_content
        try:
            f = open(home + "\list_diff.lst", "w")
            f.write(''.join(diff_content))
            f.close
        except:
            FreeCAD.Console.PrintError(
                'Error in write permission for \'list_diff.lst\' report file.\n'
            )
        FreeCADGui.Selection.clearSelection()
        nObj = 0
        old_pcb_tval = 100
        pcbN = ''
        diff_objs = []
        generate_sketch = False
        for o in doc.Objects:
            if hasattr(o, 'Shape') or o.TypeId == 'App::Link':
                if 'Sketch' not in o.Label and 'Pcb' not in o.Label:
                    for changed in diff_list:
                        if not changed[0].startswith('date'):
                            ref = changed.split(',')[0]
                            if o.Label.startswith(ref + '_'):
                                #FreeCADGui.Selection.addSelection(o)
                                gui_addSelection(o)
                                diff_objs.append(o)
                                #FreeCAD.Console.PrintWarning(o.Label+'\n') #;print('selected')
                                nObj += 1
                if 'Sketch' not in o.Label and 'Pcb' in o.Label:
                    old_pcb_tval = FreeCADGui.ActiveDocument.getObject(
                        o.Name).Transparency
                    FreeCADGui.ActiveDocument.getObject(
                        o.Name).Transparency = 70
                    pcbN = o.Name
                if 'PCB_Sketch' in o.Label and 'Sketch' in o.TypeId:
                    generate_sketch = True
        #print(''.join(diff_content)); stop
        if nObj > 0:
            dc = ''.join(diff_content)
            print(dc)
            for o in diff_objs:
                FreeCAD.Console.PrintWarning(o.Label + '\n')
            FreeCAD.Console.PrintError(
                'N.' + str(nObj) +
                ' Object(s) with changed placement \'Selected\'\n')
            #print ('Circle' in diff_content)
            if dc.find('Circle') != -1 or dc.find(
                    'Line segment') != -1:  # or dc.find('ArcOfCircle')!=-1:
                FreeCAD.Console.PrintError(
                    '*** \'Pcb Sketch\' modified! ***\n')
        elif len(diff_content) > 3:
            FreeCAD.Console.PrintError('\'Pcb Sketch\' modified!\n')
            #for d in (diff_content):
            #    print (d)
            #print(''.join(diff_content))
            if len(pcbN) > 0:
                FreeCADGui.ActiveDocument.getObject(
                    pcbN).Transparency = old_pcb_tval
        else:
            FreeCAD.Console.PrintWarning('no changes\n')
            if len(pcbN) > 0:
                FreeCADGui.ActiveDocument.getObject(
                    pcbN).Transparency = old_pcb_tval
        generateSketch = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/kicadStepUpGui").GetBool(
                'generate_sketch')
        if generate_sketch and generateSketch:
            if len(sk_add) > 0:
                #print(sk_add)
                if FreeCAD.activeDocument().getObject(
                        "Sketch_Addition") is not None:
                    FreeCAD.activeDocument().removeObject("Sketch_Addition")
                Sketch_Addition = FreeCAD.activeDocument().addObject(
                    'Sketcher::SketchObject', 'Sketch_Addition')
                FreeCADGui.activeDocument().getObject(
                    "Sketch_Addition").LineColor = (0.000, 0.000, 1.000)
                FreeCADGui.activeDocument().getObject(
                    "Sketch_Addition").PointColor = (0.000, 0.000, 1.000)
                Sketch_Addition.Geometry = sk_add
            if len(sk_sub) > 0:
                #print(sk_sub)
                if FreeCAD.activeDocument().getObject(
                        "Sketch_Subtraction") is not None:
                    FreeCAD.activeDocument().removeObject("Sketch_Subtraction")
                Sketch_Subtraction = FreeCAD.activeDocument().addObject(
                    'Sketcher::SketchObject', 'Sketch_Subtraction')
                FreeCADGui.activeDocument().getObject(
                    "Sketch_Subtraction").LineColor = (0.667, 0.000, 0.498)
                FreeCADGui.activeDocument().getObject(
                    "Sketch_Subtraction").PointColor = (0.667, 0.000, 0.498)
                Sketch_Subtraction.Geometry = sk_sub
            if len(sk_add) > 0 or len(sk_sub) > 0:
                FreeCAD.ActiveDocument.recompute()
    def _holeCenterLength(self):
        return 178

    @property
    def _holeCenterWidth(self):
        return 128

    @property
    def _insideLength(self):
        return 191.73

    @property
    def _insideWidth(self):
        return 141.73

    def __init__(self, name, origin):
        self.name = name
        if not isinstance(origin, Base.Vector):
            raise RuntimeError("origin is not a Vector!")
        self.origin = origin
        self._buildLid()


if __name__ == '__main__':
    App.ActiveDocument = App.newDocument("Boxes")
    doc = App.activeDocument()
    baselid = RL6685Lid("RL6685", Base.Vector(0, 0, 0))
    baselid.show()
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewIsometric()
Beispiel #21
0
 def calcFaceKeys(self, face, pl):
     keys = []
     # A sphere...
     if str( face.Surface ).startswith('Sphere'):
         keys.append(
             'SPH;'+
             self.calcVertexKey(pl.multVec(face.Surface.Center))+
             self.calcFloatKey(face.Surface.Radius)
             )
     # a cylindric face...
     elif all( hasattr(face.Surface,a) for a in ['Axis','Center','Radius'] ):
         axisStart = pl.multVec(face.Surface.Center)
         axisEnd   = pl.multVec(face.Surface.Center.add(face.Surface.Axis))
         axis = axisEnd.sub(axisStart)
         axisKey = self.calcAxisKey(axis)
         negativeAxis = Base.Vector(axis)
         negativeAxis.multiply(-1.0)
         negativeAxisKey = self.calcAxisKey(negativeAxis)
         radiusKey = self.calcFloatKey(face.Surface.Radius)
         #
         for v in face.Vertexes:
             vertexKey = self.calcVertexKey(pl.multVec(v.Point))
             keys.append(
                 'CYL;'+
                 vertexKey+
                 axisKey+
                 radiusKey
                 )
             keys.append(
                 'CYL;'+
                 vertexKey+
                 negativeAxisKey+
                 radiusKey
                 )
     elif str( face.Surface ) == '<Plane object>':
         pt = face.Vertexes[0].Point
         uv=face.Surface.parameter(pt)
         u=uv[0]
         v=uv[1]
         normal=face.normalAt(u,v)
         normalStart = pl.multVec(pt)
         normalEnd = pl.multVec(pt.add(normal))
         normal = normalEnd.sub(normalStart)
         negativeNormal = Base.Vector(normal)
         negativeNormal.multiply(-1.0)
         normalKey = self.calcAxisKey(normal)
         negativeNormalKey = self.calcAxisKey(negativeNormal)
         for vert in face.Vertexes:
             vertexKey = self.calcVertexKey(pl.multVec(vert.Point))
             keys.append(
                 'PLANE;'+
                 vertexKey+
                 normalKey
                 )
             keys.append(
                 'PLANE;'+
                 vertexKey+
                 negativeNormalKey
                 )
     else:
         keys.append("NOTRACE")
     return keys #FIXME
Beispiel #22
0
def place_steps(doc, placement, board_thickness):
    """ place_steps(doc,placement,board_thickness)->place step models on board 

        list of models and path to step files is set at start of this script
                 model_tab_filename= "" &   step_path="" """
    model_file = pythonopen(model_tab_filename, "r")
    model_lines = model_file.readlines()
    model_file.close()
    model_dict = []
    if IDF_diag == 1:
        model_file = pythonopen(IDF_diag_path + "/missing_models.lst", "w")
    keys = []
    #prev_step="*?.*?" #hope nobody will insert this step filename
    step_dict = []
    for model_line in model_lines:
        model_records = split_records(model_line)
        if len(model_records
               ) > 1 and model_records[0] and not model_records[0] in keys:
            keys.append(model_records[0])
            model_dict.append((str(model_records[0]).replace('"', ''),
                               str(model_records[1]).replace('"', '')))
    model_dict = dict(model_dict)
    validkeys = filter(
        lambda x: x in [place_item[2] for place_item in placement],
        model_dict.keys())
    FreeCAD.Console.PrintMessage("Step models to be loaded for footprints: " +
                                 str(validkeys) + "\n")
    grp = doc.addObject("App::DocumentObjectGroup", "Step Lib")
    for validkey in validkeys:
        ImportGui.insert(step_path + model_dict[validkey],
                         FreeCAD.ActiveDocument.Name)
        #partName=FreeCAD.ActiveDocument.ActiveObject.Name
        impPart = FreeCAD.ActiveDocument.ActiveObject
        #impPart.Shape=FreeCAD.ActiveDocument.ActiveObject.Shape
        #impPart.ViewObject.DiffuseColor=FreeCAD.ActiveDocument.ActiveObject.ViewObject.DiffuseColor
        impPart.ViewObject.Visibility = 0
        impPart.Label = validkey
        grp.addObject(impPart)
        step_dict.append((validkey, impPart))
        FreeCAD.Console.PrintMessage("Reading step file " +
                                     str(model_dict[validkey]) +
                                     " for footprint " + str(validkey) + "\n")
    step_dict = dict(step_dict)
    grp = doc.addObject("App::DocumentObjectGroup", "Step Models")
    for place_item in placement:
        if step_dict.has_key(place_item[2]):
            step_model = doc.addObject("Part::Feature", place_item[0] + "_s")
            FreeCAD.Console.PrintMessage("Adding STEP model " +
                                         str(place_item[0]) + "\n")
            #if prev_step!=place_item[2]:
            #   model0=Part.read(step_path+"/"+model_dict[place_item[2]])
            #   prev_step=place_item[2]
            step_model.Shape = step_dict[place_item[2]].Shape
            step_model.ViewObject.DiffuseColor = step_dict[
                place_item[2]].ViewObject.DiffuseColor
            z_pos = 0
            rotateY = 0
            if place_item[6] == 'BOTTOM':
                rotateY = pi
                z_pos = -board_thickness
            placmnt = Base.Placement(
                Base.Vector(place_item[3], place_item[4], z_pos),
                toQuaternion(rotateY, place_item[5] * pi / 180, 0))
            step_model.Placement = placmnt
            grp.addObject(step_model)
        else:
            if IDF_diag == 1:
                model_file.writelines(
                    str(place_item[0]) + " " + str(place_item[2]) + "\n")
                model_file.close()
Beispiel #23
0
 def IsActive(self):
     import Base
     return Base.ifReady4Drawing('DDA')
Beispiel #24
0
 def accept(self):
     self.__storePanelData2Database()
     import Base
     Base.delaycommand(self.__calculateDF)
BOR = 3 # outer radius
BCR = 2.7 # core radius

BIRSm = 3.5 # radius of small CI
BIHSm = 0.5 # height of small CI
BIRLg = 4 # radius of large CI
BIHLg = float(BIRLg*BIHSm)/BIRSm # height of large CI (proportional)
BIS = 0.5 # seperation between CIs

BIHPack = BIHSm+BIHLg+2*BIS #pack length
BIno = int(BCL//BIHPack) # number of packs fitted into core length
BIrem = BCL % BIHPack # remainder length


Btap = Part.makeCylinder(BOR,BTL)
Bcore = Part.makeCylinder(BCR,BCL,Base.Vector(0,0,BTL))
Bhead = Part.makeCylinder(BOR,BHL,Base.Vector(0,0,BTL+BCL))
midBushSHP = Btap.fuse(Bcore).fuse(Bhead)
leftBushSHP = Btap.fuse(Bcore).fuse(Bhead)
rightBushSHP = Btap.fuse(Bcore).fuse(Bhead)

BIinit = BTL+float(BIrem)/2+BIS # initial height for first cone
for i in range(0,BIno):
	Bconez = BIinit + i*BIHPack	
	BconeLg = Part.makeCone(BIRLg,BCR,BIHLg,Base.Vector(0,0,Bconez))
	BconeSm = Part.makeCone(BIRSm,BCR,BIHSm,Base.Vector(0,0,Bconez+BIHLg+BIS))
	midBushSHP = midBushSHP.fuse(BconeLg).fuse(BconeSm)
	leftBushSHP = leftBushSHP.fuse(BconeLg).fuse(BconeSm)
	rightBushSHP = rightBushSHP.fuse(BconeLg).fuse(BconeSm)

Beispiel #26
0
    def showGraph4File(self):
        import DDADisplay
        DDADisplay.clearDocument()

        from DDADatabase import dc_inputDatabase
        import Base
        
        Base.DDAObserver.lock = True

        from DDADatabase import dl_database as database
        boundaryNodes = database.boundaryNodes
        if len(boundaryNodes)>0:
            Base.addPolyLine2Document('BoundaryLine', ifStore2Database=False)
#            self.drawLines(boundaryNodes, 'BoundaryLine')
            print 'draw boundary lines : ' , len(boundaryNodes)
        
        nums = 0        
        lines = dc_inputDatabase.jointLines
        # the viewProvider will take data from dc_inputDatabase.jointLines 
#        self.drawLines( [lines[0].startPoint , lines[0].endPoint] ,'JointLine' , 0)
        if len(lines)>0:
            Base.addLines2Document('JointLine') 
            print 'draw joints : ' , len(lines)
        
        points = dc_inputDatabase.fixedPoints
#        self.drawCircles(points, Base.__radius4Points__, 'FixedPoint')
        if len(points)>0:
            Base.addCircles2Document('FixedPoint')
            print 'draw fixed points : ' , len(points)

        points = dc_inputDatabase.measuredPoints
#        self.drawCircles(points , Base.__radius4Points__, 'MeasuredPoint')
        if len(points)>0:
            Base.addCircles2Document('MeasuredPoint')
            print 'draw measured points : ' , len(points)

        points = dc_inputDatabase.loadingPoints
#        self.drawCircles(points , Base.__radius4Points__, 'LoadingPoint')
        if len(points)>0:
            Base.addCircles2Document('LoadingPoint')
        print 'draw loading points : ' , len(points)

        points = dc_inputDatabase.holePoints
#        self.drawCircles(points , Base.__radius4Points__, 'HolePoint')
        if len(points)>0:
            Base.addCircles2Document('HolePoint')
        print 'draw hole points : ' , len(points)
                                
        Base.recomputeDocument()
        
        Base.DDAObserver.lock = False
Beispiel #27
0
def makeBoreHole():
    # create a document if needed
    if App.ActiveDocument == None:
        App.newDocument("Solid")

    Group = App.ActiveDocument.addObject("App::DocumentObjectGroup", "Group")
    Group.Label = "Bore hole"

    V1 = Base.Vector(0, 10, 0)
    V2 = Base.Vector(30, 10, 0)
    V3 = Base.Vector(30, -10, 0)
    V4 = Base.Vector(0, -10, 0)
    VC1 = Base.Vector(-10, 0, 0)
    C1 = Part.Arc(V1, VC1, V4)
    # and the second one
    VC2 = Base.Vector(40, 0, 0)
    C2 = Part.Arc(V2, VC2, V3)
    L1 = Part.Line(V1, V2)
    # and the second one
    L2 = Part.Line(V4, V3)
    S1 = Part.Shape([C1, C2, L1, L2])

    W = Part.Wire(S1.Edges)
    F = Part.Face(W)
    P = F.extrude(Base.Vector(0, 0, 5))

    # add objects with the shape
    Wire = Group.newObject("Part::Feature", "Wire")
    Wire.Shape = W
    Face = Group.newObject("Part::Feature", "Face")
    Face.Shape = F
    Prism = Group.newObject("Part::Feature", "Extrude")
    Prism.Shape = P

    c = Part.Circle(Base.Vector(0, 0, -1), Base.Vector(0, 0, 1), 2.0)
    w = Part.Wire(c.toShape())
    f = Part.Face(w)
    p = f.extrude(Base.Vector(0, 0, 7))
    P = P.cut(p)

    # add first borer
    Bore1 = Group.newObject("Part::Feature", "Borer_1")
    Bore1.Shape = p
    Hole1 = Group.newObject("Part::Feature", "Borer_Hole1")
    Hole1.Shape = P

    c = Part.Circle(Base.Vector(0, -11, 2.5), Base.Vector(0, 1, 0), 1.0)
    w = Part.Wire(c.toShape())
    f = Part.Face(w)
    p = f.extrude(Base.Vector(0, 22, 0))
    P = P.cut(p)

    # add second borer
    Bore2 = Group.newObject("Part::Feature", "Borer_2")
    Bore2.Shape = p
    Hole2 = Group.newObject("Part::Feature", "Borer_Hole2")
    Hole2.Shape = P

    App.ActiveDocument.recompute()

    # hide all objets except of the final one
    Gui.ActiveDocument.getObject(Wire.Name).hide()
    Gui.ActiveDocument.getObject(Face.Name).hide()
    Gui.ActiveDocument.getObject(Prism.Name).hide()
    Gui.ActiveDocument.getObject(Bore1.Name).hide()
    Gui.ActiveDocument.getObject(Hole1.Name).hide()
    Gui.ActiveDocument.getObject(Bore2.Name).hide()
    Gui.ActiveDocument.ActiveView.fitAll()
Beispiel #28
0
    def showGraph4File(self):
        from DDADatabase import df_inputDatabase
        frame = df_inputDatabase

        from Base import DDAObserver
        DDAObserver.lock = True
        
        from interfaceTools import blocksRects , rectSelection
        
        from Base import __radius4Points__

        import Base
        Base.refreshPolygons()
        Base.refreshBlockBoundaryLines()
        nums = 0
        blocksRects.resetXYRange()
        blocks = frame.blocks
        for block in blocks:
            blocksRects.handleBlockXYRange(block.getPoints())
        print 'block number :  ' , len(blocks)
        rectSelection.setData(blocksRects.blockRects)

        points = frame.fixedPoints
#        self.drawCircles(points, Base.__radius4Points__, 'FixedPoint')
        if len(points)>0:
            Base.addCircles2Document('FixedPoint')
            print 'draw fixed points : ' , len(points)

        points = frame.measuredPoints
#        self.drawCircles(points , Base.__radius4Points__, 'MeasuredPoint')
        if len(points)>0:
            Base.addCircles2Document('MeasuredPoint')
            print 'draw measured points : ' , len(points)

        points = frame.loadingPoints
#        self.drawCircles(points , Base.__radius4Points__, 'LoadingPoint')
        if len(points)>0:
            Base.addCircles2Document('LoadingPoint')
        print 'draw loading points : ' , len(points)

        points = frame.holePoints
#        self.drawCircles(points , Base.__radius4Points__, 'HolePoint')
        if len(points)>0:
            Base.addCircles2Document('HolePoint')
        print 'draw hole points : ' , len(points)

        
        DDAObserver.lock = False
 def _buildLid(self):
     oX = self.origin.x
     oY = self.origin.y
     oZ = self.origin.z
     #print("*** OrignalLid._buildLid: oX = %f, oY = %f, oZ = %f"%(oX,oY,oZ),\
     #        file=sys.__stderr__)
     self._lid = Part.makePlane(self.OutsideWidth,self.OutsideLength,\
                               self.origin)\
                 .extrude(Base.Vector(0,0,\
                                      self.TotalLidHeight-self.LidHeight))
     innerX = oX + ((self.OutsideWidth - self._insideWidth) / 2.0)
     innerY = oY + ((self.OutsideLength - self._insideLength) / 2.0)
     innerZ = oZ + self.LidThickness
     #print("*** OrignalLid._buildLid: innerX = %f, innerY = %f, innerZ = %f"%(innerX,innerY,innerZ),\
     #        file=sys.__stderr__)
     self.fuselids(Part.makePlane(self._insideWidth,self._insideLength,\
                                 Base.Vector(innerX,innerY,innerZ))\
                  .extrude(Base.Vector(0,0,\
                                       self.TotalLidHeight-self.LidThickness)) )
     innerX = oX + ((self.OutsideWidth - self.InsideBoxWidth) / 2.0)
     innerY = oY + ((self.OutsideLength - self.InsideBoxLength) / 2.0)
     innerZ = oZ + self.TotalLidHeight - self.LidHeight
     #print("*** OrignalLid._buildLid: innerX = %f, innerY = %f, innerZ = %f"%(innerX,innerY,innerZ),\
     #        file=sys.__stderr__)
     self.cutlids(Part.makePlane(self.InsideBoxWidth,\
                                 self.InsideBoxLength,\
                               Base.Vector(innerX,innerY,innerZ))\
                  .extrude(Base.Vector(0,0,self.LidHeight)))
     h1X = oX + ((self.OutsideWidth - self._holeCenterWidth) / 2.0)
     h1Y = oY + ((self.OutsideLength - self._holeCenterLength) / 2.0)
     h1 = Part.Face(Part.Wire(Part.makeCircle(self._holeDiameter/2.0,\
                         Base.Vector(h1X,h1Y,oZ))))\
                         .extrude(Base.Vector(0,0,self.TotalLidHeight))
     self.cutlids(h1)
     h2X = h1X + self._holeCenterWidth
     h2Y = h1Y
     h2 = Part.Face(Part.Wire(Part.makeCircle(self._holeDiameter/2.0,\
                         Base.Vector(h2X,h2Y,oZ))))\
                         .extrude(Base.Vector(0,0,self.TotalLidHeight))
     self.cutlids(h2)
     h3X = h2X
     h3Y = h2Y + self._holeCenterLength
     h3 = Part.Face(Part.Wire(Part.makeCircle(self._holeDiameter/2.0,\
                         Base.Vector(h3X,h3Y,oZ))))\
                         .extrude(Base.Vector(0,0,self.TotalLidHeight))
     self.cutlids(h3)
     h4X = h3X - self._holeCenterWidth
     h4Y = h3Y
     h4 = Part.Face(Part.Wire(Part.makeCircle(self._holeDiameter/2.0,\
                         Base.Vector(h4X,h4Y,oZ))))\
                         .extrude(Base.Vector(0,0,self.TotalLidHeight))
     self.cutlids(h4)
Beispiel #30
0
    def drawLine( self , pts , shapeType , materialIndex = 0):
#        v1 = self.getPointInBaseVectorType(p1)
#        v2 = self.getPointInBaseVectorType(p2)
#            
        if shapeType == 'BoundaryLine':
            Base.addLines2Document( pts , closed=False, face=False, fname = 'BoundaryLine')
        elif shapeType == 'JointLine':
            Base.addLines2Document( pts , closed=False, face=False, fname = 'JointLine', materialIndex = materialIndex)
        elif shapeType == 'TunnelLine':
            Base.addLines2Document( pts , closed=False, face=False, fname = 'TunnelLine', materialIndex = materialIndex)
        elif shapeType == 'AdditionalLine':
            Base.addLines2Document( pts , closed=False, face=False, fname = 'AdditionalLine')
        elif shapeType == 'MaterialLine':
            Base.addLines2Document( pts , closed=False, face=False, fname = 'MaterialLine')
        elif shapeType == 'BoltElemnet':   
            Base.addLines2Document( pts , closed=False, face=False, fname = 'BoltElemnet')
        elif shapeType == 'Frame':   # frame 其实没有用
            Base.addLines2Document( pts , closed=False, face=False, fname = 'Frame')
        else :
            print 'Unkown Type : ' , shapeType
Beispiel #31
0
        App.closeDocument(doc)
App.newDocument(name)
App.setActiveDocument(name)
App.ActiveDocument = App.getDocument(name)
Gui.ActiveDocument = Gui.getDocument(name)

# The major base
base = Part.makeBox(base_length, base_width, base_depth)

# The alcove cut to fit the PCB
alcove = Part.makeBox(alcove_length, alcove_width, alcove_depth)

x = alcove_offset
y = (base_width - alcove_width) / 2
z = (base_depth - alcove_depth)
alcove.translate(Base.Vector(x, y, z))

# Antenna cut
ant = Part.makeBox(alcove_offset + ant_length, ant_width, base_depth)
x = 0
y = (base_width - alcove_width) / 2
z = 0
ant.translate(Base.Vector(x, y, z))

# LDO cut
ldo = Part.makeBox(ldo_length, ldo_width, base_depth)
x = alcove_offset
y = (alcove_width - ldo_width) + ((base_width - alcove_width) / 2)
z = 0
ldo.translate(Base.Vector(x, y, z))
Beispiel #32
0
def numpyVecToFC(nv):
    assert len(nv) == 3
    return Base.Vector(nv[0], nv[1], nv[2])
Beispiel #33
0
def design_frame(span_length, base_length, folder_path, bthick):
    pos = Base.Vector(0, 0, 0)
    support_data = file("./wall_span/supports.csv")
    support_data = csv.reader(support_data)
    for row in support_data:
        sheight = 304.5 * int(row[0])
        sthick = 304.5 * float(row[1])
        swidth = 304.5 * float(row[2])
        hthick = 304.5 * float(row[3])
    hwidth = 2 * hthick
    points = []
    x = (0.5 * span_length) + (0.5 * base_length) - (0.5 * swidth)
    y = (0.5 * sthick)
    z = bthick
    points.append(Base.Vector(x, y, z))
    points.append(Base.Vector(x + swidth, y, z))
    points.append(Base.Vector(x + swidth, -y, z))
    points.append(Base.Vector(x, -y, z))
    locs = []
    y = (0.5 * hthick)
    locs.append(Base.Vector(x, y, z))
    locs.append(Base.Vector(x + hwidth, y, z))
    locs.append(Base.Vector(x + hwidth, -y, z))
    locs.append(Base.Vector(x, -y, z))
    edges = []
    for i in range(0, 3):
        edges.append(Part.makeLine(points[i], points[i + 1]))
    edges.append(Part.makeLine(points[3], points[0]))
    w = Part.Wire(edges)
    f = Part.Face(w)
    P = f.extrude(Base.Vector(0, 0, sheight))
    edges = []
    for i in range(0, 3):
        edges.append(Part.makeLine(locs[i], locs[i + 1]))
    edges.append(Part.makeLine(locs[3], locs[0]))
    c = Part.Wire(edges)
    cf = Part.Face(c)
    cd = cf.extrude(Base.Vector(0, 0, sheight))
    x = (0.5 * span_length) + (0.5 * base_length)
    cd1 = cd.mirror(Base.Vector(x, 0, 0), Base.Vector(1, 0, 0))
    P = P.cut(cd)
    P = P.cut(cd1)
    P1 = P.mirror(Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
    cpd = Part.makeCompound([P1, P])
    cpd.exportStep(folder_path + "/frames.stp")
    return swidth
Beispiel #34
0
def insert(filename,docname=None,preferences=None):

    """imports the contents of an IFC file in the given document"""

    import ifcopenshell
    from ifcopenshell import geom

    # reset global values
    global layers
    global materials
    global objects
    global adds
    global subs
    layers = {}
    materials = {}
    objects = {}
    adds = {}
    subs = {}

    # statistics
    starttime = time.time() # in seconds
    filesize = os.path.getsize(filename) * 0.000001 # in megabytes
    print("Opening",filename+",",round(filesize,2),"Mb")

    # setup ifcopenshell
    if not preferences:
        preferences = importIFC.getPreferences()
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_BREP_DATA,True)
    settings.set(settings.SEW_SHELLS,True)
    settings.set(settings.USE_WORLD_COORDS,True)
    if preferences['SEPARATE_OPENINGS']:
        settings.set(settings.DISABLE_OPENING_SUBTRACTIONS,True)
    if preferences['SPLIT_LAYERS'] and hasattr(settings,"APPLY_LAYERSETS"):
        settings.set(settings.APPLY_LAYERSETS,True)

    # setup document
    if not FreeCAD.ActiveDocument:
        if not docname:
            docname = os.path.splitext(os.path.basename(filename))[0]
        doc = FreeCAD.newDocument(docname)
        doc.Label = docname
        FreeCAD.setActiveDocument(doc.Name)

    # open the file
    ifcfile = ifcopenshell.open(filename)
    progressbar = Base.ProgressIndicator()
    productscount = len(ifcfile.by_type("IfcProduct"))
    progressbar.start("Importing "+str(productscount)+" products...",productscount)
    cores = preferences["MULTICORE"]
    iterator = ifcopenshell.geom.iterator(settings,ifcfile,cores)
    iterator.initialize()
    count = 0

    # process objects
    for item in iterator:
        brep = item.geometry.brep_data
        ifcproduct = ifcfile.by_id(item.guid)
        obj = createProduct(ifcproduct,brep)
        progressbar.next(True)
        writeProgress(count,productscount,starttime)
        count += 1

    # process 2D annotations
    annotations = ifcfile.by_type("IfcAnnotation")
    if annotations:
        print("Processing",str(len(annotations)),"annotations...")
        ifcscale = importIFCHelper.getScaling(ifcfile)
        for annotation in annotations:
            importIFCHelper.createAnnotation(annotation,FreeCAD.ActiveDocument,ifcscale,preferences)

    # post-processing
    processRelationships()
    storeColorDict()

    # finished
    progressbar.stop()
    FreeCAD.ActiveDocument.recompute()
    endtime = round(time.time()-starttime,1)
    fs = round(filesize,1)
    ratio = int(endtime/filesize)
    endtime = "%02d:%02d" % (divmod(endtime, 60))
    writeProgress() # this cleans the line
    print("Finished importing",fs,"Mb in",endtime,"s, or",ratio,"s/Mb")
    return FreeCAD.ActiveDocument
Beispiel #35
0
def design_shield(span_length, span_t, swidth, bheight, folder_path, bthick):
    points = []
    x = 0
    y = 0.5 * span_t
    z = bthick
    points.append(Base.Vector(0, y, z))
    x = (0.5 * span_length) - (swidth + 5)
    points.append(Base.Vector(x, y, z))
    y = y + (3 * span_t)
    points.append(Base.Vector(x, y, z))
    x = x + 5
    points.append(Base.Vector(x, y, z))
    y = y - (3 * span_t)
    points.append(Base.Vector(x, y, z))
    x = x + swidth
    points.append(Base.Vector(x, y, z))
    points.append(Base.Vector(x, -y, z))
    x = x - swidth
    points.append(Base.Vector(x, -y, z))
    y = -(y + (3 * span_t))
    points.append(Base.Vector(x, y, z))
    x = x - 5
    points.append(Base.Vector(x, y, z))
    y = y + (2 * span_t)
    points.append(Base.Vector(x, y, z))
    x = 0
    points.append(Base.Vector(x, y, z))
    edges = []
    for i in range(0, 11):
        edges.append(Part.makeLine(points[i], points[i + 1]))
    edges.append(Part.makeLine(points[11], points[0]))
    w = Part.Wire(edges)
    f = Part.Face(w)
    height = 304.5 * bheight
    P = f.extrude(Base.Vector(0, 0, height))
    P1 = P.mirror(Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
    cpd = Part.makeCompound([P, P1])
    cpd.exportStep(folder_path + "/wall_span.stp")
    screw_dat = file("./seal/bolts/screw_data.csv")
    screw_data = csv.reader(screw_dat)
    for row in screw_data:
        diameter = float(row[0])
        pitch = float(row[1])
        minor_diam = float(row[2])

class LowerBox(ham_1591XXTSBK):
    @property
    def upsidedown(self):
        return True

    @property
    def includelid(self):
        return False

    def __init__(self, name, origin):
        self.name = name
        if not isinstance(origin, Base.Vector):
            raise RuntimeError("origin is not a Vector!")
        self.origin = origin
        self._buildbox()


if __name__ == '__main__':
    if "ham_1591XXTSBK" in App.listDocuments().keys():
        App.closeDocument("ham_1591XXTSBK")
    App.ActiveDocument = App.newDocument("ham_1591XXTSBK")
    doc = App.activeDocument()
    upperbox = UpperBox("upper", Base.Vector(0, 0, 0))
    upperbox.show()
    lowerbox = LowerBox("lower", Base.Vector(0, 0, 0))
    lowerbox.show()
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewIsometric()
Beispiel #37
0
def beamShape(beam):
    '''Computes the 3D representation of the beam, a shape for a CAD file obj.

    beam: beam to represent. [GaussianBeam]

    Returns a shape for a CAD file object.

    '''
    fact = settings.FCFactor
    L = beam.Length if beam.Length > 0. else 1.e6

    #geometrical data of the beam envelope
    theta = np.real(beam.QParam()[2])
    Wx = beam.Wx
    Wy = beam.Wy

    DWx = beam.DWx
    DWy = beam.DWy
    Ux0 = beam.U[0]
    Uy0 = beam.U[1]

    #rotate vectors to find eigendirections of Q:
    Ux = np.cos(theta) * Ux0 + np.sin(theta) * Uy0
    Uy = -np.sin(theta) * Ux0 + np.cos(theta) * Uy0

    #make shape by using points
    Xalpha = (beam.Wl / beam.N) / (np.pi * Wx)
    Xc = np.tan(Xalpha / 2.)
    Yalpha = (beam.Wl / beam.N) / (np.pi * Wy)
    Yc = np.tan(Yalpha / 2.)
    E2 = L * beam.Dir / fact

    XA1 = Base.Vector(tuple(-DWx * Xc * Ux / fact))
    XB1 = Base.Vector(tuple(DWx * Xc * Ux/fact \
                                + (0.01 * Ux if DWx == 0. else 0.)))
    XA2 = Base.Vector(tuple(E2 + (L - DWx) * Xc * Ux / fact))
    XB2 = Base.Vector(tuple(E2 - (L - DWx) * Xc * Ux/fact \
                                +(0.01 * Ux if (L -DWx) == 0. else 0.)))

    YA1 = Base.Vector(tuple(-DWy * Yc * Uy / fact))
    YB1 = Base.Vector(tuple( + DWy * Yc * Uy/fact \
                                + (0.01 * Ux if DWx == 0. else 0.)))
    YA2 = Base.Vector(tuple(E2 + (L - DWy) * Yc * Uy / fact))
    YB2 = Base.Vector(tuple(E2 - (L - DWy) * Yc * Uy/fact \
                                +(0.01 * Ux if (L -DWx) == 0. else 0.)))

    L1 = Part.Line(XA1, XB1).toShape()
    L2 = Part.Line(XB1, XB2).toShape()
    L3 = Part.Line(XB2, XA2).toShape()
    L4 = Part.Line(XA1, XA2).toShape()
    L5 = Part.Line(YA1, YB1).toShape()
    L6 = Part.Line(YB1, YB2).toShape()
    L7 = Part.Line(YA2, YB2).toShape()
    L8 = Part.Line(YA1, YA2).toShape()

    try:
        S1 = Part.Face(Part.Wire([L1, L2, L3, L4]))
    except Part.OCCError:
        S1 = L1.fuse(L2).fuse(L3).fuse(L4)

    try:
        S2 = Part.Face(Part.Wire([L5, L6, L7, L8]))
    except Part.OCCError:
        S2 = L5.fuse(L6).fuse(L7).fuse(L8)

    try:
        return S1.fuse(S2)
    except Part.OCCError:
        return Part.makeLine(Base.Vector(0., 0., 0.),
                             Base.Vector(tuple(L * beam.Dir / fact)))
scale = 10.0  # 1unit = 10mm
offset = 0.01  # Some things need to be offset imperceptibly from their true position to keep freecad happy

######## Axes ##########
axes = doc.addObject("App::DocumentObjectGroup", "Axes")

y_end = 1.2 * scale
x_start = -0.3 * scale
x_end = 2.2 * scale
axis_radius = 0.05

#x-axis
cyl = doc.addObject("Part::Cylinder", "x-axis")
cyl.Radius = axis_radius
cyl.Height = x_end - x_start
cyl.Placement = Base.Placement(Base.Vector(x_start, 0.00, 0.00),
                               App.Rotation(App.Vector(0, 1, 0), 90))
cyl.ViewObject.DiffuseColor = [(0.0, 0.0, 0.0)]
axes.addObject(cyl)

txt = Draft.makeText('x', point=FreeCAD.Vector(x_end + 0.5, -0.5, 0))
txt.ViewObject.FontSize = 2
axes.addObject(txt)

#y-axis
cyl = doc.addObject("Part::Cylinder", "y-axis")
cyl.Radius = axis_radius
cyl.Height = 2 * y_end
cyl.Placement = Base.Placement(Base.Vector(0.00, -y_end, 0.00),
                               App.Rotation(App.Vector(1, 0, 0), -90))
cyl.ViewObject.DiffuseColor = [(0.0, 0.0, 0.0)]
axes.addObject(cyl)
Beispiel #39
0
name = "case_lid"

# Create new document
if len(App.listDocuments()) != 0:
    for doc in App.listDocuments():
        App.setActiveDocument(doc)
        App.closeDocument(doc)
App.newDocument(name)
App.setActiveDocument(name)
App.ActiveDocument = App.getDocument(name)
Gui.ActiveDocument = Gui.getDocument(name)

# The major base
base = Part.makeBox(base_length, base_width, base_depth)

# The alcove cut to fit the PCB
alcove = Part.makeBox(alcove_length, alcove_width, alcove_depth)

x = alcove_length_offset
y = (base_width - alcove_width) / 2
z = 0
alcove.translate(Base.Vector(x, y, z))

# Battery cut
batt = Part.makeCylinder(batt_rad, batt_depth)
batt.translate(Base.Vector(batt_length_offset, batt_width_offset, 0))

Part.show(base)
Part.show(alcove)
Part.show(batt)
Beispiel #40
0
 def make_box(box):
     origin = Base.Vector(box.XMin, box.YMin, box.ZMin)
     return Part.makeBox(box.XLength, box.YLength, box.ZLength, origin)
Beispiel #41
0
def Null():
    n1 = Part.makeBox(1, 1, 1)
    n2 = Part.makeBox(1, 1, 1)
    n2.translate(Base.Vector(10, 10, 10))
    return (n1.common(n2))
Beispiel #42
0
        App.closeDocument(doc)
App.newDocument(name)
App.setActiveDocument(name)
App.ActiveDocument = App.getDocument(name)
Gui.ActiveDocument = Gui.getDocument(name)

# The major base
base = Part.makeBox(base_length, base_width, base_depth)

# The alcove cut to fit the PCB
alcove = Part.makeBox(alcove_length, alcove_width, alcove_depth)

x = alcove_length_offset
y = (base_width - alcove_width) / 2
z = 0
alcove.translate(Base.Vector(x, y, z))

# Battery cut
batt = Part.makeCylinder(batt_rad, batt_depth)
batt.translate(Base.Vector(batt_length_offset, batt_width_offset, 0))

# The alcove cut to fit the PCB
recess = Part.makeBox(recess_length, recess_width, recess_depth)
recess.translate(Base.Vector(recess_length_offset, recess_width_offset, 0))

# The cork cut to queeze the PCB
cork = Part.makeBox(cork_length, cork_width, cork_depth)
cork.translate(Base.Vector(cork_length_offset, cork_width_offset, 0))

Part.show(base)
alcove = alcove.cut(recess)
Beispiel #43
0
 def getMovement(self):
     if not self.Enabled: return None, None
     return self.refPoint, Base.Vector(0, 0, 0)
App.newDocument("Unnamed")
App.setActiveDocument("Unnamed")
App.ActiveDocument = App.getDocument("Unnamed")
Gui.ActiveDocument = Gui.getDocument("Unnamed")

#
#Inner Ring#
B1 = Part.makeCylinder(R1, TH)
B2 = Part.makeCylinder(R2, TH)
IR = B2.cut(B1)
#get edges and apply fillets
Bedges = IR.Edges
IRF = IR.makeFillet(RR, Bedges)
#create groove and show shape
T1 = Part.makeTorus(CBall, RBall)
T1.translate(Base.Vector(0, 0, TH / 2))
InnerRing = IRF.cut(T1)
Part.show(InnerRing)

#
#Outer Ring#
B3 = Part.makeCylinder(R3, TH)
B4 = Part.makeCylinder(R4, TH)
OR = B4.cut(B3)
#get edges and apply fillets
Bedges = OR.Edges
ORF = OR.makeFillet(RR, Bedges)
#create groove and show shape
T2 = Part.makeTorus(CBall, RBall)
T2.translate(Base.Vector(0, 0, TH / 2))
OuterRing = ORF.cut(T2)
Beispiel #45
0
def Process_board_outline(doc, board_outline, drills, board_thickness):
    """Process_board_outline(doc,board_outline,drills,board_thickness)-> number proccesed loops

        adds emn geometry from emn file"""
    vertex_index = -1
    #presume no vertex
    lines = -1  #presume no lines
    out_shape = []
    out_face = []
    for point in board_outline:
        vertex = Base.Vector(point[1], point[2], 0)
        vertex_index += 1
        if vertex_index == 0:
            lines = point[0]
        elif lines == point[0]:
            if point[3] != 0 and point[3] != 360:
                out_shape.append(
                    Part.Arc(prev_vertex,
                             mid_point(prev_vertex, vertex, point[3]), vertex))
                FreeCAD.Console.PrintMessage("mid point " + str(mid_point) +
                                             "\n")
            elif point[3] == 360:
                per_point = Per_point(prev_vertex, vertex)
                out_shape.append(
                    Part.Arc(per_point,
                             mid_point(per_point, vertex, point[3] / 2),
                             vertex))
                out_shape.append(
                    Part.Arc(per_point,
                             mid_point(per_point, vertex, -point[3] / 2),
                             vertex))
            else:
                out_shape.append(Part.LineSegment(prev_vertex, vertex))
        else:
            out_shape = Part.Shape(out_shape)
            out_shape = Part.Wire(out_shape.Edges)
            out_face.append(Part.Face(out_shape))
            out_shape = []
            vertex_index = 0
            lines = point[0]
        prev_vertex = vertex
    if lines != -1:
        out_shape = Part.Shape(out_shape)
        out_shape = Part.Wire(out_shape.Edges)
        out_face.append(Part.Face(out_shape))
        outline = out_face[0]
        FreeCAD.Console.PrintMessage("Added outline\n")
        if len(out_face) > 1:
            for otl_cut in out_face[1:]:
                outline = outline.cut(otl_cut)
                FreeCAD.Console.PrintMessage("Cutting shape inside outline\n")
        for drill in drills:
            FreeCAD.Console.PrintMessage("Cutting hole inside outline\n")
            out_shape = Part.makeCircle(drill[0] / 2,
                                        Base.Vector(drill[1], drill[2], 0))
            out_shape = Part.Wire(out_shape.Edges)
            outline = outline.cut(Part.Face(out_shape))
        doc_outline = doc.addObject("Part::Feature", "Board_outline")
        doc_outline.Shape = outline
        #FreeCADGui.Selection.addSelection(doc_outline)
        #FreeCADGui.runCommand("Draft_Upgrade")
        #outline=FreeCAD.ActiveDocument.getObject("Union").Shape
        #FreeCAD.ActiveDocument.removeObject("Union")
        #doc_outline=doc.addObject("Part::Feature","Board_outline")
        doc_outline.Shape = outline.extrude(Base.Vector(
            0, 0, -board_thickness))
        grp = doc.addObject("App::DocumentObjectGroup", "Board_Geoms")
        grp.addObject(doc_outline)
        doc.Board_outline.ViewObject.ShapeColor = (0.0, 0.5, 0.0, 0.0)
    return lines + 1
Beispiel #46
0
def process_emp(doc, filename, placement, board_thickness):
    """process_emp(doc,filename,placement,board_thickness) -> place components from emn file to board"""
    filename = filename.partition(".emn")[0] + ".emp"
    empfile = pythonopen(filename, "r")
    emp_unit = 1.0  #presume milimeter like emn unit
    emp_version = 2  #presume emn_version 2
    comp_height = 0  #presume 0 part height
    comp_outline = []  #no part outline
    comp_GeometryName = ""  # no geometry name
    comp_PartNumber = ""  # no Part Number
    comp_height = 0  # no Comp Height
    emplines = empfile.readlines()
    empfile.close()
    passed_sections = []
    current_section = ""
    section_counter = 0
    comps = []
    for empline in emplines:
        emprecords = split_records(empline)
        if len(emprecords) == 0: continue
        if len(emprecords[0]) > 4 and emprecords[0][0:4] == ".END":
            passed_sections.append(current_section)
            current_section = ""
            if comp_PartNumber != "":
                if comp_height == 0:
                    comp_height = 0.1
                comps.append((comp_PartNumber, [
                    Process_comp_outline(doc, comp_outline, comp_height),
                    comp_GeometryName
                ]))
                comp_PartNumber = ""
                comp_outline = []
        elif emprecords[0][0] == ".":
            current_section = emprecords[0]
            section_counter = 0
        section_counter += 1
        if current_section == ".HEADER" and section_counter == 2:
            emp_version = int(float(emprecords[1]))
            FreeCAD.Console.PrintMessage("Emp version: " + emprecords[1] +
                                         "\n")
        if (current_section == ".ELECTRICAL"
                or current_section == ".MECHANICAL"
            ) and section_counter == 2 and emprecords[2] == "THOU":
            emp_unit = 0.0254
        if (current_section == ".ELECTRICAL"
                or current_section == ".MECHANICAL"
            ) and section_counter == 2 and emprecords[2] == "MM":
            emp_unit = 1
        if (current_section == ".ELECTRICAL"
                or current_section == ".MECHANICAL") and section_counter == 2:
            comp_outline = []  #no part outline
            comp_GeometryName = emprecords[0]  # geometry name
            comp_PartNumber = emprecords[1]  # Part Number
            comp_height = emp_unit * float(emprecords[3])  # Comp Height
        if (current_section == ".ELECTRICAL"
                or current_section == ".MECHANICAL") and section_counter > 2:
            comp_outline.append([
                float(emprecords[1]) * emp_unit,
                float(emprecords[2]) * emp_unit,
                float(emprecords[3])
            ])  #add point of outline
    FreeCAD.Console.PrintMessage("\n".join(passed_sections) + "\n")
    #Write file with list of footprint
    if IDF_diag == 1:
        empfile = pythonopen(IDF_diag_path + "/footprint.lst", "w")
        for compx in comps:
            empfile.writelines(str(compx[1][1]) + "\n")
        empfile.close()
    #End section of list footprint
    comps = dict(comps)
    grp = doc.addObject("App::DocumentObjectGroup", "EMP Models")
    for place_item in placement:
        if comps.has_key(place_item[1]):
            doc_comp = doc.addObject("Part::Feature", place_item[0])
            FreeCAD.Console.PrintMessage("Adding EMP model " +
                                         str(place_item[0]) + "\n")
            doc_comp.Shape = comps[place_item[1]][0]
            doc_comp.ViewObject.DisplayMode = EmpDisplayMode
            z_pos = 0
            rotateY = 0
            if place_item[6] == 'BOTTOM':
                rotateY = pi
                z_pos = -board_thickness
            placmnt = Base.Placement(
                Base.Vector(place_item[3], place_item[4], z_pos),
                toQuaternion(rotateY, place_item[5] * pi / 180, 0))
            doc_comp.Placement = placmnt
            grp.addObject(doc_comp)
    return 1