Beispiel #1
0
def machinebuilder(text, size, height):
    '''
[doc]
-title-
Text Generator
-description-
Create text in 3D
[inputs]
str(text)
int(size)
int(height)
    '''

    #-- Generate text
    doc = FreeCAD.newDocument("TextGenerator")

    ss=Draft.makeShapeString(String=text,FontFile="/usr/share/fonts/truetype/droid/DroidSans.ttf",Size=size,Tracking=0)
    #ss=Draft.extrude(ss,FreeCAD.Base.Vector(0,0,10))

    obj = doc.addObject("Part::Extrusion","TextGenerator")
    obj.Base = ss
    obj.Dir = (0,0,height)

    doc.recompute()

    #-- Export the file
    name = text+"-"+str(size)+".stl"
    Mesh.export([obj], './%s' % name)

    return name
    def testRayPick(self):
        if not FreeCAD.GuiUp:
            return
        self.planarMesh.append([-16.097176, -29.891157, 15.987688])
        self.planarMesh.append([-16.176304, -29.859991, 15.947966])
        self.planarMesh.append([-16.071451, -29.900553, 15.912505])
        self.planarMesh.append([-16.092241, -29.893408, 16.020439])
        self.planarMesh.append([-16.007210, -29.926180, 15.967641])
        self.planarMesh.append([-16.064457, -29.904951, 16.090832])
        planarMeshObject = Mesh.Mesh(self.planarMesh)

        from pivy import coin
        import FreeCADGui

        Mesh.show(planarMeshObject)
        view = FreeCADGui.ActiveDocument.ActiveView.getViewer()
        rp = coin.SoRayPickAction(view.getSoRenderManager().getViewportRegion())
        rp.setRay(coin.SbVec3f(-16.05, 16.0, 16.0), coin.SbVec3f(0, -1, 0))
        rp.apply(view.getSoRenderManager().getSceneGraph())
        pp = rp.getPickedPoint()
        self.failUnless(pp != None)
        det = pp.getDetail()
        self.failUnless(det.getTypeId() == coin.SoFaceDetail.getClassTypeId())
        det = coin.cast(det, str(det.getTypeId().getName()))
        self.failUnless(det.getFaceIndex() == 1)
Beispiel #3
0
def makeMengerSponge(level=3,x0=0,y0=0,z0=0):
    mesh=Sierpinski(level,x0,y0,z0)
    mesh.removeDuplicatedPoints()
    mesh.removeFacets(mesh.getInternalFacets())
    mesh.rebuildNeighbourHood()
    print("Mesh is solid: %s" % (mesh.isSolid()))
    Mesh.show(mesh)
Beispiel #4
0
def process_mesh_file(fname,ext):
    import Mesh,Part
    fullname = fname+'.'+ext
    filename = os.path.join(pathName,fullname)
    objname = os.path.split(fname)[1]
    mesh1 = doc.getObject(objname) #reuse imported object
    if not mesh1:
        Mesh.insert(filename)
        mesh1=doc.getObject(objname)
    if mesh1 is not None:
        if gui:
            mesh1.ViewObject.hide()
        sh=Part.Shape()
        sh.makeShapeFromMesh(mesh1.Mesh.Topology,0.1)
        solid = Part.Solid(sh)
        obj=doc.addObject('Part::Feature',"Mesh")
        #ImportObject(obj,mesh1) #This object is not mutable from the GUI
        #ViewProviderTree(obj.ViewObject)
        solid=solid.removeSplitter()
        if solid.Volume < 0:
            #sh.reverse()
            #sh = sh.copy()
            solid.complement()
        obj.Shape=solid#.removeSplitter()
    else: #mesh1 is None
        FreeCAD.Console.PrintError('Mesh not imported %s.%s %s\n' % \
                (objname,ext,filename))
        import Part
        obj=doc.addObject('Part::Feature',"FailedMeshImport")
        obj.Shape=Part.Compound([])
    return(obj)
Beispiel #5
0
def main():
    
    start = time.time()

    # set default values
    tol = 1.e-8
    cell_size    = 10.0
    solve_method = 'NEM4'
    iterations = 100

    # create mesh
    mesh = Mesh([cell_size,cell_size], [cell_size])
    
    # create fuel
    fuel = Material(2, 'fuel')
    fuel.setSigmaA([0.005, 0.10])
    fuel.setD([1.5, 0.40])
    fuel.setNuSigmaF([0.005, 0.15])
    fuel.setChi([1.0, 0.0])
    fuel.setSigmaS(np.array([[0.0, 0.02],[0.0, 0.0]]))
    
    # create fuel
    moderator = Material(2, 'moderator')
    moderator.setSigmaA([0.0, 0.01])
    moderator.setD([1.5, 0.20])
    moderator.setSigmaS(np.array([[0.0, 0.025],[0.0, 0.0]]))
    
    if solve_method == 'NEM4':
        order = 4
    else:
        order = 2
  
    # add materials to cells
    mesh.cells[0].setMaterial(fuel, order)
    mesh.cells[1].setMaterial(moderator, order)
#     mesh = mesh.refineMesh(.1)
    mesh.makeSurfaces()
    
    # plot the mesh
    pttr.plotMesh(mesh)
    
    # create solver
    solver = Solver(mesh, solve_method)   

    # solve the matrix problem to get flux profile and keff
    solver.solve(tol, iterations)
         
    # plot the flux    
    pttr.plotFlux(solver)
    pttr.plotCellFlux(solver)
    pttr.plotCurrent(solver)

    stop = time.time()
    
    print 'Ran time ' + str(stop-start)[0:5] + ' seconds'

    print '----------------------------------------------------------------------'
Beispiel #6
0
 def execute(self):
     planarMesh = []
     for i in self.polygons:
         planarMesh.append(self.points[i[0]])
         planarMesh.append(self.points[i[2]])
         planarMesh.append(self.points[i[1]])
         planarMesh.append(self.points[i[0]])
         planarMesh.append(self.points[i[3]])
         planarMesh.append(self.points[i[2]])
     Mesh.show(Mesh.Mesh(planarMesh))
Beispiel #7
0
def makeMengerSponge_mt(level=3,x0=0,y0=0,z0=0):
    """
    Is much slower than makeMengerSponge!!! :(
    """
    if level == 0:
        mesh=Sierpinski(level,x0,y0,z0)
        Mesh.show(mesh)
        return

    boxnums = pow(3,level)
    thirds = boxnums / 3
    twothirds = thirds * 2
    
    rangerx = [ x0, x0 + thirds, x0 + twothirds ]
    rangery = [ y0, y0 + thirds, y0 + twothirds ]
    rangerz = [ z0, z0 + thirds, z0 + twothirds ]
    block = 1
    skip=[5,11,13,14,15,17,23]

    # collect the arguments for the algorithm in a list
    args=[]
    for i in rangerx:
        for j in rangery:
            for k in rangerz:
                if block not in skip:
                    args.append((level-1,i,j,k))
                block+=1

    numJobs = 4
    threads=[]
    while numJobs > 0:
        size = len(args)
        count = size / numJobs
        numJobs-=1
        thr=MengerThread(args[:count])
        threads.append(thr)
        args=args[count:]

    print("Number of threads: %i" % (len(threads)))
    for thr in threads:
        thr.start()
    for thr in threads:
        thr.join()

    mesh=Mesh.Mesh()
    for thr in threads:
        mesh.addMesh(thr.mesh)
        del thr.mesh
        
    print(mesh)
    mesh.removeDuplicatedPoints()
    mesh.removeFacets(mesh.getInternalFacets())
    mesh.rebuildNeighbourHood()
    print("Mesh is solid: %s" % (mesh.isSolid()))
    Mesh.show(mesh)
Beispiel #8
0
    def Activated(self):
        pol=np.loadtxt(FreeCAD.getHomePath()+'Mod/glider/examples/p.dat', dtype=int)
        nod=np.loadtxt(FreeCAD.getHomePath()+'Mod/glider/examples/n.dat', dtype=float)
        planarMesh = []
        for i in pol:
            planarMesh.append(nod[i[0]])
            planarMesh.append(nod[i[1]])
            planarMesh.append(nod[i[2]])
            planarMesh.append(nod[i[0]])
            planarMesh.append(nod[i[2]])
            planarMesh.append(nod[i[3]])

        planarMeshObject = Mesh.Mesh(planarMesh)
        Mesh.show(planarMeshObject)
Beispiel #9
0
def commonMesh(mesh,box): 

	t=Mesh.Mesh()
	Mesh.show(t)
	m_out=App.ActiveDocument.ActiveObject
	App.ActiveDocument.ActiveObject.ViewObject.Lighting="Two side"
	m_out.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
	

	[pts,tris]=mesh.Mesh.Topology

	filter=np.array([0]*len(pts))

	n=1
	for i,p in enumerate(pts):
		if box.Shape.BoundBox.isInside(p):
			filter[i]=n
			if i % 1000 == 0:
				FreeCAD.Console.PrintMessage(" ** " + str(i))

				tris2=[]
				for t in tris:
					(a,b,c)=t
					if filter[a] and filter[b] and filter[c]:
						tris2.append((filter[a]-1,filter[b]-1,filter[c]-1))

				pts2=[]
				for i,p in enumerate(pts):
					if filter[i]:
						pts2.append(pts[i])
				m_out.Mesh=Mesh.Mesh((pts2,tris2))
				m_out.ViewObject.DisplayMode = u"Flat Lines"
				

				Gui.updateGui()
			n += 1

	tris2=[]
	for t in tris:
		(a,b,c)=t
		if filter[a] and filter[b] and filter[c]:
			tris2.append((filter[a]-1,filter[b]-1,filter[c]-1))

	pts2=[]
	for i,p in enumerate(pts):
		if filter[i]:
			pts2.append(pts[i])

	m_out.Mesh=Mesh.Mesh((pts2,tris2))
Beispiel #10
0
def _createEllipsoid(proxy, radius, colour, moiScale, withMesh):
    """
    Private function.
    Use createEllipsoid() or createArticulatedEllipsoid() instead.
    """
    # Mesh and cdps will be set manually
    proxy.meshes = None
    proxy.cdps = None

    # Compute box moi
    moi = [0, 0, 0]
    for i in range(3):
        j = (i + 1) % 3
        k = (i + 2) % 3
        moi[i] = proxy.mass * (radius[j] * radius[j] + radius[k] * radius[k]) / 5.0
    proxy.moi = PyUtils.toVector3d(moi) * moiScale

    ellipsoid = proxy.createAndFillObject()

    cdp = Physics.SphereCDP()
    cdp.setCenter(Point3d(0, 0, 0))
    cdp.setRadius(min(radius))

    ellipsoid.addCollisionDetectionPrimitive(cdp)

    if withMesh:
        mesh = Mesh.createEllipsoid((0, 0, 0), radius, colour)
        ellipsoid.addMesh(mesh)

    return ellipsoid
Beispiel #11
0
	def testPrimitiveCount(self):
		if not FreeCAD.GuiUp:
			return
		self.planarMesh.append( [-16.097176,-29.891157,15.987688] ) 
		self.planarMesh.append( [-16.176304,-29.859991,15.947966] )
		self.planarMesh.append( [-16.071451,-29.900553,15.912505] )
		self.planarMesh.append( [-16.092241,-29.893408,16.020439] )
		self.planarMesh.append( [-16.007210,-29.926180,15.967641] )
		self.planarMesh.append( [-16.064457,-29.904951,16.090832] )
		planarMeshObject = Mesh.Mesh(self.planarMesh)

		from pivy import coin; import FreeCADGui
		Mesh.show(planarMeshObject)
		view=FreeCADGui.ActiveDocument.ActiveView
		pc=coin.SoGetPrimitiveCountAction()
		pc.apply(view.getSceneGraph())
		self.failUnless(pc.getTriangleCount() == 2)
Beispiel #12
0
def machinebuilder(diameter, height, file_path):
  
  #-- Get the freecad document
  document = os.path.abspath("cylinder.fcstd")
  doc = FreeCAD.openDocument(document)
  
  #-- Get the Cylinder object from the document
  cyl = doc.getObjectsByLabel("mycylinder")[0]
  
  #-- Set the cylinder's parameters
  if cyl:
      cyl.Radius = diameter / 2.0
      cyl.Height = height
      doc.recompute()
      
      #-- Export the file
      Mesh.export([cyl], file_path)
 def addelement(self):
     scadstr=unicode(self.form.textEdit.toPlainText())
     asmesh=self.form.checkboxmesh.checkState()
     import OpenSCADUtils, os
     extension= 'stl' if asmesh else 'csg'
     tmpfilename=OpenSCADUtils.callopenscadstring(scadstr,extension)
     if tmpfilename:
         doc=FreeCAD.activeDocument() or FreeCAD.newDocument()
         if asmesh:
             import Mesh
             Mesh.insert(tmpfilename,doc.Name)
         else:
             import importCSG
             importCSG.insert(tmpfilename,doc.Name)
         os.unlink(tmpfilename)
     else:
         FreeCAD.Console.PrintError(unicode(translate('OpenSCAD','Running OpenSCAD failed'))+u'\n')
Beispiel #14
0
def makeMesh():
	FreeCAD.newDocument()
	import Mesh

	a=FreeCAD.ActiveDocument.addObject("Mesh::FeaturePython","Mesh")
	a.Mesh=Mesh.createSphere(5.0)
	MeshFeature(a)
	ViewProviderMesh(a.ViewObject)
Beispiel #15
0
 def testLoadMesh(self):
     mesh=Mesh.createSphere(10.0,100) # a fine sphere
     name=tempfile.gettempdir() + os.sep + "mesh.stl"
     mesh.write(name)
     FreeCAD.Console.PrintMessage("Write mesh to %s\n"%(name))
     #lock=thread.allocate_lock()
     for i in range(2):
         thread.start_new(loadFile,(name,))
     time.sleep(1)
Beispiel #16
0
    def saveAndClose(self, name, saveSTL):
        # Save the FCStd file
        if os.path.isfile(self.partsDir + name + ".FCStd"):
            os.remove(self.partsDir + name + ".FCStd")
        App.getDocument(name).saveAs(self.partsDir + name + ".FCStd")

        if saveSTL:

            # Export an STL
            if os.path.isfile(self.stlDir + name + ".stl"):
                os.remove(self.stlDir + name + ".stl")
            __objs__ = []
            __objs__.append(App.getDocument(name).Objects[-1])
            Mesh.export(__objs__, self.stlDir + name + ".stl")
            del __objs__

        # close document
        App.closeDocument(name)
def saveAndClose(name, saveSTL):
    # Make dateString and add it to the directory string
    date = datetime.date.today().strftime("%m_%d_%Y")

    # make the printer's directory if it doesn't exist
    printerDir = gv.printerDir + "Printer_" + date + "/"
    if not os.path.exists(printerDir):
        try:
            os.makedirs(printerDir)
        except OSError as e:
            import traceback
            critical("Failure to save files, check your configuration file.",
                     'Error making "printerDir" in saveAndClose: ' + str(e) + '\n' + traceback.format_exc(limit=1),
                     gv.level, os.path.basename(__file__))
            raise StandardError

    # make the Parts directory if it doesn't exist
    partsDir = printerDir + "Parts/"
    if not os.path.exists(partsDir):
        os.makedirs(partsDir)

    # Save the FCStd file
    if os.path.isfile(partsDir + name + ".FCStd"):
        os.remove(partsDir + name + ".FCStd")
    App.getDocument(name).saveAs(partsDir + name + ".FCStd")

    if saveSTL:
        # make the STLs directory if it doesn't exist
        stlDir = printerDir + "STL_Files/"
        if not os.path.exists(stlDir):
            os.makedirs(stlDir)

        # Export an STL
        if os.path.isfile(stlDir + name + ".stl"):
            os.remove(stlDir + name + ".stl")
        __objs__ = []
        __objs__.append(App.getDocument(name).Objects[-1])
        import Mesh
        Mesh.export(__objs__, stlDir + name + ".stl")
        del __objs__

    # close document
    App.closeDocument(name)
Beispiel #18
0
 def export(self, p, result, label, data_hash, config):
     # export the plate to different file formats
     log.info("Exporting %s layer for %s" % (label, data_hash))
     # draw the part so we can export it
     Part.show(p.val().wrapped)
     doc = FreeCAD.ActiveDocument
     # export the drawing into different formats
     pwd_len = len(config['app']['pwd']) # the absolute part of the working directory (aka - outside the web space)
     result['exports'][label] = []
     if 'js' in result['formats']:
         with open("%s/%s_%s.js" % (config['app']['export'], label, data_hash), "w") as f:
             cadquery.exporters.exportShape(p, 'TJS', f)
             result['exports'][label].append({'name':'js', 'url':'%s/%s_%s.js' % (config['app']['export'][pwd_len:], label, data_hash)})
             log.info("Exported 'JS'")
     if 'brp' in result['formats']:
         Part.export(doc.Objects, "%s/%s_%s.brp" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'brp', 'url':'%s/%s_%s.brp' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'BRP'")
     if 'stp' in result['formats']:
         Part.export(doc.Objects, "%s/%s_%s.stp" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'stp', 'url':'%s/%s_%s.stp' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'STP'")
     if 'stl' in result['formats']:
         Mesh.export(doc.Objects, "%s/%s_%s.stl" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'stl', 'url':'%s/%s_%s.stl' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'STL'")
     if 'dxf' in result['formats']:
         importDXF.export(doc.Objects, "%s/%s_%s.dxf" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'dxf', 'url':'%s/%s_%s.dxf' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'DXF'")
     if 'svg' in result['formats']:
         importSVG.export(doc.Objects, "%s/%s_%s.svg" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'svg', 'url':'%s/%s_%s.svg' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'SVG'")
     if 'json' in result['formats'] and label == SWITCH_LAYER:
         with open("%s/%s_%s.json" % (config['app']['export'], label, data_hash), 'w') as json_file:
             json_file.write(repr(self))
         result['exports'][label].append({'name':'json', 'url':'%s/%s_%s.json' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'JSON'")
     # remove all the documents from the view before we move on
     for o in doc.Objects:
         doc.removeObject(o.Label)
Beispiel #19
0
def _createCylinder(proxy, axis, basePos, tipPos, radius, colour, moiScale, withMesh):
    """
    Private function.
    Use createCylinder() or createArticulatedCylinder() instead.
    """
    if axis != 0 and axis != 1 and axis != 2:
        raise ValueError("Axis must be 0 for x, 1 for y or 2 for z.")

    # Mesh and cdps will be set manually
    proxy.meshes = None
    proxy.cdps = None

    # Compute box moi
    moi = [0, 0, 0]
    height = math.fabs(tipPos - basePos)
    for i in range(3):
        if i == axis:
            moi[i] = proxy.mass * radius * radius / 2.0
        else:
            moi[i] = proxy.mass * (3 * radius * radius + height * height) / 12.0
        ### HACK!
        moi[i] = max(moi[i], 0.01)
    proxy.moi = PyUtils.toVector3d(moi) * moiScale

    cylinder = proxy.createAndFillObject()

    basePoint = [0, 0, 0]
    tipPoint = [0, 0, 0]
    basePoint[axis] = basePos
    tipPoint[axis] = tipPos
    basePoint3d = PyUtils.toPoint3d(basePoint)
    tipPoint3d = PyUtils.toPoint3d(tipPoint)
    baseToTipVector3d = Vector3d(basePoint3d, tipPoint3d)
    if baseToTipVector3d.isZeroVector():
        raise ValueError("Invalid points for cylinder: base and tip are equal!")
    baseToTipUnitVector3d = baseToTipVector3d.unit()

    if height <= radius * 2.0:
        cdp = Physics.SphereCDP()
        cdp.setCenter(basePoint3d + baseToTipVector3d * 0.5)
        cdp.setRadius(height / 2.0)
    else:
        cdp = Physics.CapsuleCDP()
        cdp.setPoint1(basePoint3d + baseToTipUnitVector3d * radius)
        cdp.setPoint2(tipPoint3d + baseToTipUnitVector3d * -radius)
        cdp.setRadius(radius)

    cylinder.addCollisionDetectionPrimitive(cdp)

    if withMesh:
        mesh = Mesh.createCylinder(basePoint, tipPoint, radius, colour)
        cylinder.addMesh(mesh)

    return cylinder
    def addelement(self):
        scadstr=unicode(self.form.textEdit.toPlainText()).encode('utf8')
        asmesh=self.form.checkboxmesh.checkState()
        import OpenSCADUtils, os
        extension= 'stl' if asmesh else 'csg'
        try:
            tmpfilename=OpenSCADUtils.callopenscadstring(scadstr,extension)
            doc=FreeCAD.activeDocument() or FreeCAD.newDocument()
            if asmesh:
                import Mesh
                Mesh.insert(tmpfilename,doc.Name)
            else:
                import importCSG
                importCSG.insert(tmpfilename,doc.Name)
            try:
                os.unlink(tmpfilename)
            except OSError:
                pass

        except OpenSCADUtils.OpenSCADError, e:
            FreeCAD.Console.PrintError(e.value)
def main():
    shape = Part.Shape()
    #shape_formats = ['.brp', '.igs', '.stp']
    if in_ext in mesh_formats:
        print("Opening mesh file: ", in_f)
        Mesh.open(in_f)
        o = FreeCAD.getDocument("Unnamed").findObjects()[0]
        #print("dir: ", dir(o))
        if out_ext in mesh_formats:
            print("Exporting to mesh file: ", out_f)
            Mesh.export([o], out_f)
        else:
            # TODO This is not optimizing the resulting amount of faces!
            # see http://www.freecadweb.org/wiki/index.php?title=Mesh_to_Part
            shape.makeShapeFromMesh(o.Mesh.Topology, 0.05)  # tolerance for sewing
            exportParametric(shape, out_f, out_ext)
    elif out_ext in mesh_formats:
        print("Opening parametric file: ", in_f)
        Part.open(in_f)
        o = FreeCAD.getDocument("Unnamed").findObjects()[0]
        print("Exporting to mesh file: ", out_f)
        Mesh.export([o], out_f)
    else:
        # Parametric -> Parametric
        print("Opening parametric file: ", in_f)
        shape.read(in_f)
        exportParametric(shape, out_f, out_ext)
 def exportSTL(self, filename, split_colors=True):
     __objs_dict__ = collections.defaultdict(lambda:[])
     __objs__ = []
     for obj in self.doc.Objects:
         red, green, blue, j1 = obj.ViewObject.ShapeColor
         red = round(red, 6)
         green = round(green, 6)
         blue = round(blue, 6)
         color = '%6f:%6f:%6f' % (red, green, blue)
         for key, value in SimpleSolidPy.primitives.colors.items():
             print (key, (red, green, blue), value)
             if (red, green, blue) == value:
                 print('setting color')
                 color = key
         print(color)
         __objs_dict__[color].append(obj)
         __objs__.append(obj)
     if split_colors:
         for key, value in __objs_dict__.items():
             Mesh.export(value, filename.replace('stl','').strip('.')+'_'+key+'.stl')
     else:
         Mesh.export(__objs__, filename)
def openscadmesh(doc,scadstr,objname):
    import Part,Mesh,os,OpenSCADUtils
    tmpfilename=OpenSCADUtils.callopenscadstring(scadstr,'stl')
    if tmpfilename:
        #mesh1 = doc.getObject(objname) #reuse imported object
        Mesh.insert(tmpfilename)
        os.unlink(tmpfilename)
        mesh1=doc.getObject(objname) #blog
        mesh1.ViewObject.hide()
        sh=Part.Shape()
        sh.makeShapeFromMesh(mesh1.Mesh.Topology,0.1)
        solid = Part.Solid(sh)
        obj=doc.addObject("Part::FeaturePython",objname)
        ImportObject(obj,mesh1) #This object is not mutable from the GUI
        ViewProviderTree(obj.ViewObject)
        solid=solid.removeSplitter()
        if solid.Volume < 0:
            solid.complement()
        obj.Shape=solid#.removeSplitter()
        return obj
    else:
        print scadstr
Beispiel #24
0
def process_mesh_file(fname,ext):
    import Mesh
    fullname = fname+'.'+ext
    filename = os.path.join(pathName,fullname)
    mesh1 = doc.getObject(fname) #reuse imported object
    if not mesh1:
        Mesh.insert(filename)
        mesh1=doc.getObject(fname)
    mesh1.ViewObject.hide()
    sh=Part.Shape()
    sh.makeShapeFromMesh(mesh1.Mesh.Topology,0.1)
    solid = Part.Solid(sh)
    obj=doc.addObject('Part::Feature',"Mesh")
    #ImportObject(obj,mesh1) #This object is not mutable from the GUI
    #ViewProviderTree(obj.ViewObject)
    solid=solid.removeSplitter()
    if solid.Volume < 0:
        #sh.reverse()
        #sh = sh.copy()
        solid.complement()
    obj.Shape=solid#.removeSplitter()
    return(obj)
Beispiel #25
0
 def testFitExact(self):
     # symmetric
     v=[]
     v.append(FreeCAD.Vector(0,0,0.0))
     v.append(FreeCAD.Vector(1,0,0.0))
     v.append(FreeCAD.Vector(2,0,0.0))
     v.append(FreeCAD.Vector(0,1,0.0))
     v.append(FreeCAD.Vector(1,1,1.0))
     v.append(FreeCAD.Vector(2,1,0.0))
     d = Mesh.polynomialFit(v)
     c = d["Coefficients"]
     print ("Polynomial: f(x,y)=%f*x^2%+f*y^2%+f*x*y%+f*x%+f*y%+f" % (c[0],c[1],c[2],c[3],c[4],c[5]))
     for i in d["Residuals"]:
        self.failUnless(math.fabs(i) < 0.0001, "Too high residual %f" % math.fabs(i))
Beispiel #26
0
def createConicalFrustum(radius1, radius2, height, pnt=FreeCAD.Vector(), fn=50):
    if fuzzyCompare(radius1, radius2):
        mesh = Mesh.createCylinder(abs(radius1), abs(height), 1, 0.5/fn, int(fn))
        mesh.transform(FreeCAD.Placement(pnt, FreeCAD.Rotation(0,-90,0)).toMatrix())
        return mesh

    elif radius1*radius2 >= 0:
        mesh = Mesh.createCone(abs(radius1), abs(radius2), abs(height), 1, 0.5/fn, int(fn))
        mesh.transform(FreeCAD.Placement(pnt, FreeCAD.Rotation(0,-90,0)).toMatrix())
        return mesh

    else:
        height1 = abs(height)*abs(radius1/(radius1-radius2))
        height2 = abs(height)*abs(radius2/(radius1-radius2))
        pnt1 = pnt
        pnt2 = pnt + FreeCAD.Vector(0, 0, height1)

        mesh1 = Mesh.createCone(abs(radius1), 0, height1, 1, 0.5/fn, int(fn))
        mesh1.transform(FreeCAD.Placement(pnt1, FreeCAD.Rotation(0,-90,0)).toMatrix())
        mesh2 = Mesh.createCone(0, abs(radius2), height2, 1, 0.5/fn, int(fn))
        mesh2.transform(FreeCAD.Placement(pnt2, FreeCAD.Rotation(0,-90,0)).toMatrix())
        mesh = mesh1.unite(mesh2)
        return mesh
	def accept(self):
		# Verify the active document
		actDoc = FreeCAD.ActiveDocument
		if not actDoc:
			self.errorBox("No Open Document\n")
			return False
		Console.PrintMessage("Accepted" + '\n')
		docName = actDoc.Label
		docDir = FreeCAD.ActiveDocument.FileName.replace(docName + ".fcstd", "")
		partList = FreeCADGui.Selection.getSelection()
		# Verify at least one part is selected
		if not partList:
			self.errorBox("Select at Least One Part Object")
			return False
		stlParts = docDir + docName + ".stl"
		Mesh.export(partList, stlParts)
		self.pos = self.GetXYZPos(partList)
		#Console.PrintMessage(str(self.pos) + '\n')
		retVal = self.sliceParts(self.Vars.readMisc("CuraPath"), stlParts)
		if retVal is True:
			self.errorBox("Slice Failed!\n Check log file\n" + logFile)
			return False
		else:
			return True
def saveAndClose(name,saveSTL):
	#Make dateString and add it to the directory string
	date = datetime.date.today().strftime("%m_%d_%Y")

	#make the printer's directory if it doesn't exist
	printerDir = gv.printerDir+"Printer_"+date+"/"
	if not os.path.exists(printerDir):
		os.makedirs(printerDir)
		
	#make the Parts directory if it doesn't exist
	partsDir = printerDir+"Parts/"
	if not os.path.exists(partsDir):
		os.makedirs(partsDir)
		
	#Save the FCStd file
	if os.path.isfile(partsDir+name+".FCStd"):
		os.remove(partsDir+name+".FCStd")
	App.getDocument(name).saveAs(partsDir+name+".FCStd")
	
	if saveSTL:
		#make the STLs directory if it doesn't exist
		stlDir = printerDir+"STL_Files/"
		if not os.path.exists(stlDir):
			os.makedirs(stlDir)
		
		#Export an STL
		if os.path.isfile(stlDir+name+".stl"):
			os.remove(stlDir+name+".stl")
		__objs__=[]
		__objs__.append(App.getDocument(name).Objects[-1])
		import Mesh
		Mesh.export(__objs__,stlDir+name+".stl")
		del __objs__
	
	#close document
	App.closeDocument(name)
Beispiel #29
0
def makePoints():
	FreeCAD.newDocument()
	import Mesh
	m=Mesh.createSphere(5.0).Points
	import Points
	p=Points.Points()

	l=[]
	for s in m:
		l.append(s.Vector)

	p.addPoints(l)


	a=FreeCAD.ActiveDocument.addObject("Points::FeaturePython","Points")
	a.Points=p
	PointFeature(a)
	ViewProviderPoints(a.ViewObject)
Beispiel #30
0
def _createTaperedBox(proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh):
    """
    Private function.
    Use createTaperedBox() or createArticulatedTaperedBox() instead.
    """
    taperedBox = _createBox(proxy, size, colour, moiScale=moiScale, withMesh=False)

    if withMesh:
        mesh = Mesh.createEllipsoid(
            position=(0, 0, 0),
            radius=(size[0] / 2.0, size[1] / 2.0, size[2] / 2.0),
            colour=colour,
            exponentBottom=exponentBottom,
            exponentTop=exponentTop,
            exponentSide=exponentSide,
        )
        taperedBox.addMesh(mesh)

    return taperedBox
Beispiel #31
0
 def testDelimitedGRIDElement(self):
     m = Mesh.read(
         f"{self.test_dir}/NASTRAN_Test_Delimited_GRID_CQUAD4.bdf")
     self.assertEqual(m.CountPoints, 10)
     self.assertEqual(m.CountFacets, 8)  # Quads split into two triangles
Beispiel #32
0
 def testCollapseFacetsAll(self):
     planarMeshObject = Mesh.Mesh(self.planarMesh)
     planarMeshObject.collapseFacets(range(18))
Beispiel #33
0
# Choose computing platform and set number of processors
#pde['platform'] = "gpu";   # choose this option if NVIDIA GPUs are available
pde['mpiprocs'] = 1
# number of MPI processors

# Set discretization parameters, physical parameters, and solver parameters
pde['porder'] = 3
# polynomial degree
pde['physicsparam'] = numpy.array([1.0])
# unit thermal conductivity
pde['tau'] = numpy.array([1.0])
# DG stabilization parameter

# create a mesh of 8 by 8 quads on a square domain
mesh['p'], mesh['t'] = Mesh.SquareMesh(8, 8, 1)[0:2]
# expressions for domain boundaries
mesh['boundaryexpr'] = [
    lambda p: (p[1, :] < 1e-3), lambda p: (p[0, :] > 1 - 1e-3), lambda p:
    (p[1, :] > 1 - 1e-3), lambda p: (p[0, :] < 1e-3)
]
mesh['boundarycondition'] = numpy.array([1, 1, 1, 1])
# Set boundary condition for each boundary
mesh['periodicexpr'] = [[2, lambda p: p[1, :], 4, lambda p: p[1, :]]]

# call exasim to generate and run C++ code to solve the PDE model
sol, pde, mesh = Postprocessing.exasim(pde, mesh)[0:3]

# visualize the numerical solution of the PDE model using Paraview
pde['visscalars'] = ["temperature", 0]
# list of scalar fields for visualization
Beispiel #34
0
    def generate(self):
        p = self.props

        print("Generating: " + p["NAME"])

        IL = int(10 * p["BODY_LENGTH_IN"])
        IW = int(10 * p["BODY_LENGTH_IN"])
        ILString = str(IL).rjust(2, '0') + str(IW).rjust(2, '0')
        kicad_mod = Footprint(p["NAME"])

        if p["TYPE"] == "CAPM":
            kicad_mod.setDescription(
                "Surface Mount Molded Capacitor, 2 Pins, " + ILString + ", " +
                str(p["BODY_LENGTH"]) + "mm X " + str(p["BODY_WIDTH"]) + "mm")
        elif p["TYPE"] == "CAPC":
            kicad_mod.setDescription(
                "Surface Mount Molded Capacitor, Polarized, 2 Pins, " +
                ILString + ", " + str(p["BODY_LENGTH"]) + "mm X " +
                str(p["BODY_WIDTH"]) + "mm")
        elif p["TYPE"] == "DIOM":
            kicad_mod.setDescription("Surface Mount Molded Diode, 2 Pins, " +
                                     ILString + ", " + str(p["BODY_LENGTH"]) +
                                     "mm X " + str(p["BODY_WIDTH"]) + "mm")
        elif p["TYPE"] == "INDC":
            kicad_mod.setDescription(
                "Surface Mount Molded Inductor, 2 Pins, " + ILString + ", " +
                str(p["BODY_LENGTH"]) + "mm X " + str(p["BODY_WIDTH"]) + "mm")

        kicad_mod.setTags(ILString + " " +
                          str(int(p["BODY_LENGTH"] * 10)).rjust(2, '0') +
                          str(int(p["BODY_WIDTH"] * 10)).rjust(2, '0'))

        # set general values
        kicad_mod.append(
            Text(type='reference',
                 text='REF**',
                 at=[0, -p["COURTYARD_WIDTH"] / 2 - 1],
                 layer='F.SilkS'))
        kicad_mod.append(
            Text(type='value',
                 text=p["NAME"],
                 at=[0, p["COURTYARD_WIDTH"] / 2 + 1],
                 layer='F.Fab'))

        # create fabrication layer
        kicad_mod.append(
            RectLine(start=[-p["BODY_LENGTH"] / 2, -p["BODY_WIDTH"] / 2],
                     end=[p["BODY_LENGTH"] / 2, p["BODY_WIDTH"] / 2],
                     layer='F.Fab'))

        # create silscreen
        if p["TYPE"] in ["DIOM", "CAPMP"]:
            kicad_mod.append(
                Line(start=[
                    -p["SILKSCREEN_LENGTH"] / 2, -p["SILKSCREEN_WIDTH"] / 2
                ],
                     end=[0, -p["SILKSCREEN_WIDTH"] / 2],
                     layer='F.SilkS'))
            kicad_mod.append(
                Line(start=[
                    -p["SILKSCREEN_LENGTH"] / 2, p["SILKSCREEN_WIDTH"] / 2
                ],
                     end=[0, p["SILKSCREEN_WIDTH"] / 2],
                     layer='F.SilkS'))
            kicad_mod.append(
                Line(start=[
                    -p["SILKSCREEN_LENGTH"] / 2, -p["SILKSCREEN_WIDTH"] / 2
                ],
                     end=[
                         -p["SILKSCREEN_LENGTH"] / 2, p["SILKSCREEN_WIDTH"] / 2
                     ],
                     layer='F.SilkS'))
        elif p["TYPE"] in ["CAPM"]:
            kicad_mod.append(
                RectLine(start=[
                    -p["SILKSCREEN_LENGTH"] / 2, -p["SILKSCREEN_WIDTH"] / 2
                ],
                         end=[
                             p["SILKSCREEN_LENGTH"] / 2,
                             p["SILKSCREEN_WIDTH"] / 2
                         ],
                         layer='F.SilkS'))
        elif p["TYPE"] in ["INDM"]:
            kicad_mod.append(
                RectLine(start=[-p["BODY_LENGTH"] / 2, -p["BODY_WIDTH"] / 2],
                         end=[p["BODY_LENGTH"] / 2, p["BODY_WIDTH"] / 2],
                         layer='F.SilkS'))

        # create courtyard
        kicad_mod.append(
            RectLine(
                start=[-p["COURTYARD_LENGTH"] / 2, -p["COURTYARD_WIDTH"] / 2],
                end=[p["COURTYARD_LENGTH"] / 2, p["COURTYARD_WIDTH"] / 2],
                layer='F.CrtYd'))

        # create pads
        kicad_mod.append(
            Pad(number=1,
                type=Pad.TYPE_SMT,
                shape=Pad.SHAPE_ROUNDED_RECT,
                at=[-p["PAD_DISTANCE"] / 2, 0],
                size=[p["PAD_LENGTH"], p["PAD_WIDTH"]],
                layers=Pad.LAYERS_SMT,
                solder_mask_margin=p["SOLDER_MASK_MARGIN"]))
        kicad_mod.append(
            Pad(number=2,
                type=Pad.TYPE_SMT,
                shape=Pad.SHAPE_ROUNDED_RECT,
                at=[p["PAD_DISTANCE"] / 2, 0],
                size=[p["PAD_LENGTH"], p["PAD_WIDTH"]],
                layers=Pad.LAYERS_SMT,
                solder_mask_margin=p["SOLDER_MASK_MARGIN"]))

        # generate 3d model
        scale = 1 / 2.54
        box = Part.makeBox(p["BODY_LENGTH"] * scale, p["BODY_WIDTH"] * scale,
                           p["BODY_HEIGHT"] * scale)
        box.translate(
            FreeCAD.Vector(-p["BODY_LENGTH"] / 2 * scale,
                           -p["BODY_WIDTH"] / 2 * scale, 0))
        mesh = Mesh.Mesh()
        mesh.addFacets(box.tessellate(0.01))

        # add the model to module but use kicad system paths
        # this assumes all libraries are installed into kicad system directory
        kicad_mod.append(
            Model(filename="${KISYS3DMOD}/" + p["TYPE"] + ".3dshapes/" +
                  p["NAME"] + ".wrl",
                  at=[0, 0, 0],
                  scale=[1, 1, 1],
                  rotate=[0, 0, 0]))

        self.mesh = mesh
        self.footprint = kicad_mod
    def proceed(self):
        temp_file = tempfile.mkstemp(suffix='.step')[1]
        selection = FreeCADGui.Selection.getSelection()
        if not selection:
            QtGui.QMessageBox.critical(
                None, "GMSHMesh macro",
                "An object has to be selected to run gmsh!")
            return
        # Export a part in step format
        ImportGui.export(selection, temp_file)
        selection_name = selection[0].Name
        # Mesh temporaly file
        file_format = self.cmb_format.currentText()
        temp_mesh_file = os.path.join(tempfile.tempdir,
                                      selection_name + '_Mesh.' + file_format)
        # OPTIONS GMSH:
        clmax = self.sb_max_element_size.text()
        clmin = self.sb_min_element_size.text()
        cmd_line_opt = self.le_cmd_line_opt.text()
        algo = self.cmb_algorithm.currentText()
        mesh_order = self.sb_mesh_order.text()

        if self.cb_optimized.isChecked():
            cmd_optimize = ' -optimize'
        else:
            cmd_optimize = ''

        if self.rb_3D.isChecked():
            dim = ' -3 '
        if self.rb_2D.isChecked():
            dim = ' -2 '
        if self.rb_1D.isChecked():
            dim = ' -1 '
        if self.cb_max_elme_size.isChecked():
            max_size = ' -clmax ' + clmax
        else:
            max_size = ''
        if self.cb_min_elme_size.isChecked():
            min_size = ' -clmin ' + clmin
        else:
            min_size = ''
        if self.cb_mesh_order.isChecked():
            order = ' -order ' + mesh_order
        else:
            order = ''

        options = ' -algo ' + algo + max_size + min_size + cmd_optimize + order + cmd_line_opt
        # RUN GMSH
        command = gmsh_bin + ' ' + temp_file + dim + '-format ' + file_format + ' -o ' + temp_mesh_file + '' + options
        FreeCAD.Console.PrintMessage("Running: \"{}\"\n".format(command))
        try:
            output = subprocess.check_output(
                [command, '-1'],
                shell=True,
                stderr=subprocess.STDOUT,
            )
            for line in output.split('\n'):
                if "Error" in line:
                    FreeCAD.Console.PrintError("{}\n".format(line))
                elif "Warning" in line:
                    FreeCAD.Console.PrintWarning("{}\n".format(line))
            #FreeCAD.Console.PrintMessage("Output: \"{}\"\n".format(output))
            if file_format in ('unv', 'med'):
                Fem.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name)
            if file_format == 'stl':
                Mesh.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name)
            if file_format == 'msh':
                out_mesh_file = os.path.join(
                    os.path.dirname(os.path.abspath(__file__)), "geometry.msh")
                shutil.move(temp_mesh_file, out_mesh_file)
                FreeCAD.Console.PrintMessage(
                    "Output file written to: {}\n".format(out_mesh_file))
            if self.cb_mec_anal.isChecked():
                FMesh = App.activeDocument().ActiveObject
                MechanicalAnalysis.makeMechanicalAnalysis('MechanicalAnalysis')
                FemGui.setActiveAnalysis(App.activeDocument().ActiveObject)
                App.activeDocument().ActiveObject.Member = App.activeDocument(
                ).ActiveObject.Member + [FMesh]
            if self.rb_1D.isChecked():
                FMeshG = Gui.ActiveDocument.ActiveObject
                FMeshG.DisplayMode = "Elements & Nodes"
        except:
            FreeCAD.Console.PrintError(
                "Unexpected error in GMSHMesh macro: {} {}\n".format(
                    sys.exc_info()[0],
                    sys.exc_info()[1]))
        finally:
            try:
                del temp_file
            except:
                pass
            try:
                del temp_mesh_file
            except:
                pass
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()
else:
    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * (-0.5)

# insertion part_stator
Mesh.insert(u"part_stator.stl", "assembly")
FreeCAD.getDocument("assembly").getObject(
    "part_stator").Placement = App.Placement(
        App.Vector(0, 0, 0), App.Rotation(App.Vector(0, 0, 1), 0))
FreeCADGui.getDocument("assembly").getObject("part_stator").ShapeColor = (0.50,
                                                                          0.50,
                                                                          0.50)
FreeCADGui.getDocument("assembly").getObject("part_stator").Transparency = 70

# insertion part_rotor
Mesh.insert(u"part_rotor.stl", "assembly")
FreeCAD.getDocument("assembly").getObject(
    "part_rotor").Placement = App.Placement(
        App.Vector(0, 0, 0), App.Rotation(App.Vector(0, 0, 1), 0))
FreeCADGui.getDocument("assembly").getObject("part_rotor").ShapeColor = (0.10,
                                                                         0.20,
Beispiel #37
0
def createMesh(r, s):
    #FreeCAD.Console.PrintMessage("Create sphere (%s,%s)...\n"%(r,s))
    mesh = Mesh.createSphere(r, s)
Beispiel #38
0
def createMesh():
    # ========================  Script beginning...  ========================
    beVerbose = 1
    if beVerbose == 1:
        Console.PrintMessage("\n\n\n\n\n\n\n\nScript starts...")
    # Geometry definition
    # Define objects names
    PyDocumentName = "pnJunction"
    PSideBoxName = "PSide"
    NSideBoxName = "NSide"
    DepletionBoxName = "Depletion"
    SurfDepletionBoxName = "SurfDepletion"
    OxideBoxName = "Oxide"
    AdsorbtionBoxName = "Adsorbtion"
    pnMeshName = "pnMesh"

    # Init objects
    if beVerbose == 1:
        Console.PrintMessage("\nInit Objects...")
    # closeDocument after restart of macro. Needs any ActiveDocument.
    # App.closeDocument(App.ActiveDocument.Label)
    AppPyDoc = App.newDocument(PyDocumentName)
    NSideBox = AppPyDoc.addObject("Part::Box", NSideBoxName)
    PSideBox = AppPyDoc.addObject("Part::Box", PSideBoxName)
    DepletionBox = AppPyDoc.addObject("Part::Box", DepletionBoxName)
    SurfDepletionBox = AppPyDoc.addObject("Part::Box", SurfDepletionBoxName)
    OxideBox = AppPyDoc.addObject("Part::Box", OxideBoxName)
    AdsorbtionBox = AppPyDoc.addObject("Part::Box", AdsorbtionBoxName)
    pnMesh = AppPyDoc.addObject("Mesh::Feature", pnMeshName)

    BoxList = [
        NSideBox,
        DepletionBox,
        PSideBox,
        OxideBox,
        AdsorbtionBox,
        SurfDepletionBox
    ]
    NSideBoxMesh = Mesh.Mesh()
    PSideBoxMesh = Mesh.Mesh()
    DepletionBoxMesh = Mesh.Mesh()
    SurfDepletionBoxMesh = Mesh.Mesh()
    OxideBoxMesh = Mesh.Mesh()
    AdsorbtionBoxMesh = Mesh.Mesh()
    BoxMeshList = [
        NSideBoxMesh,
        DepletionBoxMesh,
        PSideBoxMesh,
        OxideBoxMesh,
        AdsorbtionBoxMesh,
        SurfDepletionBoxMesh
    ]
    if beVerbose == 1:
        if len(BoxList) != len(BoxMeshList):
            Console.PrintMessage(
                "\n ERROR! Input len() of BoxList and BoxMeshList is not the same! "
            )

    # Set sizes in nanometers
    if beVerbose == 1:
        Console.PrintMessage("\nSet sizes...")
    tessellationTollerance = 0.05
    ModelWidth = 300
    BulkHeight = 300
    BulkLength = 300
    DepletionSize = 50
    OxideThickness = 5
    AdsorbtionThickness = 10

    # Big volumes of n and p material
    NSideBox.Height = BulkHeight  # Z-direction
    NSideBox.Width = ModelWidth  # Y-direction = const
    NSideBox.Length = BulkLength  # X-direction
    PSideBox.Height = BulkHeight
    PSideBox.Width = ModelWidth
    PSideBox.Length = BulkLength
    # Thin depletion layer between
    DepletionBox.Height = BulkHeight
    DepletionBox.Width = ModelWidth
    DepletionBox.Length = DepletionSize * 2
    # Surface deplation layer
    SurfDepletionBox.Height = DepletionSize
    SurfDepletionBox.Width = ModelWidth
    SurfDepletionBox.Length = BulkLength * 2 + DepletionSize * 2
    # Oxide on the top
    OxideBox.Height = OxideThickness
    OxideBox.Width = ModelWidth
    OxideBox.Length = BulkLength * 2 + DepletionSize * 2
    # Adsorbtion layer
    AdsorbtionBox.Height = AdsorbtionThickness
    AdsorbtionBox.Width = ModelWidth
    AdsorbtionBox.Length = BulkLength * 2 + DepletionSize * 2

    # Object placement
    Rot = App.Rotation(0, 0, 0, 1)
    NSideBox.Placement = App.Placement(
        App.Vector(0, 0, -BulkHeight),
        Rot
    )
    PSideBox.Placement = App.Placement(
        App.Vector(DepletionSize * 2 + BulkLength, 0, -BulkHeight),
        Rot
    )
    DepletionBox.Placement = App.Placement(
        App.Vector(BulkLength, 0, -BulkHeight),
        Rot
    )
    SurfDepletionBox.Placement = App.Placement(
        App.Vector(0, 0, 0),
        Rot
    )
    OxideBox.Placement = App.Placement(
        App.Vector(0, 0, DepletionSize),
        Rot
    )
    AdsorbtionBox.Placement = App.Placement(
        App.Vector(0, 0, DepletionSize + OxideThickness),
        Rot
    )

    # Unite
    if beVerbose == 1:
        Console.PrintMessage("\nFuse objects...")
    fuseShape = BoxList[0].Shape
    for index in range(1, len(BoxList), 1):
        fuseShape = fuseShape.fuse(BoxList[index].Shape)
    nmesh = Mesh.Mesh()
    nmesh.addFacets(fuseShape.tessellate(tessellationTollerance))

    # for index in range(len(BoxList)):
    for index in range(len(BoxList) - 1):  # Manual hack
        BoxMeshList[index].addFacets(
            BoxList[index].Shape.tessellate(tessellationTollerance)
        )
        nmesh.addMesh(BoxMeshList[index])

    nmesh.removeDuplicatedPoints()
    nmesh.removeDuplicatedFacets()
    pnMesh.Mesh = nmesh

    if FreeCAD.GuiUp:
        # Hide all boxes
        for box in BoxList:
            Gui.hideObject(box)

    # Remove all boxes
    # for box in BoxList:
    #     App.ActiveDocument.removeObject(box.Name)

    # Update document
    AppPyDoc.recompute()

    # export to TenGen *.poly (use File|Export instead)
    # filePath = "/home/tig/tmp/tetgen/pnJunction.poly"
    # exportMeshToTetGenPoly(pnMesh.Mesh,filePath,beVerbose)

    if FreeCAD.GuiUp:
        pnMesh.ViewObject.Document.activeView().viewAxonometric()
        pnMesh.ViewObject.Document.activeView().fitAll()

    if beVerbose == 1:
        Console.PrintMessage("\nScript finished without errors.")
Beispiel #39
0
def createMeshView(obj,
                   direction=FreeCAD.Vector(0, 0, -1),
                   outeronly=False,
                   largestonly=False):
    """createMeshView(obj,[direction,outeronly,largestonly]): creates a flat shape that is the
    projection of the given mesh object in the given direction (default = on the XY plane). If
    outeronly is True, only the outer contour is taken into consideration, discarding the inner
    holes. If largestonly is True, only the largest segment of the given mesh will be used."""

    import Mesh, math, Part, DraftGeomUtils
    if not obj.isDerivedFrom("Mesh::Feature"):
        return
    mesh = obj.Mesh

    # 1. Flattening the mesh
    proj = []
    for f in mesh.Facets:
        nf = []
        for v in f.Points:
            v = FreeCAD.Vector(v)
            a = v.negative().getAngle(direction)
            l = math.cos(a) * v.Length
            p = v.add(FreeCAD.Vector(direction).multiply(l))
            p = DraftVecUtils.rounded(p)
            nf.append(p)
        proj.append(nf)
    flatmesh = Mesh.Mesh(proj)

    # 2. Removing wrong faces
    facets = []
    for f in flatmesh.Facets:
        if f.Normal.getAngle(direction) < math.pi:
            facets.append(f)
    cleanmesh = Mesh.Mesh(facets)

    #Mesh.show(cleanmesh)

    # 3. Getting the bigger mesh from the planar segments
    if largestonly:
        c = cleanmesh.getSeparateComponents()
        #print(c)
        cleanmesh = c[0]
        segs = cleanmesh.getPlanarSegments(1)
        meshes = []
        for s in segs:
            f = [cleanmesh.Facets[i] for i in s]
            meshes.append(Mesh.Mesh(f))
        a = 0
        for m in meshes:
            if m.Area > a:
                boundarymesh = m
                a = m.Area
        #Mesh.show(boundarymesh)
        cleanmesh = boundarymesh

    # 4. Creating a Part and getting the contour

    shape = None
    for f in cleanmesh.Facets:
        p = Part.makePolygon(f.Points + [f.Points[0]])
        #print(p,len(p.Vertexes),p.isClosed())
        try:
            p = Part.Face(p)
            if shape:
                shape = shape.fuse(p)
            else:
                shape = p
        except Part.OCCError:
            pass
    shape = shape.removeSplitter()

    # 5. Extracting the largest wire

    if outeronly:
        count = 0
        largest = None
        for w in shape.Wires:
            if len(w.Vertexes) > count:
                count = len(w.Vertexes)
                largest = w
        if largest:
            try:
                f = Part.Face(w)
            except Part.OCCError:
                print("Unable to produce a face from the outer wire.")
            else:
                shape = f

    return shape
    alpha=(i*degre*math.pi)/180
    hole_vector = FreeCAD.Vector(radius*math.cos(alpha), radius*math.sin(alpha), 0)
    hole.translate(hole_vector)
    part_support_laser_cutting = part_support_laser_cutting.cut(hole)

Part.show(part_support_laser_cutting)

DOC.recompute()

__objs__ = []

__objs__.append(FreeCAD.getDocument("part_support_laser_cutting").getObject("Shape"))

stl_file = u"part_support_laser_cutting.stl"

Mesh.export(__objs__, stl_file)

dxf_file = u"part_support_laser_cutting.dxf"

importDXF.export(__objs__, dxf_file)

setview()

# Generate PNG files
file = 'part_support_laser_cutting_v3_'
# Ombr�
Gui.runCommand('Std_DrawStyle',5)
i = 1
Gui.activeDocument().activeView().viewIsometric()
Gui.activeDocument().activeView().saveImage(file + str(i) + '.png',1117,388,'Current')
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()
else:
    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * -0.5

# part_alternateur
Mesh.insert(u"part_alternateur.stl", "assembly_alternateur")
FreeCADGui.getDocument("assembly_alternateur").getObject(
    "part_alternateur").ShapeColor = (0.10, 0.10, 0.10)
FreeCAD.getDocument("assembly_alternateur").getObject(
    "part_alternateur").Placement = App.Placement(
        App.Vector(0, 0, 0), App.Rotation(App.Vector(0, 0, 1), 0))

# part_poulie_alternateur
Mesh.insert(u"part_poulie_alternateur.stl", "assembly_alternateur")
FreeCADGui.getDocument("assembly_alternateur").getObject(
    "part_poulie_alternateur").ShapeColor = (0.90, 0.80, 0.70)
FreeCAD.getDocument("assembly_alternateur").getObject(
    "part_poulie_alternateur").Placement = App.Placement(
        App.Vector(-50, 456 / 2, 250), App.Rotation(App.Vector(0, 1, 0), 90))

# part_moyeu_amovible_alternateur
import sys

import Mesh
import Part
import FreeCAD

# This file is run by Freecads own version of python to do step file conversion
# The exporter will shell out to Freecad and provide the path to this file

in_fn, out_fn = sys.argv[2], sys.argv[3]

try:
    Part.open(in_fn)
except:
    sys.exit(1)

o = [FreeCAD.getDocument("Unnamed").findObjects()[0]]
Mesh.export(o, out_fn)
Beispiel #43
0
# Set discretization parameters, physical parameters, and solver parameters
pde['porder'] = 3
# polynomial degree
pde['physicsparam'] = numpy.array([1.0, 0.0])
# unit thermal conductivity
pde['tau'] = numpy.array([1.0])
# DG stabilization parameter

# Choose computing platform and set number of processors
#pde['platform'] = "gpu";   # choose this option if NVIDIA GPUs are available
pde['mpiprocs'] = 2
# number of MPI processors

# create a mesh of 8 by 8 by 8 hexes for a unit cube
mesh['p'], mesh['t'] = Mesh.cubemesh(8, 8, 8, 1)[0:2]
# expressions for domain boundaries
mesh['boundaryexpr'] = [
    lambda p: (p[1, :] < 1e-3), lambda p: (p[0, :] > 1 - 1e-3), lambda p:
    (p[1, :] > 1 - 1e-3), lambda p: (p[0, :] < 1e-3), lambda p:
    (p[2, :] < 1e-3), lambda p: (p[2, :] > 1 - 1e-3)
]
mesh['boundarycondition'] = numpy.array([1, 1, 1, 1, 1, 1])
# Set boundary condition for each boundary

# call exasim to generate and run C++ code to solve the PDE model
sol, pde, mesh = Postprocessing.exasim(pde, mesh)[0:3]

# visualize the numerical solution of the PDE model using Paraview
#pde['paraview'] = "/Applications/ParaView-5.8.1.app/Contents/MacOS/paraview"; # Set the path to Paraview executable
pde['visscalars'] = ["temperature", 0]
Beispiel #44
0
 def testCollapseFacetsSingle(self):
     for i in range(18):
         planarMeshObject = Mesh.Mesh(self.planarMesh)
         planarMeshObject.collapseFacets([i])
Beispiel #45
0
    def build_triangle_mesh(self, resolution):  
        n = 6.0
        output = 30.0
        h = int(n/2) + 1 #height

        while output < resolution:
            n += 1.0
            h = int(n/2) + 1
            output = 2 * n + (n * h) 
        
        m = Mesh()

        # center vertices
        v_bottom = (0.0, -1.0, 0.0)
        v_top = (0.0, 1.0, 0.0)

        # edge and vertex dictionaries
        e_dict = {}
        v_dict = {}

        for first in range(0, int(n+1)):
            for second in range(0, h+1): 

                x = cos( ((2.0 * pi) / n) * first )
                y = (2.0 / h) * float(second) - 1.0
                z = sin( ((2.0 * pi) / n) * first )

                x_iPlus1 = cos( ((2.0 * pi) / n) * (first + 1) )
                y_jPlus1 = (2.0 / h) * float(second + 1) - 1.0
                z_iPlus1 = sin( ((2.0 * pi) / n) * (first + 1) )

                coordinates = (x, y, z)
                vertical    = (x, y_jPlus1, z)
                horizontal  = (x_iPlus1, y, z_iPlus1)
                diagonal    = (x_iPlus1, y_jPlus1, z_iPlus1)

                # if top
                if y == 1.0 and e_dict.get( (coordinates, v_top) ) == None:
                    e_dict[ (coordinates, v_top) ] = True
                    m.edges.append( (coordinates, v_top) )

                    if v_dict.get(coordinates) == None:
                        v_dict[coordinates] = True
                        m.vertices.append(coordinates)

                    if v_dict.get(v_top) == None:
                        v_dict[v_top] = True
                        m.vertices.append(v_top)

                # if bottom
                if y == -1.0 and e_dict.get( (coordinates, v_bottom) ) == None:
                    e_dict[ (coordinates, v_bottom) ] = True
                    m.edges.append( (coordinates, v_bottom) )
 
                    if v_dict.get(coordinates) == None:
                        v_dict[coordinates] = True
                        m.vertices.append(coordinates)

                    if v_dict.get(v_bottom) == None:
                        v_dict[v_bottom] = True
                        m.vertices.append(v_bottom)

                # horizontal
                if e_dict.get( (coordinates, horizontal) ) == None:
                    e_dict[ (coordinates, horizontal) ] = True
                    m.edges.append( (coordinates, horizontal) )

                    if v_dict.get(coordinates) == None:
                        v_dict[coordinates] = True
                        m.vertices.append(coordinates)

                    if v_dict.get(horizontal) == None:
                        v_dict[horizontal] = True
                        m.vertices.append(horizontal)
                    
                # vertical
                if y_jPlus1 <= 1.0 and e_dict.get( (coordinates, vertical) ) == None:
                    e_dict[ (coordinates, vertical) ] = True
                    m.edges.append( (coordinates, vertical) )

                    if v_dict.get(coordinates) == None:
                        v_dict[coordinates] = True
                        m.vertices.append(coordinates)

                    if v_dict.get(vertical) == None:
                        v_dict[vertical] = True
                        m.vertices.append(vertical)
                
                # diagonal
                if y_jPlus1 <= 1.0 and e_dict.get( (coordinates, diagonal) ) == None:
                    e_dict[ (coordinates, diagonal) ] = True
                    m.edges.append( (coordinates, diagonal) )

                    if v_dict.get(coordinates) == None:
                        v_dict[coordinates] = True
                        m.vertices.append(coordinates)

                    if v_dict.get(diagonal) == None:
                        v_dict[diagonal] = True
                        m.vertices.append(diagonal)

        self.mesh = m
Beispiel #46
0
def createFace(obj):

    nar = np.array(obj.nar).reshape(obj.xdim, obj.ydim)
    a = obj.uPos
    c = obj.vPos
    b = obj.uSize
    d = obj.vSize
    d += 1
    b += 1

    ptsd = []
    ptse = []
    for ix in range(a, a + b):
        for iy in range(c, c + d):
            if nar[ix, iy] != 0:
                ptsd += [FreeCAD.Vector(ix, iy, nar[ix, iy])]
            else:
                ptse += [FreeCAD.Vector(ix, iy, 0)]

    if obj.createPoints:
        p = Points.Points(ptsd)
        Points.show(p)
        am = App.ActiveDocument.ActiveObject
        App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (0., 1.0, 1.)
        App.ActiveDocument.ActiveObject.Label = "lidar points"
        if obj.useOrigin:
            am.Placement = obj.placementOrigin
        else:
            am.Placement = FreeCAD.Placement()

    dat = np.array(ptsd)
    import scipy
    import scipy.interpolate
    modeB = "cubic"

    xy2h = scipy.interpolate.Rbf(dat[:, 0],
                                 dat[:, 1],
                                 dat[:, 2],
                                 function=modeB)

    ptsda = []

    for ix in range(a, a + b):
        for iy in range(c, c + d):
            ptsda += [FreeCAD.Vector(ix, iy, xy2h(ix, iy))]

    if obj.createPoints:
        p = Points.Points(ptsda)
        Points.show(p)
        am = App.ActiveDocument.ActiveObject
        App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (0., 1.0, 0.)
        App.ActiveDocument.ActiveObject.Label = "interpolated points"
        if obj.useOrigin:
            am.Placement = obj.placementOrigin
        else:
            am.Placement = FreeCAD.Placement()

    ptsdarr = np.array(ptsda).reshape(b, d, 3)
    ta = time.time()
    if obj.createNurbs:
        bs = Part.BSplineSurface()
        bs.interpolate(ptsdarr)

        fn = "face_" + str(a) + "_" + str(b) + "_" + str(c) + '_' + str(d)
        obja = App.ActiveDocument.getObject(fn)
        if obja == None:
            obja = FreeCAD.ActiveDocument.addObject("Part::Feature", fn)
            obja.ViewObject.ShapeColor = (random.random(), random.random(),
                                          random.random())
            obja.ViewObject.hide()

        obja.Shape = bs.toShape()
        obj.Shape = bs.toShape()
        if obj.useOrigin:
            obja.Placement = obj.placementOrigin
        else:
            obja.Placement = FreeCAD.Placement()

    Gui.updateGui()
    tb = time.time()

    # def toUVMesh(ptsda,b=50):
    if obj.createMesh:
        topfaces = []
        for x in range(b - 1):
            for y in range(d - 1):
                topfaces.append(
                    (d * x + y, (d) * x + y + 1, (d) * (x + 1) + y))
                topfaces.append(((d) * x + y + 1, (d) * (x + 1) + y,
                                 (d) * (x + 1) + y + 1))

        t = Mesh.Mesh((ptsda, topfaces))
        #Mesh.show(t)
        fn = "mesh_" + str(a) + "_" + str(b) + "_" + str(c) + '_' + str(d)

        if obj.meshName == "":
            obj.meshName = "LidarMesh"
        fn = obj.meshName
        mm = App.ActiveDocument.getObject(fn)
        if mm == None:
            mm = FreeCAD.ActiveDocument.addObject("Mesh::FeaturePython", fn)
            mm.ViewObject.ShapeColor = (random.random(), random.random(),
                                        random.random())

        mm.Mesh = t
        ViewProvider(mm.ViewObject)
        mm.ViewObject.Lighting = "Two side"
        mm.ViewObject.ShapeColor = obj.ViewObject.ShapeColor

        if obj.useOrigin:
            mm.Placement = obj.placementOrigin
        else:
            mm.Placement = FreeCAD.Placement()

    tc = time.time()
    print("nurbs ", tb - ta)
    print("mesh ", tc - tb)
Beispiel #47
0
def loadFile(name):
    #lock.acquire()
    mesh = Mesh.Mesh()
    #FreeCAD.Console.PrintMessage("Create mesh instance\n")
    #lock.release()
    mesh.read(name)
    hole = Part.makeCylinder(5, 6)
    hole.translate(hole_vector)
    cylinder_1 = cylinder_1.cut(hole)

Part.show(cylinder_1)

DOC.recompute()

FreeCADGui.getDocument("light_assembly").getObject("Shape").Transparency = 80

# insertion part_rondelle_10m - 0
degre = 60
radius = diametre_maximal/2 - 7.5 - 5
alpha=(degre*math.pi)/180
vector = App.Vector(radius*math.cos(alpha), radius*math.sin(alpha), -2)
Mesh.insert(u"part_rondelle_10m.stl", "light_assembly")
FreeCAD.getDocument("light_assembly").getObject("part_rondelle_10m").Placement = App.Placement(vector, App.Rotation(App.Vector(0,0,1), 0))
FreeCADGui.getDocument("light_assembly").getObject("part_rondelle_10m").ShapeColor = (1.00,1.00,0.00)

# For placing the part_rondelle_10m
i1 = 1
degres = [120, 180, 240, 300, 360]
for degre in degres:
    radius = diametre_maximal/2 - 7.5 - 5
    alpha=(degre*math.pi)/180
    vector = App.Vector(radius*math.cos(alpha), radius*math.sin(alpha), -2)
    Mesh.insert(u"part_rondelle_10m.stl", "light_assembly")
    FreeCAD.getDocument("light_assembly").getObject("part_rondelle_10m00" + str(i1)).Placement = App.Placement(vector, App.Rotation(App.Vector(0,0,1), 0))
    FreeCADGui.getDocument("light_assembly").getObject("part_rondelle_10m00" + str(i1)).ShapeColor = (1.00,1.00,0.00)
    i1 += 1
Beispiel #49
0
def compute():
    QtGui.qApp.setOverrideCursor(QtCore.Qt.WaitCursor)

    if FreeCAD.ActiveDocument == None:
        FreeCAD.newDocument("Gear")

    oldDocumentObjects = App.ActiveDocument.Objects

    try:
        N = int(l1.text())
        p = float(l2.text())
        alfa = int(l3.text())
        y = float(
            l4.text())  #standard value y<1 for gear drives y>1 for Gear pumps
        m = p / math.pi  #standard value 0.06, 0.12, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 60 (polish norm)
        c = float(l5.text()) * m  #standard value 0,1*m - 0,3*m
        j = float(l6.text()) * m  #standard value 0,015 - 0,04*m
        width = float(l7.text())  #gear width
    except ValueError:
        FreeCAD.Console.PrintError("Wrong input! Only numbers allowed...\n")

    #tooth height
    h = 2 * y * m + c

    #pitch diameter
    d = N * m

    #root diameter
    df = d - 2 * y * m - 2 * c  #df=d-2hf where and hf=y*m+c

    #addendum diameter
    da = d + 2 * y * m  #da=d+2ha where ha=y*m

    #base diameter for involute
    db = d * math.cos(math.radians(alfa))

    #Base circle
    baseCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                                  "BaseCircle")
    Draft._Circle(baseCircle)
    Draft._ViewProviderDraft(baseCircle.ViewObject)
    baseCircle.Radius = db / 2
    baseCircle.FirstAngle = 0.0
    baseCircle.LastAngle = 0.0

    #Root circle
    rootCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                                  "RootCircle")
    Draft._Circle(rootCircle)
    Draft._ViewProviderDraft(rootCircle.ViewObject)
    rootCircle.Radius = df / 2
    rootCircle.FirstAngle = 0.0
    rootCircle.LastAngle = 0.0

    #Addendum circle
    addendumCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                                      "AddendumCircle")
    Draft._Circle(addendumCircle)
    Draft._ViewProviderDraft(addendumCircle.ViewObject)
    addendumCircle.Radius = da / 2
    addendumCircle.FirstAngle = 0.0
    addendumCircle.LastAngle = 0.0

    #Pitch circle
    pitchCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                                   "PitchCircle")
    Draft._Circle(pitchCircle)
    Draft._ViewProviderDraft(pitchCircle.ViewObject)
    pitchCircle.Radius = d / 2
    pitchCircle.FirstAngle = 0.0
    pitchCircle.LastAngle = 0.0

    #************ Calculating right sides of teeth
    #Involute of base circle
    involute = []
    involutee = []
    involutesav = []

    for t in range(0, 60, 1):
        x = db / 2 * (math.cos(math.radians(t)) +
                      math.radians(t) * math.sin(math.radians(t)))
        y = db / 2 * (math.sin(math.radians(t)) -
                      math.radians(t) * math.cos(math.radians(t)))
        involute.append(Part.Vertex(x, y, 0).Point)


#************ Drawing rigth sides of teeth
    involutesav.extend(involute)
    involutee.extend(involute)

    for angle in range(1, N + 1, 1):
        involuteobj = FreeCAD.ActiveDocument.addObject(
            "Part::Feature", "InvoluteL" + str(angle))
        involutee.insert(0, (0, 0, 0))
        involuteshape = Part.makePolygon(involutee)
        involuteobj.Shape = involuteshape
        involutee = []
        for num in range(0, 60, 1):
            point = involute.pop()
            pointt = Part.Vertex(
                point.x * math.cos(math.radians(angle * 360 / N)) -
                point.y * math.sin(math.radians(angle * 360 / N)),
                point.x * math.sin(math.radians(angle * 360 / N)) +
                point.y * math.cos(math.radians(angle * 360 / N)), 0).Point
            involutee.insert(0, pointt)
        involute.extend(involutesav)
    involutee = []

    #************ Calculating difference between tooth spacing on BaseCircle and PitchCircle

    pc = App.ActiveDocument.getObject("PitchCircle")
    inv = App.ActiveDocument.getObject("InvoluteL1")
    cut = inv.Shape.cut(pc.Shape)
    #    FreeCAD.ActiveDocument.addObject("Part::Feature","CutInv").Shape=cut
    invPoint = cut.Vertexes[0].Point

    diff = invPoint.y * 2  # instead of making axial symmetry and calculating point distance.
    anglediff = 2 * math.asin(diff / d)

    #************ Calculating left sides of teeth

    #************ Inversing Involute
    for num in range(0, 60, 1):
        point = involute.pop()
        pointt = Part.Vertex(point.x, point.y * -1, 0).Point
        involutee.insert(0, pointt)
    involute.extend(involutee)
    involutee = []

    #Normal tooth size calculated as: 0,5*  p    -      j                         j=m * 0,1 below are calculations
    #                                 0,5*  p    -      m      * 0,1
    #                                 0,5*  p    -     p   /pi * 0,1
    #                                 0,5*360/N  - ((360/N)/pi)* 0,1
    #                                 0,5*360/N  - (360/N)*((1/pi)*0,1)           j=(p/pi)*0,1
    #                                 0,5*360/N  - (360/N)*((p/pi)*0,1)/p
    #                                 0,5*360/N  - (360/N)*(    j     )/p
    for num in range(0, 60, 1):
        point = involute.pop()
        pointt = Part.Vertex(
            point.x *
            math.cos(math.radians(180 / N - (360 / N) *
                                  (j / p)) + anglediff) - point.y *
            math.sin(math.radians(180 / N - (360 / N) * (j / p)) + anglediff),
            point.x *
            math.sin(math.radians(180 / N - (360 / N) *
                                  (j / p)) + anglediff) + point.y *
            math.cos(math.radians(180 / N - (360 / N) * (j / p)) + anglediff),
            0).Point
        involutee.insert(0, pointt)
    involute.extend(involutee)
    involutesav = []
    involutesav.extend(involute)

    #************ Drawing left sides of teeth
    for angle in range(1, N + 1, 1):
        involuteobj = FreeCAD.ActiveDocument.addObject(
            "Part::Feature", "InvoluteR" + str(angle))
        involutee.insert(0, (0, 0, 0))
        involuteshape = Part.makePolygon(involutee)
        involuteobj.Shape = involuteshape
        involutee = []
        for num in range(0, 60, 1):
            point = involute.pop()
            pointt = Part.Vertex(
                point.x * math.cos(math.radians(angle * 360 / N)) -
                point.y * math.sin(math.radians(angle * 360 / N)),
                point.x * math.sin(math.radians(angle * 360 / N)) +
                point.y * math.cos(math.radians(angle * 360 / N)), 0).Point
            involutee.insert(0, pointt)
        involute.extend(involutesav)

    Gui.SendMsgToActiveView("ViewFit")

    #************ Forming teeth

    cutCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",
                                                 "CutCircle")
    Draft._Circle(cutCircle)
    Draft._ViewProviderDraft(cutCircle.ViewObject)
    cutCircle.Radius = da  # da because must be bigger than addendumCircle and bigger than whole construction da is right for this but it not has to be.
    cutCircle.FirstAngle = 0.0
    cutCircle.LastAngle = 0.0

    cutTool = cutCircle.Shape.cut(addendumCircle.Shape)
    #cutshape=Part.show(cutTool)

    gearShape = rootCircle.Shape

    for invNum in range(1, N + 1, 1):
        invL = App.ActiveDocument.getObject("InvoluteL" + str(invNum))
        invR = App.ActiveDocument.getObject("InvoluteR" + str(invNum))
        cutL = invL.Shape.cut(cutTool)
        cutR = invR.Shape.cut(cutTool)
        pointL = cutL.Vertexes.pop().Point
        pointR = cutR.Vertexes.pop().Point
        faceEdge = Part.makeLine(pointL, pointR)

        toothWhole = cutL.fuse(cutR)
        toothWhole = toothWhole.fuse(faceEdge)
        toothWire = Part.Wire(toothWhole.Edges)
        toothShape = Part.Face(toothWire)
        #        tooth=App.ActiveDocument.addObject("Part::Feature","Tooth"+str(invNum))
        #        tooth.Shape=toothShape
        gearShape = gearShape.fuse(toothShape)

    for o in App.ActiveDocument.Objects:
        if oldDocumentObjects.count(o) == 0:
            App.ActiveDocument.removeObject(o.Name)

    gearFlat = App.ActiveDocument.addObject("Part::Feature", "GearFlat")
    gearFlat.Shape = gearShape
    Gui.ActiveDocument.getObject(gearFlat.Name).Visibility = False

    gear = App.ActiveDocument.addObject("Part::Extrusion", "Gear3D")
    gear.Base = gearFlat
    gear.Dir = (0, 0, width)
    App.ActiveDocument.recompute()

    if c1.isChecked() == True:
        gearMesh = App.ActiveDocument.addObject("Mesh::Feature", "Gear3D-mesh")

        faces = []
        triangles = gear.Shape.tessellate(
            1)  # the number represents the precision of the tessellation)
        for tri in triangles[1]:
            face = []
            for i in range(3):
                vindex = tri[i]
                face.append(triangles[0][vindex])
            faces.append(face)
        mesh = Mesh.Mesh(faces)

        gearMesh.Mesh = mesh
        App.ActiveDocument.removeObject(gear.Name)
        App.ActiveDocument.removeObject(gearFlat.Name)

    App.ActiveDocument.recompute()
    Gui.SendMsgToActiveView("ViewFit")

    QtGui.qApp.restoreOverrideCursor()

    hide()
cylinder_8 = Part.makeCylinder(radius_tank + 2, 2.5)

# cylinder_7 cut by cylinder_8
cylinder_7 = cylinder_7.cut(cylinder_8)

# tank cut by cylinder_7
cylinder_7_vector = FreeCAD.Vector(0, 0, maximal_height + 2.5)
cylinder_7.translate(cylinder_7_vector)
tank = tank.cut(cylinder_7)

Part.show(tank)

DOC.recompute()

# Insert part_top_electrodes
Mesh.insert(u"part_top_electrodes.stl","assembly_with_electrodes")
FreeCAD.getDocument("assembly_with_electrodes").getObject("part_top_electrodes").Placement = App.Placement(App.Vector(0, 0, maximal_height + 2.5),App.Rotation(App.Vector(0,0,0),0))

# Insert part_electrode
Mesh.insert(u"part_electrode.stl","assembly_with_electrodes")
FreeCAD.getDocument("assembly_with_electrodes").getObject("part_electrode").Placement = App.Placement(App.Vector(0, 0, -radius_tank/3),App.Rotation(App.Vector(0,0,0),0))

# Insert part_electrode
Mesh.insert(u"part_electrode.stl","assembly_with_electrodes")
FreeCAD.getDocument("assembly_with_electrodes").getObject("part_electrode001").Placement = App.Placement(App.Vector(10, 0, -radius_tank/3),App.Rotation(App.Vector(0,0,0),0))

# Insert part_electrode
Mesh.insert(u"part_electrode.stl","assembly_with_electrodes")
FreeCAD.getDocument("assembly_with_electrodes").getObject("part_electrode002").Placement = App.Placement(App.Vector(-10, 0, -radius_tank/3),App.Rotation(App.Vector(0,0,0),0))

# Insert part_ecrou
Beispiel #51
0
# time step sizes
pde['soltime'] = numpy.arange(1, pde['dt'].size + 1)
# steps at which solution are collected
pde['visdt'] = pde['dt'][0]
# visualization timestep size

gam = 1.4
# specific heat ratio
M_ref = numpy.sqrt(1 / gam)
# Mach number
pde['physicsparam'] = [gam, M_ref]
pde['tau'] = numpy.array([1 + 1 / M_ref])
# DG stabilization parameter

# create a mesh of 10 by 10 quads on a square domain
mesh['p'], mesh['t'] = Mesh.SquareMesh(10, 10, 1)[0:2]
mesh['p'] = 10 * mesh['p'] - 5
# expressions for domain boundaries
mesh['boundaryexpr'] = [
    lambda p: (p[1, :] < -5 + 1e-3), lambda p: (p[0, :] > 5 - 1e-3), lambda p:
    (p[1, :] > 5 - 1e-3), lambda p: (p[0, :] < -5 + 1e-3)
]
mesh['boundarycondition'] = numpy.array([1, 1, 1, 1])
# Set boundary condition for each boundary
mesh['periodicexpr'] = [[2, lambda p: p[1, :], 4, lambda p: p[1, :]],
                        [1, lambda p: p[0, :], 3, lambda p: p[0, :]]]

# call exasim to generate and run C++ code to solve the PDE model
sol, pde, mesh = Postprocessing.exasim(pde, mesh)[0:3]

# visualize the numerical solution of the PDE model using Paraview
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()
else:
    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * -0.5

# part_tank
Mesh.insert(u"part_tank.stl", "assembly")
FreeCADGui.getDocument("assembly").getObject("part_tank").ShapeColor = (0.10,
                                                                        0.10,
                                                                        0.10)
FreeCAD.getDocument("assembly").getObject(
    "part_tank").Placement = App.Placement(
        App.Vector(0, 0, 0), App.Rotation(App.Vector(0, 0, 1), 0))
FreeCADGui.getDocument("assembly").getObject("part_tank").Transparency = 80

# part_support_laser_cutting _ 1
Mesh.insert(u"part_support_laser_cutting.stl", "assembly")
FreeCADGui.getDocument("assembly").getObject(
    "part_support_laser_cutting").ShapeColor = (1.00, 1.00, 0.00)
FreeCAD.getDocument("assembly").getObject(
    "part_support_laser_cutting").Placement = App.Placement(
        App.Vector(0, 0, -2), App.Rotation(App.Vector(0, 1, 0), 0))
Beispiel #53
0
    def Activated(self):
        print "Scaling mesh"

        # you might want to change this to where you want your exported mesh/sdf to be located.
        robotName = "testing"
        #projPath = "/home/maiden/Projects/RobotCreator/"+robotName + "/"
        projPath = os.path.expanduser(
            '~') + "/.gazebo/models/" + robotName + "Static/"
        meshPath = projPath + "meshes/"

        if not os.path.exists(projPath):
            os.makedirs(projPath)

        if not os.path.exists(meshPath):
            os.makedirs(meshPath)

        #os.chdir(projectName)

        sdfFile = open(projPath + robotName + 'Static.sdf', 'w')
        sdfFile.write('<?xml version=\"1.0\"?>\n')
        sdfFile.write('<sdf version=\"1.5\">\n')
        sdfFile.write('<model name=\"' + robotName + '\">\n')
        sdfFile.write('<static>true</static>\n')

        objs = FreeCAD.ActiveDocument.Objects
        for obj in objs:
            print obj.Name
            if "Joint" in obj.Name:
                print "Joint: " + obj.Name + " with label " + obj.Label + " detected!"
                pos = obj.Shape.Placement
                pos.Base *= 0.001
                sdfFile.write(' <joint name="' +
                              bodyLabelFromObjStr(obj.Parent) +
                              bodyLabelFromObjStr(obj.Child) +
                              '" type="revolute">\n')
                sdfFile.write('   <pose>' + str(pos.Base[0]) + ' ' +
                              str(pos.Base[1]) + ' ' + str(pos.Base[2]) +
                              ' 0 0 0 </pose>\n')
                sdfFile.write('   <child>' + bodyLabelFromObjStr(obj.Child) +
                              '</child>\n')
                sdfFile.write('   <parent>' + bodyLabelFromObjStr(obj.Parent) +
                              '</parent>\n')
                sdfFile.write('   <axis>')
                sdfFile.write('     <xyz>0 0 1</xyz>')
                sdfFile.write('   </axis>\n')
                sdfFile.write(' </joint>\n')

            if obj.TypeId == 'PartDesign::Body' or obj.TypeId == 'Part::Box':
                print "Link: " + obj.Name + " with label " + obj.Label + " detected!"
                name = obj.Label
                mass = obj.Shape.Mass
                inertia = obj.Shape.MatrixOfInertia
                pos = obj.Shape.Placement
                com = obj.Shape.CenterOfMass
                com *= 0.001
                mass *= 0.001
                A11 = inertia.A11 * 0.000000001
                A12 = inertia.A12 * 0.000000001
                A13 = inertia.A13 * 0.000000001
                A22 = inertia.A22 * 0.000000001
                A23 = inertia.A23 * 0.000000001
                A33 = inertia.A33 * 0.000000001

                pos.Base *= 0.001

                #export shape as mesh (stl)
                obj.Shape.exportStl(meshPath + name + ".stl")
                #import stl and translate/scale
                mesh = Mesh.read(meshPath + name + ".stl")

                # scaling, millimeter -> meter
                mat = FreeCAD.Matrix()
                mat.scale(0.001, 0.001, 0.001)

                #apply scaling
                mesh.transform(mat)

                #move origo to center of mass
                pos.move(com * -1)
                mesh.Placement.Base *= 0.001

                #save scaled and transformed mesh as stl
                mesh.write(meshPath + name + ".stl")

                sdfFile.write('<link name=\"' + name + '\">\n')
                sdfFile.write('<pose> ' + str(0) + ' ' + str(0) + ' ' +
                              str(0) + ' ' + str(deg2rad(pos.Rotation.Q[0])) +
                              ' ' + str(deg2rad(pos.Rotation.Q[1])) + ' ' +
                              str(deg2rad(pos.Rotation.Q[2])) + '</pose>\n')
                sdfFile.write('<inertial>\n')
                sdfFile.write('<pose> ' + str(0 + com.x) + ' ' +
                              str(0 + com.y) + ' ' + str(0 + com.z) + ' ' +
                              str(deg2rad(pos.Rotation.Q[0])) + ' ' +
                              str(deg2rad(pos.Rotation.Q[1])) + ' ' +
                              str(deg2rad(pos.Rotation.Q[2])) + '</pose>\n')
                sdfFile.write('<inertia>\n')
                sdfFile.write('<ixx>' + float_to_str(A11) + '</ixx>\n')
                sdfFile.write('<ixy>' + float_to_str(A12) + '</ixy>\n')
                sdfFile.write('<ixz>' + float_to_str(A13) + '</ixz>\n')
                sdfFile.write('<iyy>' + float_to_str(A22) + '</iyy>\n')
                sdfFile.write('<iyz>' + float_to_str(A23) + '</iyz>\n')
                sdfFile.write('<izz>' + float_to_str(A33) + '</izz>\n')
                sdfFile.write('</inertia>\n')
                sdfFile.write('<mass>' + str(mass) + '</mass>\n')
                sdfFile.write('</inertial>\n')
                sdfFile.write('<collision name=\"collision\">\n')
                sdfFile.write('<geometry>\n')
                sdfFile.write('<mesh>\n')
                sdfFile.write('<uri>model://' + robotName + 'Static/meshes/' +
                              name + '.stl</uri>\n')
                sdfFile.write('</mesh>\n')
                sdfFile.write('</geometry>\n')
                sdfFile.write('</collision>\n')
                sdfFile.write('<visual name=\"visual\">\n')
                sdfFile.write('<geometry>\n')
                sdfFile.write('<mesh>\n')
                sdfFile.write('<uri>model://' + robotName + 'Static/meshes/' +
                              name + '.stl</uri>\n')
                sdfFile.write('</mesh>\n')
                sdfFile.write('</geometry>\n')
                sdfFile.write('</visual>\n')
                sdfFile.write('</link>\n')
        sdfFile.write('</model>\n')
        sdfFile.write('</sdf>\n')

        sdfFile.close()
        return
Beispiel #54
0
 def testSixteenCharGRIDElement(self):
     m = Mesh.read(f"{self.test_dir}/NASTRAN_Test_GRIDSTAR_CQUAD4.bdf")
     self.assertEqual(m.CountPoints, 4)
     self.assertEqual(m.CountFacets, 2)  # Quads split into two triangles
Beispiel #55
0
def old_generate_car(carname, slices):
    docname = carname
    sketchnames = []
    App.newDocument(docname)
    App.setActiveDocument(docname)
    App.ActiveDocument=App.getDocument(docname)
            
    for i in range(10):
        offset = i * 5
        sname = "sketch"+str(i)
        sketchnames.append(sname)
        App.activeDocument().addObject('Sketcher::SketchObject',sname)
        App.activeDocument().getObject(sname).Placement = App.Placement(App.Vector(offset,0.000000,0.000000),App.Rotation(0.500000,0.500000,0.500000,0.500000))
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(0.000000,0.000000,0),App.Vector(30.000000,15.000000,0)))
        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',-1,1,0,1)) 
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(30.000000,15.000000,0),App.Vector(50.000000,15.000000,0)))
        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',0,2,1,1)) 
        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Horizontal',1)) 
        App.ActiveDocument.recompute()
        #App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(50.000000,15.000000,0),App.Vector(71.760025,22.753183,0)))
        y = (random.random()*10) + 12
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(50.000000,15.000000,0),App.Vector(71.760025,y,0)))

        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',1,2,2,1)) 
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(71.760025,y,0),App.Vector(93.929802,26.837082,0)))
        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) 
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(93.929802,26.837082,0),App.Vector(113.765884,28.879032,0)))
        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',3,2,4,1)) 
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(113.765884,28.879032,0),App.Vector(113.474182,0.000000,0)))

        #App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',4,2,5,1)) 
        App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Vertical',5)) 
        App.ActiveDocument.getObject(sname).addGeometry(Part.Line(App.Vector(113.765884,0.000000,0),App.Vector(0.000000,-0.000000,0)))
        App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',5,2,6,1)) 
        App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Coincident',6,2,0,1)) 
        App.ActiveDocument.getObject(sname).addConstraint(Sketcher.Constraint('Horizontal',6))
        App.ActiveDocument.recompute()

    #loft them together
    App.getDocument(carname).addObject('Part::Loft','Loft')
    App.getDocument(carname).getObject('Loft').Sections=[App.getDocument(carname).sketch9, App.getDocument(carname).sketch8, App.getDocument(carname).sketch7, App.getDocument(carname).sketch6, App.getDocument(carname).sketch5, App.getDocument(carname).sketch4, App.getDocument(carname).sketch3, App.getDocument(carname).sketch2, App.getDocument(carname).sketch1, App.getDocument(carname).sketch0, ]

    #sections = [App.getDocument(carname).getProperty(sname) for sname in sketchnames]
    App.getDocument(carname).getObject('Loft').Sections = sections
    App.getDocument(carname).getObject('Loft').Solid=True
    #App.getDocument(carname).getObject('Loft').Ruled=True
    App.getDocument(carname).getObject('Loft').Ruled=False
    App.ActiveDocument.recompute()

    __doc__=FreeCAD.getDocument(docname)
    __doc__.addObject("Part::Mirroring")
    __doc__.ActiveObject.Source=__doc__.getObject("Loft")
    __doc__.ActiveObject.Label="Loft (Mirror #1)"
    __doc__.ActiveObject.Normal=(1,0,0)
    __doc__.ActiveObject.Base=(0,0,0)
    del __doc__
    App.ActiveDocument.recompute()

    App.getDocument(docname).saveAs(carname+'.fcstd')

    __objs__=[]
    __objs__.append(FreeCAD.getDocument(carname).getObject("Loft"))
    __objs__.append(FreeCAD.getDocument(carname).getObject("Part__Mirroring"))
    Mesh.export(__objs__,'./'+carname+".stl")
Beispiel #56
0
    def startElement(self, tag, attributes):

        if tag == "wall":
            name = attributes["id"]
            p1 = FreeCAD.Vector(
                float(attributes["xStart"]) * 10,
                float(attributes["yStart"]) * 10, 0)
            p2 = FreeCAD.Vector(
                float(attributes["xEnd"]) * 10,
                float(attributes["yEnd"]) * 10, 0)
            height = float(attributes["height"]) * 10
            thickness = float(attributes["thickness"]) * 10
            if DEBUG: print "Creating wall: ", name
            line = Draft.makeLine(p1, p2)
            if self.makeIndividualWalls:
                wall = Arch.makeWall(baseobj=line,
                                     width=thickness,
                                     height=height,
                                     name=name)
                wall.Label = name
            else:
                self.lines.setdefault(str(thickness) + ";" + str(height),
                                      []).append(line)

        elif tag == "pieceOfFurniture":
            name = attributes["name"]
            data = self.z.read(attributes["model"])
            th, tf = tempfile.mkstemp(suffix=".obj")
            f = pyopen(tf, "wb")
            f.write(data)
            f.close()
            os.close(th)
            m = Mesh.read(tf)
            fx = (float(attributes["width"]) / 100) / m.BoundBox.XLength
            fy = (float(attributes["height"]) / 100) / m.BoundBox.YLength
            fz = (float(attributes["depth"]) / 100) / m.BoundBox.ZLength
            mat = FreeCAD.Matrix()
            mat.scale(1000 * fx, 1000 * fy, 1000 * fz)
            mat.rotateX(math.pi / 2)
            mat.rotateZ(math.pi)
            if DEBUG: print "Creating furniture: ", name
            if "angle" in attributes.keys():
                mat.rotateZ(float(attributes["angle"]))
            m.transform(mat)
            os.remove(tf)
            p = m.BoundBox.Center.negative()
            p = p.add(
                FreeCAD.Vector(
                    float(attributes["x"]) * 10,
                    float(attributes["y"]) * 10, 0))
            p = p.add(
                FreeCAD.Vector(0, 0, m.BoundBox.Center.z - m.BoundBox.ZMin))
            m.Placement.Base = p
            obj = FreeCAD.ActiveDocument.addObject("Mesh::Feature", name)
            obj.Mesh = m
            self.furniture.append(obj)

        elif tag == "doorOrWindow":
            name = attributes["name"]
            data = self.z.read(attributes["model"])
            th, tf = tempfile.mkstemp(suffix=".obj")
            f = pyopen(tf, "wb")
            f.write(data)
            f.close()
            os.close(th)
            m = Mesh.read(tf)
            fx = (float(attributes["width"]) / 100) / m.BoundBox.XLength
            fy = (float(attributes["height"]) / 100) / m.BoundBox.YLength
            fz = (float(attributes["depth"]) / 100) / m.BoundBox.ZLength
            mat = FreeCAD.Matrix()
            mat.scale(1000 * fx, 1000 * fy, 1000 * fz)
            mat.rotateX(math.pi / 2)
            m.transform(mat)
            b = m.BoundBox
            v1 = FreeCAD.Vector(b.XMin, b.YMin - 500, b.ZMin)
            v2 = FreeCAD.Vector(b.XMax, b.YMin - 500, b.ZMin)
            v3 = FreeCAD.Vector(b.XMax, b.YMax + 500, b.ZMin)
            v4 = FreeCAD.Vector(b.XMin, b.YMax + 500, b.ZMin)
            sub = Part.makePolygon([v1, v2, v3, v4, v1])
            sub = Part.Face(sub)
            sub = sub.extrude(FreeCAD.Vector(0, 0, b.ZLength))
            os.remove(tf)
            shape = Arch.getShapeFromMesh(m)
            if not shape:
                shape = Part.Shape()
                shape.makeShapeFromMesh(m.Topology, 0.100000)
                shape = shape.removeSplitter()
            if shape:
                if DEBUG: print "Creating window: ", name
                if "angle" in attributes.keys():
                    shape.rotate(shape.BoundBox.Center,
                                 FreeCAD.Vector(0, 0, 1),
                                 math.degrees(float(attributes["angle"])))
                    sub.rotate(shape.BoundBox.Center, FreeCAD.Vector(0, 0, 1),
                               math.degrees(float(attributes["angle"])))
                p = shape.BoundBox.Center.negative()
                p = p.add(
                    FreeCAD.Vector(
                        float(attributes["x"]) * 10,
                        float(attributes["y"]) * 10, 0))
                p = p.add(
                    FreeCAD.Vector(
                        0, 0, shape.BoundBox.Center.z - shape.BoundBox.ZMin))
                if "elevation" in attributes.keys():
                    p = p.add(
                        FreeCAD.Vector(0, 0,
                                       float(attributes["elevation"]) * 10))
                shape.translate(p)
                sub.translate(p)
                obj = FreeCAD.ActiveDocument.addObject("Part::Feature",
                                                       name + "_body")
                obj.Shape = shape
                subobj = FreeCAD.ActiveDocument.addObject(
                    "Part::Feature", name + "_sub")
                subobj.Shape = sub
                if FreeCAD.GuiUp:
                    subobj.ViewObject.hide()
                win = Arch.makeWindow(baseobj=obj, name=name)
                win.Label = name
                win.Subvolume = subobj
                self.windows.append(win)
            else:
                print("importSH3D: Error creating shape for door/window " +
                      name)
Beispiel #57
0
 def testCollapseFacetsMultible(self):
     planarMeshObject = Mesh.Mesh(self.planarMesh)
     planarMeshObject.collapseFacets(range(7))
Beispiel #58
0
 def testCTRIA3Element(self):
     m = Mesh.read(f"{self.test_dir}/NASTRAN_Test_GRID_CTRIA3.bdf")
     self.assertEqual(m.CountPoints, 3)
     self.assertEqual(m.CountFacets, 1)
    FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()
else:
    clear_doc()

# Export assembly_global_v2
__objs__ = []

# part_permanent_magnet_neodyme_n40_10mm_40mm - 1
Mesh.insert(u"part_permanent_magnet_neodyme_n40_10mm_40mm.stl",
            "assembly_global_v3")
FreeCADGui.getDocument("assembly_global_v3").getObject(
    "part_permanent_magnet_neodyme_n40_10mm_40mm").ShapeColor = (0.30, 0.60,
                                                                 0.90)
FreeCAD.getDocument("assembly_global_v3").getObject(
    "part_permanent_magnet_neodyme_n40_10mm_40mm").Placement = App.Placement(
        App.Vector(40 * 0, 0, 0), App.Rotation(App.Vector(0, 1, 0), 90))
__objs__.append(
    FreeCAD.getDocument("assembly_global_v3").getObject(
        "part_permanent_magnet_neodyme_n40_10mm_40mm"))

# part_permanent_magnet_neodyme_n40_10mm_40mm - 2
Mesh.insert(u"part_permanent_magnet_neodyme_n40_10mm_40mm.stl",
            "assembly_global_v3")
FreeCADGui.getDocument("assembly_global_v3").getObject(
    "part_permanent_magnet_neodyme_n40_10mm_40mm001").ShapeColor = (0.30, 0.60,
Beispiel #60
0
 def setUp(self):
     self.mesh = Mesh.createBox(1.0, 1.0, 1.0)