Example #1
0
def makeMP4():
    p0 = Base.Vector(-70,-25,0)
    util.makeRef(p0, p0+a3hf, p0+a3hf+a3lf, Base.Vector(0,0,30))
    mp = MiddlePart()
    b = mp.back()
    
    Part.show(b)
Example #2
0
def main():
    doc = App.getDocument("test_birail")
    obj = doc.getObject("Ruled_Surface")
    face = obj.Shape.Face1

    obj = doc.getObject("Spline005")
    e1 = obj.Shape.Edge1
    
    obj = doc.getObject("Spline006")
    e2 = obj.Shape.Edge1

    obj = doc.getObject("Spline007")
    e3 = obj.Shape.Edge1
    
    s2r = SweepOn2Rails()
    s2r.parametrization = 1.0
    s2r.fac = 1.0
    s2r.profileSamples = 100
    s2r.extend = True
    s2r.setRails(face)
    s2r.setProfiles([e1,e2,e3]) #((e1,e2,e3))
    s2r.build()
    #s2r.showLocalProfiles()
    s2r.showInterpoCurves()
    s2r.mix("Rail1")
    Part.show(s2r.shape())
Example #3
0
def makeMP2():
    p0 = Base.Vector(-105,-18,0)
    util.makeRef(p0, p0+a3hf, p0+a3hf+a3lf, Base.Vector(0,0,30))
    mp = MiddlePart()
    p = mp.legHolder()
    #p.rotate(Base.Vector(0), Base.Vector(0,0,1) ,20)
    Part.show(p)
Example #4
0
def mainFrameCoeff(ship, draft):
    """ Calculate main frame coefficient.
    @param ship Selected ship instance
    @param draft Draft.
    @return Main frame coefficient
    """
    cm = 0.0
    maxY = 0.0
    minY = 0.0

    shape = ship.Shape.copy()
    shape.translate(Vector(0.0, 0.0, -draft * Units.Metre.Value))
    x = 0.0
    area = 0.0

    bbox = shape.BoundBox
    xmin = bbox.XMin
    xmax = bbox.XMax

    # Create the "sea" box
    L = xmax - xmin
    B = bbox.YMax - bbox.YMin
    p = Vector(-1.5*L, -1.5*B, bbox.ZMin - 1.0)
    box = Part.makeBox(1.5*L + x, 3.0*B, - bbox.ZMin + 1.0, p)

    maxY = bbox.YMin / Units.Metre.Value
    minY = bbox.YMax / Units.Metre.Value
    for s in shape.Solids:
        try:
            common = box.common(s)
        except:
            continue
        if common.Volume == 0.0:
            continue
        # Recompute the object adding it to the scene. OpenCASCADE must be
        # performing an internal tesellation doing that
        try:
            Part.show(common)
        except:
            continue
        # Divide the solid by faces and filter the well placed ones
        faces = common.Faces
        for f in faces:
            faceBounds = f.BoundBox
            # Orientation filter
            if faceBounds.XMax - faceBounds.XMin > 0.00001:
                continue
            # Position filter
            if abs(faceBounds.XMax - x) > 0.00001:
                continue

            area = area + f.Area / Units.Metre.Value**2
            maxY = max(maxY, faceBounds.YMax / Units.Metre.Value)
            minY = min(minY, faceBounds.YMin / Units.Metre.Value)
        App.ActiveDocument.removeObject(App.ActiveDocument.Objects[-1].Name)

    dy = maxY - minY
    if dy * draft > 0.0:
        cm = area / (dy * draft)
    return cm
Example #5
0
def mainFrameCoeff(ship, draft):
	""" Calculate main frame coefficient.
	@param ship Selected ship instance
	@param draft Draft.
	@return Main frame coefficient
	"""
	cm	 = 0.0
	maxY = 0.0
	minY = 0.0
	# We will take a duplicate of ship shape in order to place it
	shape = ship.Shape.copy()
	shape.translate(Vector(0.0,0.0,-draft))
	x	 = 0.0
	area = 0.0
	# Now we need to know the x range of values
	bbox = shape.BoundBox
	xmin = bbox.XMin
	xmax = bbox.XMax
	# Create the box
	L = xmax - xmin
	B = bbox.YMax - bbox.YMin
	p = Vector(-1.5*L, -1.5*B, bbox.ZMin - 1.0)
	box = Part.makeBox(1.5*L + x, 3.0*B, - bbox.ZMin + 1.0, p)
	maxY = bbox.YMin
	minY = bbox.YMax
	# Compute common part with ship
	for s in shape.Solids:
		# Get solids intersection
		try:
			common = box.common(s)
		except:
			continue
		if common.Volume == 0.0:
			continue
		# Recompute object adding it to the scene, when we have
		# computed desired data we can remove it.
		try:
			Part.show(common)
		except:
			continue
		# Divide by faces and compute only section placed ones
		faces  = common.Faces
		for f in faces:
			faceBounds = f.BoundBox
			# Orientation filter
			if faceBounds.XMax - faceBounds.XMin > 0.00001:
				continue
			# Place filter
			if abs(faceBounds.XMax - x) > 0.00001:
				continue
			# Valid face, compute area
			area = area + f.Area
			maxY = max(maxY, faceBounds.YMax)
			minY = min(minY, faceBounds.YMin)
		# Destroy last object generated
		App.ActiveDocument.removeObject(App.ActiveDocument.Objects[-1].Name)
	dy = maxY - minY
	if dy*draft > 0.0:
		cm = area / (dy*draft)
	return cm
def makeCylinder(p1,p2,p3,p4):
	s=Part.makePolygon([p1,p2,p3,p1])
	f=Part.makeFilledFace(s.Edges)
	n=f.Faces[0].normalAt(0,0)
	# Drehung 
	n2=FreeCAD.Vector(0,0,1)
	r=FreeCAD.Rotation(n,n2)


	k1=r.multVec(p1)
	sp1=sympy.point.Point2D(k1.x,k1.y)
	z=k1.z
	sp1
	k2=r.multVec(p2)
	sp2=sympy.point.Point2D(k2.x,k2.y)
	sp2
	k3=r.multVec(p3)
	sp3=sympy.point.Point2D(k3.x,k3.y)
	sp3

	k4=r.multVec(p4)
	sp4=sympy.point.Point2D(k4.x,k4.y)
	sp4

	t=sympy.Triangle(sp1,sp2,sp3)
	rad=t.circumradius.evalf()
	center=t.circumcenter
	print rad
	print center
	x=center.x.evalf()
	y=center.y.evalf()

	circ=Part.makeCircle(rad,FreeCAD.Vector(x,y,z))
	Part.show(circ)
	cb=App.ActiveDocument.ActiveObject


	h=k4.z-k3.z

	# und wieder zurueck
	r2=FreeCAD.Rotation(n2,n)

	ex=App.ActiveDocument.addObject("Part::Extrusion","Extrude")
	ex.Base = cb
	ex.Dir = (0,0,h)
	ex.Solid = (True)
	ex.Placement.Rotation=r2
	ex.ViewObject.Transparency=80

	cb.ViewObject.hide()


	s2=Part.makePolygon([p1,p2,p3,p4])
	Part.show(s2)
	for p in [p1,p2,p3,p4]:
		k1=App.ActiveDocument.addObject("Part::Sphere","Sphere")
		k1.Placement.Base=p
		k1.Radius=0.5
		k1.ViewObject.ShapeColor=(1.0,0.0,0.0)
		App.activeDocument().recompute()
Example #7
0
 def update(self, draft, trim, ship):
     """ Update free surface 3D view
     @param traft Draft.
     @param trim Trim in degrees.
     """
     # Destroy old object if exist
     self.clean()
     # Set free surface bounds
     bbox = ship.Shape.BoundBox
     L = 1.5 * bbox.XLength
     B = 3.0 * bbox.YLength
     # Create plane
     x = - 0.5 * L
     y = - 0.5 * B
     point = Base.Vector(x,y,0.0)
     plane = Part.makePlane(L,B, point, Base.Vector(0,0,1))
     # Set position
     plane.rotate(Base.Vector(0,0,0), Base.Vector(0,1,0), trim)
     plane.translate(Base.Vector(0,0,draft))
     # Create the FreeCAD object
     Part.show(plane)
     objs = FreeCAD.ActiveDocument.Objects
     self.obj = objs[len(objs)-1]
     self.obj.Label = 'FreeSurface'
     # Set properties of object
     guiObj = FreeCADGui.ActiveDocument.getObject(self.obj.Name)
     guiObj.ShapeColor = (0.4,0.8,0.85)
     guiObj.Transparency = 50
Example #8
0
def makeSnapshotWithGui():
	from PyQt4 import QtGui
	import FreeCADGui

	def getMainWindow():
		toplevel = QtGui.qApp.topLevelWidgets()
		for i in toplevel:
			if i.metaObject().className() == "Gui::MainWindow":
				return i
		raise Exception("No main window found")

	mw=getMainWindow()
	mw.hide()
	#mw.showMinimized()

	# Create a test geometry and add it to the document
	obj=Part.makeCone(10,8,10)
	doc = FreeCAD.newDocument()
	Part.show(obj)

	# switch off animation so that the camera is moved to the final position immediately
	view = FreeCADGui.getDocument(doc.Name).activeView()
	view.setAnimationEnabled(False)
	view.viewAxometric()
	view.fitAll()
	view.saveImage('crystal.png',800,600,'Current')
	FreeCAD.closeDocument(doc.Name)
	# close the application
	QtGui.qApp.quit()
Example #9
0
def makeRef(p1, p2, p3, border):
        p4 = p1 + (p3 - p2)

        lines = linesFromPoints([p1, p2, p3, p4], True)
        w = Part.Wire(lines)
        p = w.extrude(border)
        Part.show(p)
def generate_bspline_patch(vertices, n_nodes, degree, knots):
	"""
	Generates a bspine patch from the given vertices. Parameters like degree of the patch, knot vector and number of
	control points are defined above.
	:param vertices: lexicographically numbered control points in a 2D Array of 3 component points
	"""
	n_nodes_u = n_nodes
	n_nodes_v = n_nodes
	degree_u = degree
	degree_v = degree
	knot_u = knots
	knot_v = knots

	patch = Part.BSplineSurface()
	patch.increaseDegree(degree_u, degree_v)

	for i in range(4, len(knot_u)-4):
		patch.insertUKnot(knot_u[i], 1, 0) # todo why is the second argument equal to 1? If anyone could explain = awesome
	for i in range(4, len(knot_v)-4):
		patch.insertVKnot(knot_v[i], 1, 0) # todo why is the second argument equal to 1? If anyone could explain = awesome

	for ii in range(0, n_nodes_u):
		for jj in range(0, n_nodes_v):
			k = ii + jj * n_nodes_u
			v = vertices[k]
			control_point = FreeCAD.Vector(v[0], v[1], v[2])
			patch.setPole(ii + 1, jj + 1, control_point, 1)
			if(PLOT_CONTROL_POINTS):
				Part.show(Part.Vertex(control_point))  # plotting corresponding control points, switched on/off in configuration section

	return patch.toShape()
def process_nonchanging_domains(nonchanging_file_name, output_file_name, refinement_level):
	if len(nonchanging_file_name) != 0:
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")
		
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
Example #12
0
def show(parts):
    if(type(parts) == type([])):
        for p in parts:
            Part.show(p)
        pass
    else:
        Part.show(parts)
def process_nonchanging_domains(nonchanging_file_name, output_file_name):
	if len(nonchanging_file_name) != 0:

		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()
		len_original =len(__objs_original__)
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
Example #14
0
def gen_haus(le,wi,hiall,hi,ang,midx=0.7,wx=0.5,midy=0.5,wy=0):
	h=gen_haus0(le,wi,hiall,hi,midx,wx,midy,wy)
	print h
	Part.show(h)
	p=FreeCAD.ActiveDocument.ActiveObject
	p.Placement.Rotation.Angle=ang*math.pi/180
	return p
def showFace(rbf,rbf2,x,y,gridsize,shapeColor,bound):

	import Draft
	grids=gridsize

	ws=[]

	pts2=[]
	xi, yi = np.linspace(np.min(x), np.max(x), grids), np.linspace(np.min(y), np.max(y), grids)

	for ix in xi:
		points=[]
		for iy in yi:
#			print (ix,iy, rbf(ix,iy))
			iz=float(rbf(ix,iy))

#---------------------- special hacks #+#
			if bound>0:
				if iz > bound: iz = bound
				if iz < -bound: iz = -bound
#			print (ix,iy,iz)
#			if abs(ix)>20 or abs(iy)>20: 
#					iz=0

#			if ix==np.max(x) or ix==np.min(x) or iy==np.max(y) or iy==np.min(y): 
#					iz=0

#---------------------- end hack 


#			if rbf2<>None:
#				iz -= float(rbf2(ix,iy))

			points.append(FreeCAD.Vector(iy,ix,iz))
		w=Draft.makeWire(points,closed=False,face=False,support=None)
		ws.append(w)
		pts2.append(points)

#-		FreeCAD.activeDocument().recompute()
#-		FreeCADGui.updateGui()
#-		Gui.SendMsgToActiveView("ViewFit")

	ll=FreeCAD.activeDocument().addObject('Part::Loft','elevation')
	ll.Sections=ws
	ll.Ruled = True
	ll.ViewObject.ShapeColor = shapeColor
	ll.ViewObject.LineColor = (0.00,0.67,0.00)

	for w in ws:
		w.ViewObject.Visibility=False


	ll.Label="Interpolation Gitter " + str(grids)

	bs=Part.BSplineSurface()
#	print "Points --"
#	print pts2
	bs.interpolate(pts2)
	Part.show(bs.toShape())
Example #16
0
def main(filename,canny1=100,canny2=200,rho=1,theta=1, threshold=10, minLineLength =25, maxLineGap =10,
			showimage=False,showimagewithlines=False,newDocument=True):
# def main(f):
	f=filename
	im = cv2.imread(f)
	gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
	edges = cv2.Canny(gray,canny1,canny2)

	xsize=len(im[0])
	ysize=len(im)

#image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]])
	lines = cv2.HoughLinesP(edges,1,np.pi/180*theta,threshold, minLineLength = minLineLength, maxLineGap = maxLineGap)
#	lines = cv2.HoughLinesP(edges,1,np.pi/180,10, minLineLength = 25, maxLineGap = 10)
	#lines = cv2.HoughLinesP(edges,1,np.pi/2,2)[0]

	k=0
	fclines=[]

	for l in lines:
		k += 1
		[[x1,y1,x2,y2]] = l       
		fl=fclinev2(x1,-y1,x2,-y2)
		fclines.append(fl)
		#print (x1,y1,x2,y2)
		a=cv2.line(im,(x1,y1),(x2,y2),(0,255,255),2)

	c=Part.makeCompound(fclines)
	c.Placement.Base=FreeCAD.Vector(-xsize/2*scaler,ysize/2*scaler,0)
	if newDocument:
		d=App.newDocument("HoughLines")
#		App.setActiveDocument("Unnamed1")
#		App.ActiveDocument=d
#		Gui.ActiveDocument=Gui.getDocument("Unnamed1")
		
	Part.show(c)

	cv2.imwrite('/tmp/out.png',im)

	import Image, ImageGui
	#ImageGui.open(unicode("/tmp/out.png","utf-8"))

	if showimage:
		fimg=App.activeDocument().addObject('Image::ImagePlane','Image 2')
		fimg.Label=f
		fimg.ImageFile = f
		fimg.XSize = xsize*scaler
		fimg.YSize = ysize*scaler
		fimg.Placement.Base.z=-5

	if showimagewithlines:
		fimg=App.activeDocument().addObject('Image::ImagePlane','Image with Houghlines')
		fimg.ImageFile = '/tmp/out.png'
		fimg.XSize = xsize*scaler
		fimg.YSize = ysize*scaler
		fimg.Placement.Base.z=-10
		FreeCADGui.SendMsgToActiveView("ViewFit")

	print ("lines:",k)
Example #17
0
	def update(self, L, B, T):
		""" Update the 3D view printing annotations.
		@param L Ship length.
		@param B Ship beam.
		@param T Ship draft.
		"""
		# Destroy all previous entities
		self.clean()
		# Draw base line
		xStart   = -0.6*L;
		xEnd	 =  0.6*L;
		baseLine = Part.makeLine((xStart,0,0),(xEnd,0,0))
		Part.show(baseLine)
		objs = FreeCAD.ActiveDocument.Objects
		self.baseLine = objs[len(objs)-1]
		self.baseLine.Label = 'BaseLine'
		text = str(QtGui.QApplication.translate("ship_create","Base line",
												None,QtGui.QApplication.UnicodeUTF8))
		self.baseLineLabel = DrawText('BaseLineText', text, Base.Vector(xEnd,0,0))
		# Draw free surface
		fsLine = Part.makeLine((xStart,0,T),(xEnd,0,T))
		Part.show(fsLine)
		objs = FreeCAD.ActiveDocument.Objects
		self.fsLine = objs[len(objs)-1]
		self.fsLine.Label = 'FreeSurface'
		text = str(QtGui.QApplication.translate("ship_create","Free surface",
												None,QtGui.QApplication.UnicodeUTF8))
		self.fsLineLabel = DrawText('FSText', text, Base.Vector(xEnd,0,T))
		# Draw forward perpendicular
		zStart = -0.1*T
		zEnd   =  1.1*T
		fpLine = Part.makeLine((0.5*L,0,zStart),(0.5*L,0,zEnd))
		Part.show(fpLine)
		objs = FreeCAD.ActiveDocument.Objects
		self.fpLine = objs[len(objs)-1]
		self.fpLine.Label = 'ForwardPerpendicular'
		text = str(QtGui.QApplication.translate("ship_create","Forward perpendicular",
												None,QtGui.QApplication.UnicodeUTF8))
		self.fpLineLabel = DrawText('FPText', text, Base.Vector(0.5*L,0,zEnd))
		# Draw after perpendicular
		apLine = Part.makeLine((-0.5*L,0,zStart),(-0.5*L,0,zEnd))
		Part.show(apLine)
		objs = FreeCAD.ActiveDocument.Objects
		self.apLine = objs[len(objs)-1]
		self.apLine.Label = 'AfterPerpendicular'
		text = str(QtGui.QApplication.translate("ship_create","After perpendicular",
												None,QtGui.QApplication.UnicodeUTF8))
		self.apLineLabel = DrawText('APText', text, Base.Vector(-0.5*L,0,zEnd))
		# Draw amin frame
		amLine = Part.makeLine((0,-0.5*B,zStart),(0,-0.5*B,zEnd))
		Part.show(amLine)
		objs = FreeCAD.ActiveDocument.Objects
		self.amLine = objs[len(objs)-1]
		self.amLine.Label = 'AminFrame'
		text = str(QtGui.QApplication.translate("ship_create","Main frame",
												None,QtGui.QApplication.UnicodeUTF8))
		self.amLineLabel = DrawText('AMText', text, Base.Vector(0,-0.5*B,zEnd))
Example #18
0
 def makeAll2(self, toCut=False):
     parts = self.makeAll()
     tr = Base.Vector(-215,0,-45)
     for p in parts:
         p.translate(tr)
         p.rotate(Base.Vector(0,0,0), Base.Vector(0,1,0), -20)
         p.translate(Base.Vector(123,0,0))
         Part.show(p)
     return parts
def plane(start, l, w):
    p1 = FreeCAD.Vector(start[0],start[1],start[2])
    p2 = FreeCAD.Vector(start[0]+l,start[1],start[2])
    p3 = FreeCAD.Vector(start[0]+l,start[1]+w,start[2])
    p4 = FreeCAD.Vector(start[0],start[1]+w,start[2])
    pointslist = [p1, p2, p3, p4, p1]
    mywire = Part.makePolygon(pointslist)
    myface = Part.Face(mywire)
    Part.show(myface)
Example #20
0
    def showLine(self,l,dist=None):
        v1 = Base.Vector(l.p0[0], 0 , l.p0[1])
        if dist==None:
            v2 = Base.Vector(l.p0[0] + l.direction[0], 0 , l.p0[1] + l.direction[1])
        else:
            p = l.pointAtDist(dist)
            v2 = Base.Vector(p[0],0,p[1])

        s1 = Part.Shape([Part.Line(v1,v2)])
        Part.show(s1)
Example #21
0
 def makeBorder(self):
     l = 750
     h = 500
     p1 = Base.Vector(-10,0,-10)
     p2= p1 + Base.Vector(l,0,0)
     p3= p1 + Base.Vector(l,0,h)
     p4= p1 + Base.Vector(0,0,h)
     
     lines = util.linesFromPoints([p1,p2,p3,p4],True)
     Part.show(Part.Wire(lines))
Example #22
0
	def showpath(self):
		''' path as Part.polygon '''
		FreeCAD.s=self
		points=self.Object.Proxy.path
		for p in self.Object.Proxy.path:
			say(str(p))
		pp=Part.makePolygon(points)
		Part.show(pp)
		FreeCAD.ActiveDocument.recompute()
		return FreeCAD.activeDocument().ActiveObject
Example #23
0
def generate_quad(vertices):
    edges = 4 * [None]
    for i in range(4):
        edges[i] = Part.makeLine(tuple(vertices[i]),tuple(vertices[(i+1)%4]))

    wires = 4 * [None]
    wires[0] = Part.Wire([edges[0],edges[3]])
    wires[1] = Part.Wire([edges[2],edges[1]])
    wires[2] = Part.Wire([wires[0],wires[1]])
    Part.show(wires[2])
Example #24
0
def makePrism(l):
	print l
	hp=l[-1]
	p1=l[0]
	bl=l[:-1]
	bl.append(p1)
	print bl
	
	s=Part.makePolygon(bl)
	f=Part.makeFilledFace(s.Edges)
	Part.show(f)
	cb=App.ActiveDocument.ActiveObject
	cb.Label="Prism Bottom Face"
	cb.ViewObject.hide()

	n=f.Faces[0].normalAt(0,0)
	n2=FreeCAD.Vector(0,0,1)
	r=FreeCAD.Rotation(n,n2)


	k1=r.multVec(p1)
	sp1=sympy.point.Point2D(k1.x,k1.y)
	z=k1.z
	sp1


	k4=r.multVec(hp)
	sp4=sympy.point.Point2D(k4.x,k4.y)
	sp4

	bl2=[]
	for p in bl:
		k=r.multVec(p)
		bl2.append(k)

	s=Part.makePolygon(bl2)
	f=Part.makeFilledFace(s.Edges)
	Part.show(f)
	cb=App.ActiveDocument.ActiveObject
	cb.Label="Prism Bottom Face Helper"
	cb.ViewObject.hide()

	h=k4.z-k1.z

	# und wieder zurueck
	r2=FreeCAD.Rotation(n2,n)

	ex=App.ActiveDocument.addObject("Part::Extrusion","Extrude")
	ex.Base = cb
	ex.Dir = (0,0,h)
	ex.Solid = (True)
	ex.Placement.Rotation=r2
	ex.ViewObject.Transparency=80
	ex.Label="Prism"
	App.activeDocument().recompute()
def process_allowed_domains(allowed_domains_file_name, output_file_name, refinement_level):
	if len(allowed_domains_file_name) != 0:
		print "Checking allowed domains..."
		# take the intersection of allowed domains
		# read in step file for allowed domains
		Import.insert(allowed_domains_file_name, "tmp")
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# get bounding box of the allowed domains
		# NOTE: ASSUMING ALLOWED DOMAINS ARE ALL FUSED IN ONE OBJECT.
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# create mega BB object
		create_mega_bounding_box_object()

		# cut out allowed domains from mega BB object
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
		FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument("tmp").Objects[-3]
		FreeCAD.getDocument("tmp").recompute()
		#Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# cut out not-allowed parts
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
		FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument("tmp").Objects[0]
		FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").recompute()
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove everything except the last cut-object
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		print __objs__

		if len(__objs__) > 1:
			# create a fuse object and union all "Common"s
			FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
			FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1: len(__objs__)]
			print FreeCAD.getDocument("tmp").Fuse.Shapes
			FreeCAD.getDocument("tmp").recompute()

			# remove "Commons"s
			for i in range(0, len(__objs__)):
				FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
Example #26
0
    def _punch_holes(self):
        FreeCAD.Console.PrintMessage("- Punching holes ... ")
        FreeCADGui.updateGui()

        grid = self.cylinder.cut(self.punch_tool.Shape)

        Part.show(grid)
        FreeCAD.ActiveDocument.removeObject(self.punch_tool.Name)

        FreeCAD.ActiveDocument.recompute()
        FreeCAD.Console.PrintMessage("OK\n")
Example #27
0
    def Activated(self):
        doc = FreeCAD.ActiveDocument
        pg = FreeCAD.ParamGet("User parameter:Plugins/MeshRemodel")
        line_width = pg.GetFloat("LineWidth", 5.0)
        point_size = pg.GetFloat("PointSize", 4.0)
        #QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        #add_varargs_method("makeCircle",&Module::makeCircle,
        #    "makeCircle(radius,[pnt,dir,angle1,angle2]) -- Make a circle with a given radius\n"
        #    "By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0 and angle2=360"
        #);

        modifiers = QtGui.QApplication.keyboardModifiers()
        poly = Part.makePolygon(self.pts)
        #Part.show(poly)
        normal = DraftGeomUtils.getNormal(poly)

        A = self.pts[0]
        B = self.pts[1]
        C = self.pts[2]

        if gu.isColinear(A, B, C):
            FreeCAD.Console.PrintError(
                "MeshRemodel Error: Cannot make arc/circle from 3 colinear points\n"
            )
            return

        center = gu.circumcenter(A, B, C)
        radius = gu.circumradius(A, B, C)

        doc.openTransaction("Create circle")
        circle = Part.makeCircle(radius, center, normal)
        circName = "MR_Ref"
        if not modifiers == QtCore.Qt.ShiftModifier.__or__(
                QtCore.Qt.ControlModifier):
            Part.show(circle, "MR_Circle")
            circName = doc.ActiveObject.Name
            doc.ActiveObject.ViewObject.LineWidth = line_width
            FreeCAD.Console.PrintMessage(circName + ": radius = " +
                                         str(radius) + "\n  center at " +
                                         str(center) + "\n")
            Gui.Selection.clearSelection()
            Gui.Selection.addSelection(doc.getObject(circName))
        if modifiers == QtCore.Qt.ControlModifier or modifiers == QtCore.Qt.ControlModifier.__or__(
                QtCore.Qt.ShiftModifier):
            Part.show(
                Part.Point(center).toShape(), circName + "_Ctr"
            )  #show the center point on ctrl click or shift+ctrl click
            doc.ActiveObject.ViewObject.PointSize = point_size

        doc.recompute()
        doc.commitTransaction()
        #QtGui.QApplication.restoreOverrideCursor()
        return
Example #28
0
def showShapes(shapes):
    '''Показывает фигуры из массива
       для точек создает сферы с радиусом=3
    '''
    if type(shapes) not in (list, tuple): shapes = [shapes]

    for s in shapes:
        if s.__class__.__name__ == 'Vector':
            Part.show(Part.makeSphere(3, s), 'Point')
        else:
            Part.show(s, s.ShapeType)
 def getpoint(self, event_cb):
     event = event_cb.getEvent()
     if event.getState() == SoMouseButtonEvent.DOWN:
         pos = event.getPosition()
         point = self.view.getPoint(pos[0], pos[1])
         self.stack.append(point)
         if len(self.stack) == 2:
             l = Part.LineSegment(self.stack[0], self.stack[1])
             shape = l.toShape()
             Part.show(shape)
             self.view.removeEventCallbackPivy(SoMouseButtonEvent.getClassTypeId(), self.callback)
Example #30
0
def draw_box():
    #pts = [getPoint(-0.5,-0.5), getPoint(0.5,-0.5), getPoint(0.5,0.5), getPoint(-0.5,0.5), getPoint(-0.5,-0.5)]
    pts = [
        getPoint(0, 0),
        getPoint(1, 0),
        getPoint(1, 1),
        getPoint(0, 1),
        getPoint(0, 0)
    ]
    poly = Part.makePolygon(pts)
    Part.show(poly)
Example #31
0
def process_allowed_domains(allowed_domains_file_name, output_file_name):
    if len(allowed_domains_file_name) != 0:
        print "Checking allowed domains..."
        # take the intersection of allowed domains
        # read in step file for allowed domains

        __objs_original__ = FreeCAD.getDocument("tmp").findObjects()

        Import.insert(allowed_domains_file_name, "tmp")
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        # create mega BB object
        create_mega_bounding_box_object()

        # cut out allowed domains from mega BB object
        FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
        FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument(
            "tmp").Objects[-2]
        FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument(
            "tmp").Objects[-3]
        FreeCAD.getDocument("tmp").recompute()
        #Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # cut out not-allowed parts
        FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
        FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument(
            "tmp").Objects[0]
        FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument(
            "tmp").Objects[-2]
        FreeCAD.getDocument("tmp").recompute()
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # remove everything except the last cut-object
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        for i in range(0, len(__objs__) - 1):
            FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        # update __objs__
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        if len(__objs__) > 1:
            # create a fuse object and union all "Common"s
            FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
            FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1:len(__objs__)]
            print FreeCAD.getDocument("tmp").Fuse.Shapes
            FreeCAD.getDocument("tmp").recompute()

            # remove "Commons"s
            for i in range(0, len(__objs__)):
                FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        # update __objs__
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
Example #32
0
    def draw(self):

        #for pipe_obj in self.pipe_obj_list:
        #    Part.show(pipe_obj[0]) #outer cylinderの描画
        #    Part.show(pipe_obj[1]) #inner cylinderの描画

        for pipe_obj in self.subtructed_pipe_obj_list:
            Part.show(pipe_obj)

        for frange_obj in self.frange_obj_list:
            Part.show(frange_obj)
Example #33
0
def makePrism(l):
    print(l)
    hp = l[-1]
    p1 = l[0]
    bl = l[:-1]
    bl.append(p1)
    print(bl)

    s = Part.makePolygon(bl)
    f = Part.makeFilledFace(s.Edges)
    Part.show(f)
    cb = App.ActiveDocument.ActiveObject
    cb.Label = "Prism Bottom Face"
    cb.ViewObject.hide()

    n = f.Faces[0].normalAt(0, 0)
    n2 = FreeCAD.Vector(0, 0, 1)
    r = FreeCAD.Rotation(n, n2)

    k1 = r.multVec(p1)
    sp1 = sympy.point.Point2D(k1.x, k1.y)
    z = k1.z
    sp1

    k4 = r.multVec(hp)
    sp4 = sympy.point.Point2D(k4.x, k4.y)
    sp4

    bl2 = []
    for p in bl:
        k = r.multVec(p)
        bl2.append(k)

    s = Part.makePolygon(bl2)
    f = Part.makeFilledFace(s.Edges)
    Part.show(f)
    cb = App.ActiveDocument.ActiveObject
    cb.Label = "Prism Bottom Face Helper"
    cb.ViewObject.hide()

    h = k4.z - k1.z

    # und wieder zurueck
    r2 = FreeCAD.Rotation(n2, n)

    ex = App.ActiveDocument.addObject("Part::Extrusion", "Extrude")
    ex.Base = cb
    ex.Dir = (0, 0, h)
    ex.Solid = (True)
    ex.Placement.Rotation = r2
    ex.ViewObject.Transparency = 80
    ex.Label = "Prism"
    App.activeDocument().recompute()
Example #34
0
def GIS2BIM_FreeCAD_3DBuildings(curves3DBAG, heightData3DBAG):
    for i, j, k in zip(curves3DBAG, heightData3DBAG[1], heightData3DBAG[2]):
        pointlist = []
        for curve in i:
            pointlist.append(
                FreeCAD.Vector(curve[0], curve[1],
                               float(j) * 1000))
        a = Part.makePolygon(pointlist)
        face = Part.Face(a)
        solid = face.extrude(FreeCAD.Vector(0, 0, float(k) * 1000))
        Part.show(solid)
    return solid
Example #35
0
def showVector(point, vector, name=None, color=None):
    ''' showVector(startPoint, Vector)
        показывает Vector из startPoint
    '''
    line = Part.makeLine(point, point + vector)
    if name:
        Part.show(line, name)
    else:
        Part.show(line)

    if color:
        App.ActiveDocument.Objects[-1].ViewObject.LineColor = color
Example #36
0
    def Activated(self):
        try:
            oneObject = False
            selected = Gui.Selection.getSelectionEx()
            selectedOne1 = Gui.Selection.getSelectionEx()[0]
            selectedOne2 = Gui.Selection.getSelectionEx()[0]
            selectedOne3 = Gui.Selection.getSelectionEx()[0]
            allSelected = []
            if ((len(selected) < 3 or len(selected) > 3)
                    and (selectedOne1.HasSubObjects == False
                         or selectedOne2.HasSubObjects == False
                         or selectedOne3.HasSubObjects == False)):
                # Two object must be selected
                errMessage = "Select two or more objects to useArc3Points Tool"
                faced.getInfo(selected).errorDialog(errMessage)
                return
            if selectedOne1.HasSubObjects and len(selected) == 1:
                # We have only one object that we take vertices from
                oneObject = True
                subObjects = selected[0].SubObjects
                for n in subObjects:
                    allSelected.append(n.Point)
            elif len(selected) == 3:
                for t in selected:
                    allSelected.append(
                        t.Object.Shape.Vertexes[0].Placement.Base)
                    print(len(allSelected))
            else:
                oneObject = False
                print("A combination of objects")
                print("Not implemented")
                return
            C1 = _part.Arc(App.Vector(allSelected[0]),
                           App.Vector(allSelected[1]),
                           App.Vector(allSelected[2]))
            S1 = _part.Shape([C1])
            W = _part.Wire(S1.Edges)
            _part.show(W)
            App.ActiveDocument.recompute()
            App.ActiveDocument.ActiveObject.Label = "Arc_3_Points"
            # Remove only if it is not one object
            if oneObject == False:
                for n in selected:
                    App.ActiveDocument.removeObject(n.ObjectName)
            del allSelected[:]
            App.ActiveDocument.recompute()

        except Exception as err:
            App.Console.PrintError("'Arc3Points' Failed. "
                                   "{err}\n".format(err=str(err)))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
Example #37
0
 def Activated(self):
     TEST = 0
     if TEST:
         v1 = FreeCAD.Vector(20, 10, 10.0)
         v2 = FreeCAD.Vector(30, 10, 10)
         v3 = FreeCAD.Vector(25, 15, 10)
         ps = [v1, v2, v1, v3, v2, v3]
         p = Part.makePolygon(ps)
         Part.show(p)
         self.ff(v1, v2, v3)
     else:
         self.main()
Example #38
0
    def clicked(self, index, previewDocName = "Viewer"):
        import Part, FreeCADGui, zipfile, tempfile, os
        self.previewOn = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM").GetBool("3DPreview",False)
        try:
            self.path = self.dirmodel.filePath(index)
        except:
            self.path = self.previousIndex
            print(self.path)
        self.isFile = os.path.isfile(self.path)
        # if the 3D preview checkbox is on ticked, show the preview
        if self.previewOn == True or self.linked == True:
            if self.isFile == True:
                # close a non linked preview document
                if self.linked == False:
                    try:
                        FreeCAD.closeDocument(self.previewDocName)
                    except:
                        pass
                # create different kinds of previews based on file type
                if self.path.lower().endswith(".stp") or self.path.lower().endswith(".step") or self.path.lower().endswith(".brp") or self.path.lower().endswith(".brep"):
                    self.previewDocName = "Viewer"
                    FreeCAD.newDocument(self.previewDocName)
                    FreeCAD.setActiveDocument(self.previewDocName)
                    Part.show(Part.read(self.path))
                    FreeCADGui.SendMsgToActiveView("ViewFit")
                elif self.path.lower().endswith(".fcstd"):
                    openedDoc = FreeCAD.openDocument(self.path)
                    FreeCADGui.SendMsgToActiveView("ViewFit")
                    self.previewDocName = FreeCAD.ActiveDocument.Name
                    thumbnailSave = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM").GetBool("SaveThumbnails",False)
                    if thumbnailSave == True:
                        FreeCAD.ActiveDocument.save()
        if self.linked == False:
            self.previousIndex = self.path

        # create a 2D image preview
        if self.path.lower().endswith(".fcstd"):
            zfile=zipfile.ZipFile(self.path)
            files=zfile.namelist()
            # check for meta-file if it's really a FreeCAD document
            if files[0] == "Document.xml":
                image="thumbnails/Thumbnail.png"
                if image in files:
                    image=zfile.read(image)
                    thumbfile = tempfile.mkstemp(suffix='.png')[1]
                    thumb = open(thumbfile,"wb")
                    thumb.write(image)
                    thumb.close()
                    im = QtGui.QPixmap(thumbfile)
                    self.form.framePreview.setPixmap(im)
                    return self.previewDocName, self.previousIndex, self.linked
        self.form.framePreview.clear()
        return self.previewDocName, self.previousIndex, self.linked
Example #39
0
def extractWires():
    '''extract the wires'''
    sel = Gui.Selection.getSelection()
    w = sel[0]
    print w.Shape.Wires
    for i, wire in enumerate(w.Shape.Wires):
        Part.show(wire)
        App.ActiveDocument.ActiveObject.Label = "wire " + str(
            i + 1) + " for " + w.Label + " "
        wire.reverse()
        Part.show(wire)
        App.ActiveDocument.ActiveObject.Label = "wire " + str(
            i + 1) + " for " + w.Label + " reverse "
Example #40
0
def generate_bezier_patch(degree, vertices):
    patch = Part.BezierSurface()
    patch.increase(degree,degree)

    for i in range(degree+1):
        for j in range(degree+1):
            k = i+j*(degree+1)
            v = vertices[k]
            control_point = FreeCAD.Vector(v[0],v[1],v[2])
            patch.setPole(i+1,j+1,control_point)
            #Part.show(Part.Vertex(control_point))

    Part.show(patch.toShape())
Example #41
0
 def update(self, names, pos):
     """ Update the 3D view printing annotations.
     @param names Weight names.
     @param pos Weight positions (FreeCAD::Base::Vector).
     """
     # Destroy all previous entities
     self.clean()
     for i in range(0, len(names)):
         # Draw gravity line
         line = Part.makeLine((pos[i].x, pos[i].y, pos[i].z),
                              (pos[i].x, pos[i].y, pos[i].z - 9.81))
         Part.show(line)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'Line'
         # Draw circles
         circle = Part.makeCircle(0.5, pos[i], Base.Vector(1.0, 0.0, 0.0))
         Part.show(circle)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'CircleX'
         circle = Part.makeCircle(0.5, pos[i], Base.Vector(0.0, 1.0, 0.0))
         Part.show(circle)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'CircleY'
         circle = Part.makeCircle(0.5, pos[i], Base.Vector(0.0, 0.0, 1.0))
         Part.show(circle)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'CircleZ'
         # Draw annotation
         self.objects.append(
             DrawText(names[i] + 'Text', names[i],
                      Base.Vector(pos[i].x + 1.0, pos[i].y, pos[i].z)))
def process_allowed_domains(allowed_domains_file_name, output_file_name):
	if len(allowed_domains_file_name) != 0:
		print "Checking allowed domains..."
		# take the intersection of allowed domains
		# read in step file for allowed domains
		
		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()

		Import.insert(allowed_domains_file_name, "tmp")
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create mega BB object
		create_mega_bounding_box_object()

		# cut out allowed domains from mega BB object
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_megaBB")
		FreeCAD.getDocument("tmp").Cut_megaBB.Base = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").Cut_megaBB.Tool = FreeCAD.getDocument("tmp").Objects[-3]
		FreeCAD.getDocument("tmp").recompute()
		#Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# cut out not-allowed parts
		FreeCAD.getDocument("tmp").addObject("Part::Cut", "Cut_allowed")
		FreeCAD.getDocument("tmp").Cut_allowed.Base = FreeCAD.getDocument("tmp").Objects[0]
		FreeCAD.getDocument("tmp").Cut_allowed.Tool = FreeCAD.getDocument("tmp").Objects[-2]
		FreeCAD.getDocument("tmp").recompute()
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove everything except the last cut-object
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		if len(__objs__) > 1:
			# create a fuse object and union all "Common"s
			FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "Fuse")
			FreeCAD.getDocument("tmp").Fuse.Shapes = __objs__[1: len(__objs__)]
			print FreeCAD.getDocument("tmp").Fuse.Shapes
			FreeCAD.getDocument("tmp").recompute()

			# remove "Commons"s
			for i in range(0, len(__objs__)):
				FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		# update __objs__
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
Example #43
0
 def update(self, names, pos):
     """ Update the 3D view printing annotations.
     @param names Weight names.
     @param pos Weight positions (FreeCAD::Base::Vector).
     """
     # Destroy all previous entities
     self.clean()
     for i in range(0, len(names)):
         # Draw gravity line
         line = Part.makeLine((pos[i].x,pos[i].y,pos[i].z),(pos[i].x,pos[i].y,pos[i].z - 9.81))
         Part.show(line)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'Line'
         # Draw circles
         circle = Part.makeCircle(0.5, pos[i], Base.Vector(1.0,0.0,0.0))
         Part.show(circle)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'CircleX'            
         circle = Part.makeCircle(0.5, pos[i], Base.Vector(0.0,1.0,0.0))
         Part.show(circle)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'CircleY'            
         circle = Part.makeCircle(0.5, pos[i], Base.Vector(0.0,0.0,1.0))
         Part.show(circle)
         objs = FreeCAD.ActiveDocument.Objects
         self.objects.append(objs[-1])
         objs[-1].Label = names[i] + 'CircleZ'            
         # Draw annotation
         self.objects.append(DrawText(names[i] + 'Text', names[i], Base.Vector(pos[i].x+1.0,pos[i].y,pos[i].z)))
Example #44
0
def main():
    s = FreeCADGui.Selection.getSelectionEx()
    edges = []
    for so in s:
        for su in so.SubObjects:
            #subshapes(su)
            if isinstance(su, Part.Edge):
                edges.append(su)
        if not so.HasSubObjects:
            edges.append(so.Object.Shape.Wires[0])

    nc1, nc2 = reparametrize(edges[0], edges[1], 40)
    com2 = Part.Compound([nc1.toShape(), nc2.toShape()])
    Part.show(com2)
Example #45
0
 def buildDummy(self):
     "Builds a dummy object with faces spaced on the Z axis, for visual check"
     z = 0
     if not self.sorted:
         self.sort()
     faces = []
     for f in self.faces[:]:
         ff = self.flattenFace(f)[0]
         ff.translate(FreeCAD.Vector(0, 0, z))
         faces.append(ff)
         z += 1
     if faces:
         c = Part.makeCompound(faces)
         Part.show(c)
Example #46
0
    def updateUI(self):

        if PathLog.getLevel(LOG_MODULE) == PathLog.Level.DEBUG:
            for obj in FreeCAD.ActiveDocument.Objects:
                if obj.Name.startswith('Shape'):
                    FreeCAD.ActiveDocument.removeObject(obj.Name)
            print('object name %s' % self.obj.Name)
            if hasattr(self.obj.Proxy, "shapes"):
                PathLog.info("showing shapes attribute")
                for shapes in self.obj.Proxy.shapes.itervalues():
                    for shape in shapes:
                        Part.show(shape)
            else:
                PathLog.info("no shapes attribute found")
def makeCompoundFromSelected(objects=None):
    """makeCompoundFromSelected([objects]): Creates a new compound object from the given
    subobjects (faces, edges) or from the the selection if objects is None"""
    import FreeCADGui,Part
    so = []
    if not objects:
        objects = FreeCADGui.Selection.getSelectionEx()
    if not isinstance(objects,list):
        objects = [objects]
    for o in objects:
        so.extend(o.SubObjects)
    if so:
        c = Part.makeCompound(so)
        Part.show(c)
Example #48
0
def makeCompoundFromSelected(objects=None):
    """makeCompoundFromSelected([objects]): Creates a new compound object from the given
    subobjects (faces, edges) or from the the selection if objects is None"""
    import FreeCADGui,Part
    so = []
    if not objects:
        objects = FreeCADGui.Selection.getSelectionEx()
    if not isinstance(objects,list):
        objects = [objects]
    for o in objects:
        so.extend(o.SubObjects)
    if so:
        c = Part.makeCompound(so)
        Part.show(c)
Example #49
0
def buildObject(doc, parent, layer, objMaterials, objTags):
    FreeCAD.Console.PrintMessage("Building mesh '%s'...\n" % (layer.name))
    data = []
    mfacets = []
    if (layer.pols):
        for pol in layer.pols:
            ngon = [layer.pnts[idx] for idx in pol]
            points = [V(k) for k in ngon]
            points.append(points[0])
            if len(ngon) > 2:
                wire = Part.makePolygon(points)
                plane = wire.findPlane(0.00001)
                points2 = [plane.projectPoint(p) for p in points]
                wire = Part.makePolygon(points2)
                try:
                    face = Part.Face(wire)
                    tris = face.tessellate(0.1)
                    for tri in tris[1]:
                        data.append([tris[0][i] for i in tri])
                except Exception as e:
                    Part.show(wire)
                    FreeCAD.Console.PrintWarning(
                        "   skipping polygon (%s): %s\n" % (e, ngon))

    me = newObject(doc, layer.name, data)
    me.Placement.Base = FreeCAD.Vector(layer.pivot)

    # Create the Material Slots and assign the MatIndex to the correct faces.
    for surf_key in layer.surf_tags:
        if objTags[surf_key] in objMaterials:
            material = objMaterials[objTags[surf_key]]
            #			me.ViewObject.ShapeMaterial.AmbientColor  =
            me.ViewObject.ShapeMaterial.DiffuseColor = material.colr
            #			me.ViewObject.ShapeMaterial.EmissiveColor =
            #			me.ViewObject.ShapeMaterial.SpecularColor =
            me.ViewObject.ShapeMaterial.Shininess = material.lumi
            me.ViewObject.ShapeMaterial.Transparency = material.trnl

    # Clear out the dictionaries for this layer.
    layer.surf_tags.clear()
    if (len(layer.subds) == 0):
        if (parent is not None):
            parent.Shapes.append(me)
    else:
        group = newGroup(doc, layer.name)
        group.Shapes.append(me)
        if (parent is not None):
            parent.Shapes.append(group)
        for child in layer.subds:
            buildObject(doc, group, child, objMaterials, objTags)
Example #50
0
 def buildDummy(self):
     "Builds a dummy object with faces spaced on the Z axis, for visual check"
     z = 0
     if not self.sorted:
         self.sort()
     faces = []
     for f in self.faces[:]:
         ff = self.flattenFace(f)[0]
         ff.translate(FreeCAD.Vector(0,0,z))
         faces.append(ff)
         z += 1
     if faces:
         c = Part.makeCompound(faces)
         Part.show(c)
Example #51
0
    def GetPathSolid(self, tool, cmd, pos):
        toolPath = PathGeom.edgeForCmd(cmd, pos)
        # curpos = e1.valueAt(e1.LastParameter)
        startDir = toolPath.tangentAt(0)
        startDir[2] = 0.0
        endPos = toolPath.valueAt(toolPath.LastParameter)
        endDir = toolPath.tangentAt(toolPath.LastParameter)
        try:
            startDir.normalize()
            endDir.normalize()
        except:
            return (None, endPos)
        # height = self.height

        # hack to overcome occ bugs
        rad = tool.Diameter / 2.0 - 0.001 * pos[2]
        # rad = rad + 0.001 * self.icmd
        if type(toolPath.Curve
                ) is Part.Circle and toolPath.Curve.Radius <= rad:
            rad = toolPath.Curve.Radius - 0.01 * (pos[2] + 1)
            return (None, endPos)

        # create the path shell
        toolProf = self.CreateToolProfile(tool, startDir, pos, rad)
        rotmat = Base.Matrix()
        rotmat.move(pos.negative())
        rotmat.rotateZ(math.pi)
        rotmat.move(pos)
        mirroredProf = toolProf.transformGeometry(rotmat)
        fullProf = Part.Wire([toolProf, mirroredProf])
        pathWire = Part.Wire(toolPath)
        try:
            pathShell = pathWire.makePipeShell([fullProf], False, True)
        except:
            if self.debug:
                Part.show(pathWire)
                Part.show(fullProf)
            return (None, endPos)

        # create the start cup
        startCup = toolProf.revolve(pos, Vector(0, 0, 1), -180)

        # create the end cup
        endProf = self.CreateToolProfile(tool, endDir, endPos, rad)
        endCup = endProf.revolve(endPos, Vector(0, 0, 1), 180)

        fullShell = Part.makeShell(startCup.Faces + pathShell.Faces +
                                   endCup.Faces)
        return (Part.makeSolid(fullShell).removeSplitter(), endPos)
Example #52
0
def createheel():

    points = [
        FreeCAD.Vector(30.0, 11.0, 0.0),
        FreeCAD.Vector(65., 5., 0.0),
        FreeCAD.Vector(60., -10., 0.0),
        FreeCAD.Vector(19., -13., 0.0)
    ]
    spline = Draft.makeBSpline(points, closed=True, face=True, support=None)

    s = spline.Shape.Edge1
    f = App.ActiveDocument.orig.Shape.Face1

    p = f.makeParallelProjection(s, App.Vector(0, 0, 1))
    Part.show(p)
    proj = App.ActiveDocument.ActiveObject

    clone = Draft.clone(spline)
    clone.Placement.Base.z = -100
    clone.Scale = (0.4, 0.5, 1.)

    loft = App.ActiveDocument.addObject('Part::Loft', 'Loft')
    loft.Sections = [proj, clone]

    points = [
        FreeCAD.Vector(165., -7., -00.0),
        FreeCAD.Vector(208., -25., -00.0),
        FreeCAD.Vector(233., 20., -00.0)
    ]
    spline = Draft.makeBSpline(points, closed=True, face=True, support=None)

    s = spline.Shape.Edge1
    f = App.ActiveDocument.orig.Shape.Face1

    p = f.makeParallelProjection(s, App.Vector(0, 0, 1))
    Part.show(p)
    proj = App.ActiveDocument.ActiveObject

    clone = Draft.clone(spline)
    clone.Placement.Base.z = -100

    loft = App.ActiveDocument.addObject('Part::Loft', 'Loft')
    loft.Sections = [proj, clone]

    App.activeDocument().recompute()
    Gui.activeDocument().activeView().viewAxonometric()
    Gui.SendMsgToActiveView("ViewFit")

    print "okay"
def run():

    try:
        [sourcex, targetx] = Gui.Selection.getSelectionEx()
        s = sourcex.SubObjects[0]
        f = targetx.SubObjects[0]

    except:
        [source, target] = Gui.Selection.getSelection()

        s = source.Shape.Edge1
        f = target.Shape.Face1

    p = f.makeParallelProjection(s, App.Vector(0, 0, 1))
    Part.show(p)
Example #54
0
def run_FreeCAD_Toy3(self):
    # testdaten fuer toponaming

    pts = [[0, 0, 0], [10, 0, 0], [10, 5, 0], [0, 5, 0], [0, 0, 15],
           [10, 0, 15], [10, 5, 15], [0, 5, 10]]

    if 1:
        [A, B, C, D, E, F, G, H] = [FreeCAD.Vector(p) for p in pts]
        col = [
            Part.makePolygon(l)
            for l in [[A, B], [B, C], [C, D], [D, A], [E, F], [F, G], [G, H],
                      [H, E], [A, E], [B, F], [C, G], [D, H]]
        ]

        Part.show(Part.Compound(col))
    def accept(self):
        """
        Executed upon clicking "OK" button in FreeCAD Tasks panel.
        """
        width = self.widthInputField.property('quantity').Value
        thickness = self.thicknessInputField.property('quantity').Value
        orientation_text = self.orientationComboBox.currentText()
        orientation = title_case_to_snake_case(orientation_text)
        with_set_screw = self.setScrewCheckbox.isChecked()
        with_filleting = self.filletCheckbox.isChecked()

        connector = AngleFrameConnector.make(width, thickness, orientation,
                                             with_set_screw, with_filleting)
        Part.show(connector)
        Gui.Control.closeDialog()
Example #56
0
def show_lineset_points(glider, pattern=None):
	import Part
	import FreeCAD as App
	points = []
	for line in glider.lineset.lines:
		if not pattern or pattern in line.name:
			points += [tuple(line.upper_node.vec.tolist())]
			points += [tuple(line.lower_node.vec.tolist())]
	# delete duplicates
	points = list(set(points))
	vertices = []
	for point in points:
		# rotate the points to align with rotation of glider
		vertices += [Part.Vertex(point[1], -point[0], point[2])]
	compound = Part.Compound(vertices)
	Part.show(compound)
Example #57
0
    def place(self,path):

        import Part
        self.shape = Part.read(path)
        if hasattr(FreeCADGui,"Snapper"):
            import DraftTrackers
            self.box = DraftTrackers.ghostTracker(self.shape,dotted=True,scolor=(0.0,0.0,1.0),swidth=1.0)
            self.delta = self.shape.BoundBox.Center
            self.box.move(self.delta)
            self.box.on()
            if hasattr(FreeCAD,"DraftWorkingPlane"):
                FreeCAD.DraftWorkingPlane.setup()
            self.origin = self.makeOriginWidget()
            FreeCADGui.Snapper.getPoint(movecallback=self.mouseMove,callback=self.mouseClick,extradlg=self.origin)
        else:
            Part.show(self.shape)
Example #58
0
    def Activated(self):
        import numpy as np
        import flatmesh
        obj = Gui.Selection.getSelection()[0] # obj must be a Mesh (Mesh-Design->Meshes->Create-Mesh)
        points = np.array([[i.x, i.y, i.z] for i in obj.Mesh.Points])
        faces = np.array([list(i) for i in  obj.Mesh.Topology[1]])
        flattener = flatmesh.FaceUnwrapper(points, faces)
        flattener.findFlatNodes(5, 0.95)
        boundaries = flattener.getFlatBoundaryNodes()
        #print('number of nodes: {}'.format(len(flattener.ze_nodes)))
        #print('number of faces: {}'.format(len(flattener.tris)))

        wires = []
        for edge in boundaries:
            pi = Part.makePolygon([App.Vector(*node) for node in edge])
            Part.show(Part.Wire(pi))
Example #59
0
def make_topo_edge(compoundpoi2):
    '''
    make all bodies confining boundary mesh edges
    (3d to be implemented)
    '''
    #!visu lines topo
    edgetL=[]
    for a in compoundpoi2.Shape.Edges:
	Part.show(a)
	edgetL.append(FreeCAD.ActiveDocument.Objects[len(FreeCAD.ActiveDocument.Objects)-1])

    compoundpoi2=FreeCAD.activeDocument().addObject("Part::Compound","Compoundi2")
    compoundpoi2.Links= edgetL
    FreeCAD.ActiveDocument.recompute()

    return compoundpoi2