def check_images(img, kp, name, all_ = True): if not all_: draw.bounding_boxes(cv.imread(img), kp, '_'+name) else: for n_file in range(len(img)): img_ = cv.imread(img[n_file]) kp_ = kp[n_file] draw.bounding_boxes(img_, kp_, '_'+name)
def getDXF(self): "returns a flat shape representation of the view" if hasattr(self,"baseshape"): import Drawing [V0,V1,H0,H1] = Drawing.project(self.baseshape,self.direction) DxfOutput = Drawing.projectToDXF(self.baseshape,self.direction) return DxfOutput else: FreeCAD.Console.PrintMessage(translate("Arch","No shape has been computed yet, select wireframe rendering and render again")) return None
def execute(self, obj): if obj.Source: if hasattr(obj.Source.Proxy,"BaseProfile"): p = obj.Source.Proxy.BaseProfile n = obj.Source.Proxy.ExtrusionVector import Drawing svg1 = "" svg2 = "" result = "" svg1 = Drawing.projectToSVG(p,DraftVecUtils.neg(n)) if svg1: w = str(obj.LineWidth/obj.Scale) #don't let linewidth be influenced by the scale... svg1 = svg1.replace('stroke-width="0.35"','stroke-width="'+w+'"') svg1 = svg1.replace('stroke-width="1"','stroke-width="'+w+'"') svg1 = svg1.replace('stroke-width:0.01','stroke-width:'+w) svg1 = svg1.replace('scale(1,-1)','scale('+str(obj.Scale)+',-'+str(obj.Scale)+')') if obj.Source.Tag: svg2 = '<text id="tag'+obj.Name+'"' svg2 += ' fill="'+Draft.getrgb(obj.TextColor)+'"' svg2 += ' font-size="'+str(obj.FontSize)+'"' svg2 += ' style="text-anchor:start;text-align:left;' svg2 += ' font-family:'+obj.FontName+'" ' svg2 += ' transform="translate(' + str(obj.TextX) + ',' + str(obj.TextY) + ')">' svg2 += '<tspan>'+obj.Source.Tag+'</tspan></text>\n' result += '<g id="' + obj.Name + '"' result += ' transform="' result += 'rotate('+str(obj.Rotation)+','+str(obj.X)+','+str(obj.Y)+') ' result += 'translate('+str(obj.X)+','+str(obj.Y)+')' result += '">\n ' result += svg1 result += svg2 result += '</g>' obj.ViewResult = result
def export_xyz_to_dxf(ai_solid, ai_size_x, ai_size_y, ai_size_z, ai_xy_slice_list, ai_xz_slice_list, ai_yz_slice_list, ai_output_file): """ Cut a FreeCAD Part Object in many slices in the three directions X, Y and Z and put all those slices in a DXF file """ # calculate the space between two drawings l_space = max(ai_size_x/5.0, ai_size_y/5.0, ai_size_z/5.0) # vec_z_unit = Base.Vector(0,0,1) # l_slice_list = [] l_pos_y = 0 for lo in ['xy','xz','yz']: #l_solid = ai_solid l_solid = ai_solid.copy() l_depth_list = [] l_shift_x = 0 l_gauge_max = 0 if(lo=='xy'): l_solid.rotate(Base.Vector(ai_size_x/2.0, ai_size_y/2.0, ai_size_z/2.0), Base.Vector(0,0,1), 0) l_solid.translate(Base.Vector(0,0,0)) # place the module corner at origin (0,0,0) l_solid.translate(Base.Vector(0,2*ai_size_z+7*l_space,0)) l_pos_y = 2*ai_size_z+6*l_space l_depth_list = ai_xy_slice_list l_shift_x = ai_size_x l_gauge_max = ai_size_z elif(lo=='xz'): l_solid.rotate(Base.Vector(ai_size_x/2.0, ai_size_y/2.0, ai_size_z/2.0), Base.Vector(1,0,0), -90) l_solid.translate(Base.Vector((ai_size_x-ai_size_x)/2.0, (ai_size_z-ai_size_y)/2.0, (ai_size_y-ai_size_z)/2.0)) # place the module corner at origin (0,0,0) l_solid.translate(Base.Vector(0,1*ai_size_z+4*l_space,0)) l_pos_y = 1*ai_size_z+3*l_space l_depth_list = ai_xz_slice_list l_shift_x = ai_size_x l_gauge_max = ai_size_y elif(lo=='yz'): l_solid.rotate(Base.Vector(ai_size_x/2.0, ai_size_y/2.0, ai_size_z/2.0), Base.Vector(0,0,1), -90) l_solid.rotate(Base.Vector(ai_size_x/2.0, ai_size_y/2.0, ai_size_z/2.0), Base.Vector(1,0,0), -90) l_solid.translate(Base.Vector((ai_size_y-ai_size_x)/2.0, (ai_size_z-ai_size_y)/2.0, (ai_size_x-ai_size_z)/2.0)) # place the module corner at origin (0,0,0) l_solid.translate(Base.Vector(0,l_space,0)) l_pos_y = 0*ai_size_z+0*l_space l_depth_list = ai_yz_slice_list l_shift_x = ai_size_y l_gauge_max = ai_size_x l_pos_x = 0 for l_depth in l_depth_list: #print("dbg163: l_shift_x l_space l_gauge_max l_depth l_pos_x l_pos_y", l_shift_x, l_space, l_gauge_max, l_depth, l_pos_x, l_pos_y) l_slice_list.extend(draw_gauge(l_shift_x, l_space/2.0, l_gauge_max, l_depth, l_pos_x, l_pos_y)) l_pos_x += l_shift_x+2*l_space ll_depth = l_depth if(lo=='xz'): ll_depth = ai_size_y-l_depth #print("dbg168: ll_depth:", ll_depth) l_slice_list.extend(l_solid.slice(vec_z_unit, ll_depth)) l_solid.translate(Base.Vector(l_shift_x+2*l_space,0,0)) l_slice = Part.makeCompound(l_slice_list) r_dxf = Drawing.projectToDXF(l_slice, vec_z_unit) #r_dxf = Drawing.projectToDXF(ai_solid, ai_vector) fh_output = open(ai_output_file, 'w') fh_output.write(r_dxf) fh_output.close() return(1)
def computeAreas(self, obj): "computes the area properties" if not obj.Shape: return if obj.Shape.isNull(): return if not obj.Shape.isValid(): return if not obj.Shape.Faces: return import Drawing, Part a = 0 fset = [] for i, f in enumerate(obj.Shape.Faces): try: ang = f.normalAt(0, 0).getAngle(FreeCAD.Vector(0, 0, 1)) except Part.OCCError: print "Debug: Error computing areas for ", obj.Label, ": normalAt() Face ", i return else: if (ang > 1.57) and (ang < 1.571): a += f.Area if ang < 1.5707: fset.append(f) if a and hasattr(obj, "VerticalArea"): if obj.VerticalArea.Value != a: obj.VerticalArea = a if fset and hasattr(obj, "HorizontalArea"): pset = [] for f in fset: if f.normalAt(0, 0).getAngle(FreeCAD.Vector(0, 0, 1)) < 0.00001: # already horizontal pset.append(f) else: try: pf = Part.Face(Part.Wire(Drawing.project(f, FreeCAD.Vector(0, 0, 1))[0].Edges)) except Part.OCCError: # error in computing the areas. Better set them to zero than show a wrong value if obj.HorizontalArea.Value != 0: print "Debug: Error computing areas for ", obj.Label, ": unable to project face: ", str( [v.Point for v in f.Vertexes] ), " (face normal:", f.normalAt(0, 0), ")" obj.HorizontalArea = 0 if hasattr(obj, "PerimeterLength"): if obj.PerimeterLength.Value != 0: obj.PerimeterLength = 0 else: pset.append(pf) if pset: self.flatarea = pset.pop() for f in pset: self.flatarea = self.flatarea.fuse(f) self.flatarea = self.flatarea.removeSplitter() if obj.HorizontalArea.Value != self.flatarea.Area: obj.HorizontalArea = self.flatarea.Area if hasattr(obj, "PerimeterLength") and (len(self.flatarea.Faces) == 1): if obj.PerimeterLength.Value != self.flatarea.Faces[0].OuterWire.Length: obj.PerimeterLength = self.flatarea.Faces[0].OuterWire.Length
def getDXF(obj): "returns a DXF representation from a TechDraw/Drawing view" allOn = True if hasattr(obj, "AllOn"): allOn = obj.AllOn elif hasattr(obj, "AlwaysOn"): allOn = obj.AlwaysOn showHidden = False if hasattr(obj, "showCut"): showHidden = obj.showCut elif hasattr(obj, "showHidden"): showHidden = obj.showHidden result = [] import Drawing, Part if not obj.Source: return result section = obj.Source if not section.Objects: return result p = FreeCAD.Placement(section.Placement) direction = p.Rotation.multVec(FreeCAD.Vector(0, 0, 1)) objs = Draft.getGroupContents(section.Objects, walls=True, addgroups=True) if not allOn: objs = Draft.removeHidden(objs) # separate spaces and Draft objects spaces = [] nonspaces = [] drafts = [] objs = [ o for o in objs if ((not (Draft.getType(o) in ["Space", "Dimension", "Annotation"])) and (not (o.isDerivedFrom("Part::Part2DObject")))) ] shapes, hshapes, sshapes, cutface, cutvolume, invcutvolume = getCutShapes( objs, section, showHidden) if shapes: result.append( Drawing.projectToDXF(Part.makeCompound(shapes), direction)) if sshapes: result.append( Drawing.projectToDXF(Part.makeCompound(sshapes), direction)) if hshapes: result.append( Drawing.projectToDXF(Part.makeCompound(hshapes), direction)) return result
def draw(self, screen): '''for element in self.tiles: for unit in element: unit.draw(screen)''' spr = Drawing.Sprite(self.bg) spr.draw(screen) for entity in self.entities: entity.draw(screen)
def __drawEllipse(self): if self.ellipseColor == self.ellipseBgColor: self.__showErrorMessage("Цвет фона и цвет рисунка совпадают!") return xc = self.ui.spinBox_ellipse_xc.value() yc = self.ui.spinBox_ellipse_yc.value() axisX = self.ui.spinBox_start_semiaxis_x.value() axisY = self.ui.spinBox_start_semiaxis_y.value() count = self.ui.spinBox_ellipse_number.value() stepX = self.ui.spin_box_ellipse_step_x.value() stepY = self.ui.spinBox_ellipse_step_y.value() alg = self.__getAlgorithm(self.ui.comboBox_ellipse_alg.currentText()) drawableObject = EllipseSpectrum(QPoint(xc, yc), axisX, axisY, count, stepX, stepY, alg, self.ellipseColor) self.childWindow = Drawing(drawableObject, self.ellipseBgColor, self.ellipseColor) self.childWindow.show()
def getFlatShape(self): "returns a flat shape representation of the view" if hasattr(self,"baseshape"): import Drawing [V0,V1,H0,H1] = Drawing.project(self.baseshape,self.direction) return V0.Edges+V1.Edges else: FreeCAD.Console.PrintMessage(translate("Arch","No shape has been computed yet, select wireframe rendering and render again")) return None
def computeAreas(self,obj): "computes the area properties" if not obj.Shape: return if obj.Shape.isNull(): return if not obj.Shape.isValid(): return if not obj.Shape.Faces: return import Drawing,Part a = 0 fset = [] for i,f in enumerate(obj.Shape.Faces): try: ang = f.normalAt(0,0).getAngle(FreeCAD.Vector(0,0,1)) except Part.OCCError: print("Debug: Error computing areas for ",obj.Label,": normalAt() Face ",i) return else: if (ang > 1.57) and (ang < 1.571): a += f.Area if ang < 1.5707: fset.append(f) if a and hasattr(obj,"VerticalArea"): if obj.VerticalArea.Value != a: obj.VerticalArea = a if fset and hasattr(obj,"HorizontalArea"): pset = [] for f in fset: if f.normalAt(0,0).getAngle(FreeCAD.Vector(0,0,1)) < 0.00001: # already horizontal pset.append(f) else: try: pf = Part.Face(Part.Wire(Drawing.project(f,FreeCAD.Vector(0,0,1))[0].Edges)) except Part.OCCError: # error in computing the areas. Better set them to zero than show a wrong value if obj.HorizontalArea.Value != 0: print("Debug: Error computing areas for ",obj.Label,": unable to project face: ",str([v.Point for v in f.Vertexes])," (face normal:",f.normalAt(0,0),")") obj.HorizontalArea = 0 if hasattr(obj,"PerimeterLength"): if obj.PerimeterLength.Value != 0: obj.PerimeterLength = 0 else: pset.append(pf) if pset: self.flatarea = pset.pop() for f in pset: self.flatarea = self.flatarea.fuse(f) self.flatarea = self.flatarea.removeSplitter() if obj.HorizontalArea.Value != self.flatarea.Area: obj.HorizontalArea = self.flatarea.Area if hasattr(obj,"PerimeterLength") and (len(self.flatarea.Faces) == 1): if obj.PerimeterLength.Value != self.flatarea.Faces[0].OuterWire.Length: obj.PerimeterLength = self.flatarea.Faces[0].OuterWire.Length
def getDXF(self,obj): "returns a DXF representation of the view" if obj.RenderingMode == "Solid": print "Unable to get DXF from Solid mode: ",obj.Label return "" result = [] import Drawing if not hasattr(self,"baseshape"): self.onChanged(obj,"Source") if hasattr(self,"baseshape"): if self.baseshape: result.append(Drawing.projectToDXF(self.baseshape,self.direction)) if hasattr(self,"sectionshape"): if self.sectionshape: result.append(Drawing.projectToDXF(self.sectionshape,self.direction)) if hasattr(self,"hiddenshape"): if self.hiddenshape: result.append(Drawing.projectToDXF(self.hiddenshape,self.direction)) return result
def export_to_svg(ai_solid, ai_vector, ai_depth, ai_output_file): """ create a SVG of a slice of FreeCAD Part Object. The generated SVG is incomplete. SVG header must be added to it to be opened by Inkscape """ l_slice = Part.makeCompound(ai_solid.slice(ai_vector, ai_depth)) # slice the plank in the ai_vector plan at a the height ai_depth r_dxf = Drawing.projectToSVG(l_slice, ai_vector) # it generates a snippet of svg not directly usable by Inkscape. It needs the svg head and document markers. #r_dxf = Drawing.projectToSVG(ai_solid, ai_vector) # works also :) fh_output = open(ai_output_file, 'w') fh_output.write(r_dxf) fh_output.close() return(1)
def __init__(self, room): super().__init__(room) self.spr = Drawing.Sprite( pygame.image.load("res/characters/shopkeeper.png").convert_alpha()) self.frame = 0 self.anim_counter = 0 self.health = self.maxhealth = 20
def export_to_dxf(ai_solid, ai_vector, ai_depth, ai_output_file): """ create a DXF of a slice of FreeCAD Part Object """ l_slice = Part.makeCompound(ai_solid.slice(ai_vector, ai_depth)) # slice the plank in the ai_vector plan at a the height ai_depth r_dxf = Drawing.projectToDXF(l_slice, ai_vector) #r_dxf = Drawing.projectToDXF(ai_solid, ai_vector) # works also :) fh_output = open(ai_output_file, 'w') fh_output.write(r_dxf) fh_output.close() return(1)
def main(): #for i in range(1, 9): # for j in range(1, 9): # direction_table[i][j] = random.randint(0, 360) #for i in range(9, -1, -1): # for j in range(10): # y = 95 - i*10 # x = j*10 + 5 # Drawing.drawAngle(direction_table[i][j], x, y, 'angles.png') #Drawing.closeGraph() """ Первые два параметра - начальная точка Третий - длина шага Четвертый - функция принадлежности Пятый - количество шагов :return: """ fuzzyCircle(50, 50, 1, MemFunctions.triangle, 400) Drawing.closeGraph()
def real_time(frame, distance, total_distance, max_speed, min_speed): draw.drawText( frame, str("Real Time Distance : " + "%.2f" % round(distance, 2) + " m"), (40, 80)) draw.drawText( frame, str("Total Distance : " + "%.2f" % round(total_distance, 2) + " m"), (40, 120)) draw.drawText( frame, str("Current Speed : " + "%.2f" % round(((distance * 3.6) / 3), 2) + " km/h"), (40, 160)) draw.drawText(frame, str("Max Speed :" + "%.2f" % round(max_speed, 2) + "km/h"), (40, 200)) draw.drawText(frame, str("Min Speed :" + "%.2f" % round(min_speed, 2) + "km/h"), (40, 240))
def ray_map(self, draw_ray, start_x, start_y, alpha, in_map, out_map): smallest_dis, smallest_x, smallest_y = 1000.0, 0.0, 0.0 ray_x1, ray_y1, ray_x2, ray_y2 = 100, 100, 300, 300 for i in range(len(in_map) / 2 - 1): x, y, dis = self.ray_line(start_x, start_y, alpha, in_map[i * 2], in_map[i * 2 + 1], in_map[i * 2 + 2], in_map[i * 2 + 3]) if dis != -1 and dis < smallest_dis: smallest_dis, smallest_x, smallest_y = dis, x, y ray_x1, ray_y1, ray_x2, ray_y2 = in_map[i * 2], in_map[ i * 2 + 1], in_map[i * 2 + 2], in_map[i * 2 + 3] x, y, dis = self.ray_line(start_x, start_y, alpha, in_map[len(in_map) - 2], in_map[len(in_map) - 1], in_map[0], in_map[1]) if dis != -1 and dis < smallest_dis: smallest_dis, smallest_x, smallest_y = dis, x, y ray_x1, ray_y1, ray_x2, ray_y2 = in_map[i * 2], in_map[ i * 2 + 1], in_map[i * 2 + 2], in_map[i * 2 + 3] for i in range(len(out_map) / 2 - 1): x, y, dis = self.ray_line(start_x, start_y, alpha, out_map[i * 2], out_map[i * 2 + 1], out_map[i * 2 + 2], out_map[i * 2 + 3]) if dis != -1 and dis < smallest_dis: smallest_dis, smallest_x, smallest_y = dis, x, y ray_x1, ray_y1, ray_x2, ray_y2 = out_map[i * 2], out_map[ i * 2 + 1], out_map[i * 2 + 2], out_map[i * 2 + 3] x, y, dis = self.ray_line(start_x, start_y, alpha, out_map[len(out_map) - 2], out_map[len(out_map) - 1], out_map[0], out_map[1]) if dis != -1 and dis < smallest_dis: smallest_dis, smallest_x, smallest_y = dis, x, y ray_x1, ray_y1, ray_x2, ray_y2 = out_map[i * 2], out_map[ i * 2 + 1], out_map[i * 2 + 2], out_map[i * 2 + 3] if draw_ray and smallest_dis < 500: Drawing.draw_line([0, 255, 0, 1], smallest_x, smallest_y, start_x, start_y) return smallest_dis
def renderWireframeSVG(self, objs, direction): os = objs[:] if os: sh = os.pop().Shape for o in os: sh = sh.fuse(o.Shape) result = Drawing.projectToSVG(sh, fcvec.neg(direction)) if result: result = result.replace('stroke-width="0.35"', 'stroke-width="0.01 px"') return result return ''
def export_to_dxf(ai_solid, ai_vector, ai_depth, ai_output_file): """ create a DXF of a slice of FreeCAD Part Object """ l_slice = Part.makeCompound( ai_solid.slice(ai_vector, ai_depth) ) # slice the plank in the ai_vector plan at a the height ai_depth r_dxf = Drawing.projectToDXF(l_slice, ai_vector) #r_dxf = Drawing.projectToDXF(ai_solid, ai_vector) # works also :) fh_output = open(ai_output_file, 'w') fh_output.write(r_dxf) fh_output.close() return (1)
def computeAreas(self, obj): "computes the area properties" if not obj.Shape: return if obj.Shape.isNull(): return if not obj.Shape.isValid(): return if not obj.Shape.Faces: return a = 0 fset = [] for f in obj.Shape.Faces: ang = f.normalAt(0, 0).getAngle(FreeCAD.Vector(0, 0, 1)) if (ang > 1.57) and (ang < 1.571): a += f.Area if ang < 1.5707: fset.append(f) if a and hasattr(obj, "VerticalArea"): if obj.VerticalArea.Value != a: obj.VerticalArea = a if fset and hasattr(obj, "HorizontalArea"): import Drawing, Part pset = [] for f in fset: try: pf = Part.Face( Part.Wire( Drawing.project(f, FreeCAD.Vector(0, 0, 1))[0].Edges)) except Part.OCCError: # error in computing the areas. Better set them to zero than show a wrong value if obj.HorizontalArea.Value != 0: print "Error computing areas for ", obj.Label obj.HorizontalArea = 0 if hasattr(obj, "PerimeterLength"): if obj.PerimeterLength.Value != 0: obj.PerimeterLength = 0 else: pset.append(pf) if pset: self.flatarea = pset.pop() for f in pset: self.flatarea = self.flatarea.fuse(f) self.flatarea = self.flatarea.removeSplitter() if obj.HorizontalArea.Value != self.flatarea.Area: obj.HorizontalArea = self.flatarea.Area if hasattr(obj, "PerimeterLength") and (len( self.flatarea.Faces) == 1): if obj.PerimeterLength.Value != self.flatarea.Faces[ 0].OuterWire.Length: obj.PerimeterLength = self.flatarea.Faces[ 0].OuterWire.Length
def getProjected(shape,direction): "returns projected edges from a shape and a direction" import Part,Drawing edges = [] groups = Drawing.projectEx(shape,direction) for g in groups[0:5]: if g: edges.append(g) # if hasattr(obj,"Tessellation") and obj.Tessellation: # return DraftGeomUtils.cleanProjection(Part.makeCompound(edges),obj.Tessellation,obj.SegmentLength) # else: return Part.makeCompound(edges)
def SaveAsUnusedName(): global Filename, Folder # code cycles through all of the available nubmers to create a unique filename Index = 0 Filename = str(Index) + ".png" while Filename in listdir("./letters/" + Folder): Index += 1 Filename = str(Index) + ".png" # actually do the drawing Drawing.DrawLetter(Folder, Filename)
def getProjected(shape, direction): "returns projected edges from a shape and a direction" import Part, Drawing edges = [] groups = Drawing.projectEx(shape, direction) for g in groups[0:5]: if g: edges.append(g) # if hasattr(obj,"Tessellation") and obj.Tessellation: # return DraftGeomUtils.cleanProjection(Part.makeCompound(edges),obj.Tessellation,obj.SegmentLength) # else: return Part.makeCompound(edges)
def updateSVG(self, obj, join=False): "encapsulates a svg fragment into a transformation node" import Part from draftlibs import fcgeo if hasattr(obj, "Source"): if obj.Source: if obj.Source.Objects: svg = "" # generating SVG linewidth = obj.LineWidth / obj.Scale if obj.RenderingMode == "Solid": # render using the Arch Vector Renderer import ArchVRM render = ArchVRM.Renderer() render.setWorkingPlane(obj.Source.Placement) render.addObjects(obj.Source.Objects) render.cut(obj.Source.Shape) svg += render.getViewSVG(linewidth=linewidth) svg += render.getSectionSVG(linewidth=linewidth * 2) # print render.info() else: # render using the Drawing module shapes = [] for o in obj.Source.Objects: if o.isDerivedFrom("Part::Feature"): shapes.append(o.Shape) if shapes: base = shape.pop() for sh in shapes: base = base.fuse(sh) svgf = Drawing.projectToSVG(base, fcvec.neg(direction)) if svgf: svgf = svgf.replace('stroke-width="0.35"', 'stroke-width="' + str(linewidth) + 'px"') svg += svgf result = "" result += '<g id="' + obj.Name + '"' result += ' transform="' result += "rotate(" + str(obj.Rotation) + "," + str(obj.X) + "," + str(obj.Y) + ") " result += "translate(" + str(obj.X) + "," + str(obj.Y) + ") " result += "scale(" + str(obj.Scale) + "," + str(-obj.Scale) + ")" result += '">\n' result += svg result += "</g>\n" # print "complete node:",result return result return ""
def updateSVG(self, obj,join=False): "encapsulates a svg fragment into a transformation node" import Part, DraftGeomUtils if hasattr(obj,"Source"): if obj.Source: if obj.Source.Objects: objs = Draft.getGroupContents(obj.Source.Objects) svg = '' # generating SVG linewidth = obj.LineWidth/obj.Scale if obj.RenderingMode == "Solid": # render using the Arch Vector Renderer import ArchVRM render = ArchVRM.Renderer() render.setWorkingPlane(obj.Source.Placement) render.addObjects(Draft.getGroupContents(objs,walls=True)) render.cut(obj.Source.Shape) svg += render.getViewSVG(linewidth=linewidth) svg += render.getSectionSVG(linewidth=linewidth*2) # print render.info() else: # render using the Drawing module import Drawing shapes = [] for o in objs: if o.isDerivedFrom("Part::Feature"): shapes.append(o.Shape) if shapes: base = shape.pop() for sh in shapes: base = base.fuse(sh) svgf = Drawing.projectToSVG(base,DraftVecUtils.neg(direction)) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="' + str(linewidth) + 'px"') svgf = svgf.replace('stroke-width:0.01','stroke-width:' + str(linewidth) + 'px') svg += svgf result = '' result += '<g id="' + obj.Name + '"' result += ' transform="' result += 'rotate('+str(obj.Rotation)+','+str(obj.X)+','+str(obj.Y)+') ' result += 'translate('+str(obj.X)+','+str(obj.Y)+') ' result += 'scale('+str(obj.Scale)+','+str(-obj.Scale)+')' result += '">\n' result += svg result += '</g>\n' # print "complete node:",result return result return ''
def updateSVG(self, obj,join=False): "encapsulates a svg fragment into a transformation node" import Part, DraftGeomUtils if hasattr(obj,"Source"): if obj.Source: if obj.Source.Objects: objs = Draft.getGroupContents(obj.Source.Objects) svg = '' # generating SVG linewidth = obj.LineWidth/obj.Scale if obj.RenderingMode == "Solid": # render using the Arch Vector Renderer import ArchVRM render = ArchVRM.Renderer() render.setWorkingPlane(obj.Source.Placement) render.addObjects(objs) render.cut(obj.Source.Shape) svg += render.getViewSVG(linewidth=linewidth) svg += render.getSectionSVG(linewidth=linewidth*2) # print render.info() else: # render using the Drawing module import Drawing shapes = [] for o in objs: if o.isDerivedFrom("Part::Feature"): shapes.append(o.Shape) if shapes: base = shape.pop() for sh in shapes: base = base.fuse(sh) svgf = Drawing.projectToSVG(base,DraftVecUtils.neg(direction)) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="' + str(linewidth) + 'px"') svgf = svgf.replace('stroke-width:0.01','stroke-width:' + str(linewidth) + 'px') svg += svgf result = '' result += '<g id="' + obj.Name + '"' result += ' transform="' result += 'rotate('+str(obj.Rotation)+','+str(obj.X)+','+str(obj.Y)+') ' result += 'translate('+str(obj.X)+','+str(obj.Y)+') ' result += 'scale('+str(obj.Scale)+','+str(-obj.Scale)+')' result += '">\n' result += svg result += '</g>\n' # print "complete node:",result return result return ''
def getDXF(obj): "returns a DXF representation from a TechDraw/Drawing view" allOn = True if hasattr(obj,"AllOn"): allOn = obj.AllOn elif hasattr(obj,"AlwaysOn"): allOn = obj.AlwaysOn showHidden = False if hasattr(obj,"showCut"): showHidden = obj.showCut elif hasattr(obj,"showHidden"): showHidden = obj.showHidden result = [] import Drawing,Part if not obj.Source: return result section = obj.Source if not section.Objects: return result p = FreeCAD.Placement(section.Placement) direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) objs = Draft.getGroupContents(section.Objects,walls=True,addgroups=True) if not allOn: objs = Draft.removeHidden(objs) # separate spaces and Draft objects spaces = [] nonspaces = [] drafts = [] objs = [o for o in objs if ((not(Draft.getType(o) in ["Space","Dimension","Annotation"])) and (not (o.isDerivedFrom("Part::Part2DObject"))))] shapes,hshapes,sshapes,cutface,cutvolume,invcutvolume = getCutShapes(objs,section,showHidden) if shapes: result.append(Drawing.projectToDXF(Part.makeCompound(shapes),direction)) if sshapes: result.append(Drawing.projectToDXF(Part.makeCompound(sshapes),direction)) if hshapes: result.append(Drawing.projectToDXF(Part.makeCompound(hshapes),direction)) return result
def __init__(self, room, direction, damage=2, hostile=True): super().__init__(room) self.spr = Drawing.Sprite( pygame.image.load("res/bullet.png").convert_alpha()) self.direction = direction self.frame = 0 self.hostile = hostile self.damage = damage self.hitSomething = False self.anim_counter = 0 self.pos = pygame.math.Vector2(64 + 48, 120) self.prevPos = self.pos
def export_to_svg(ai_solid, ai_vector, ai_depth, ai_output_file): """ create a SVG of a slice of FreeCAD Part Object. The generated SVG is incomplete. SVG header must be added to it to be opened by Inkscape """ l_slice = Part.makeCompound( ai_solid.slice(ai_vector, ai_depth) ) # slice the plank in the ai_vector plan at a the height ai_depth r_dxf = Drawing.projectToSVG( l_slice, ai_vector ) # it generates a snippet of svg not directly usable by Inkscape. It needs the svg head and document markers. #r_dxf = Drawing.projectToSVG(ai_solid, ai_vector) # works also :) fh_output = open(ai_output_file, 'w') fh_output.write(r_dxf) fh_output.close() return (1)
def draw(self, screen): spr = Drawing.Sprite(bomb_tex) if self.fuse >= 0: spr.pos = pygame.math.Vector2(self.pos.x - 16, self.pos.y - 48) spr.subrect = pygame.Rect( int((Constants.BOMB_FUSE_LENGTH - self.fuse) / (180 / 7)) * 32, 0, 32, 64) spr.draw(screen) else: stage = int(self.fuse / -5) spr.pos = pygame.math.Vector2(self.pos.x - 16, self.pos.y - 48) spr.subrect = pygame.Rect(256 + 32 * stage, 0, 32, 64) spr.scale = pygame.math.Vector2(1, 1) spr.draw(screen)
def createSVG(Part): # projecting with HLR [Visibly,Hidden] = Drawing.project(Part) buffer = startSVG for i in Hidden.Edges: buffer += '<line x1="' +`i.Vertexes[0].X` +'" y1="' +`i.Vertexes[0].Y` +'" x2="'+ `i.Vertexes[1].X`+ '" y2="'+ `i.Vertexes[1].Y`+ '" stroke="#fff000" stroke-width="1px" />\n' for i in Visibly.Edges: buffer += '<line x1="' +`i.Vertexes[0].X` +'" y1="' +`i.Vertexes[0].Y` +'" x2="'+ `i.Vertexes[1].X`+ '" y2="'+ `i.Vertexes[1].Y`+ '" stroke="#000000" stroke-width="1px" />\n' buffer += '</svg>' return buffer
def __init__(self, game): super().__init__(game) self.title = Drawing.Text(pygame.font.SysFont("Consolas", 50), "Infinite Shores") self.title.pos = ((Constants.WINDOW_SIZE[0] - self.title.get_width()) / 2, 50) self.playButton = Ui.Button("Play", (Constants.WINDOW_SIZE[0] - 200) / 2, 250, 200, 50) self.playButton.callback = self.callback_button_play self.widgets.append(self.playButton) self.worldButton = Ui.Button("Test World", self.playButton.rect.x, self.playButton.rect.y + self.playButton.rect.height + 32, self.playButton.rect.width, self.playButton.rect.height) self.worldButton.callback = self.callback_button_world self.widgets.append(self.worldButton)
def __init__(self): import Drawing self.__starColl = Star.StarCollection() #天体集合 self.__updateSpan = 100000 #每次计算对应虚拟世界的时间长度 self.__scale = 7E-11 #空间的比例尺 self.__canvas = None #用于绘制的画布 self.__drawInterval = 0.016 #两次绘制的间隔 self.__updateInterval = 0.001 #两次计算的间隔 self.__updateLoop = Loop(self.__updateInterval, self.__onUpdate) #计算线程 self.__drawLoop = Loop(self.__drawInterval, self.__onDraw) #绘制线程 self.__drawing = Drawing.Drawing() self.__drawTime1 = datetime.now() #前一次绘制的时间 self.__drawTime2 = datetime.now() #后一次绘制的时间(用于计算帧频) self.__updateTime1 = datetime.now() #前一次计算的时间 self.__updateTime2 = datetime.now() #后一次计算的时间(用于计算时间比例尺) self.__followedNumber = -1
def __init__(self, room, tex, frameCount=3, frameSize=64): super().__init__(room) self.spr = Drawing.Sprite( pygame.image.load("res/characters/" + tex + ".png").convert_alpha()) self.frame = 0 self.frameCount = frameCount self.frameSize = frameSize self.animInterval = 10 self.animAlways = False self.anim_counter = 0 self.prevPos = self.pos self.health = self.health_max = 12 self.hostile = True
def computeAreas(self,obj): "computes the area properties" if not obj.Shape: return if obj.Shape.isNull(): return if not obj.Shape.isValid(): return if not obj.Shape.Faces: return a = 0 fset = [] for f in obj.Shape.Faces: ang = f.normalAt(0,0).getAngle(FreeCAD.Vector(0,0,1)) if (ang > 1.57) and (ang < 1.571): a += f.Area if ang < 1.5707: fset.append(f) if a and hasattr(obj,"VerticalArea"): if obj.VerticalArea.Value != a: obj.VerticalArea = a if fset and hasattr(obj,"HorizontalArea"): import Drawing,Part pset = [] for f in fset: try: pf = Part.Face(Part.Wire(Drawing.project(f,FreeCAD.Vector(0,0,1))[0].Edges)) except Part.OCCError: # error in computing the areas. Better set them to zero than show a wrong value if obj.HorizontalArea.Value != 0: print "Error computing areas for ",obj.Label obj.HorizontalArea = 0 if hasattr(obj,"PerimeterLength"): if obj.PerimeterLength.Value != 0: obj.PerimeterLength = 0 else: pset.append(pf) if pset: self.flatarea = pset.pop() for f in pset: self.flatarea = self.flatarea.fuse(f) self.flatarea = self.flatarea.removeSplitter() if obj.HorizontalArea.Value != self.flatarea.Area: obj.HorizontalArea = self.flatarea.Area if hasattr(obj,"PerimeterLength") and (len(self.flatarea.Faces) == 1): if obj.PerimeterLength.Value != self.flatarea.Faces[0].OuterWire.Length: obj.PerimeterLength = self.flatarea.Faces[0].OuterWire.Length
def __init__(self, text, x, y, w, h): super().__init__() self.rect = pygame.Rect(x, y, w, h) self.text = Drawing.Text(pygame.font.SysFont("Consolas", int(h * 0.8)), text) draw_x = self.rect.left + (self.rect.width - self.text.get_width()) / 2 draw_y = self.rect.top + int(self.rect.height * 0.1) self.text.pos = pygame.math.Vector2(draw_x, draw_y) self.hovered = False self.fillColor = pygame.Color(255, 255, 255) self.outlineColor = pygame.Color(0, 0, 0) self.outlineThickness = 2 self.hoverColor = pygame.Color(128, 128, 128)
def Rankings(Img, NetworkName): Net = LoadNetwork(NetworkName) Values = Net.ForwardPass(Drawing.OneDimensionalImage(Img))["Outputs"] Letters = listdir("./letters") CompleteData = [] for i in range(0, len(Values)): CompleteData.append({"Letter": Letters[i], "Value": Values[i]}) # sort the array with the function CompleteData = Sort(CompleteData) #for i in range(0, 2): # print str(CompleteData[i]["Value"]) + "%" + " chance letter " + CompleteData[i]["Letter"] return CompleteData
def __init__(self, game, gen=True, test=False): super().__init__(game) self.test = test self.gen = gen if gen: self.game.sea = Sea("Test" if test else gibberish.generate_word( random.randint(1, 3)).capitalize()) self.selected_tile = pygame.Vector2(3, 3) self.name_font = pygame.font.SysFont("Consolas", 30) self.island_placeholder = pygame.image.load( "res/island-placeholder.png") self.sea_bg = pygame.Surface(pygame.math.Vector2(7 * 64, 7 * 64)) for ix in range(0, 7): for iy in range(0, 7): tile = -1 if ix == 0: if iy == 0: tile = 0 elif iy == 6: tile = 6 else: tile = 3 elif ix == 6: if iy == 0: tile = 2 elif iy == 6: tile = 8 else: tile = 5 else: if iy == 0: tile = 1 elif iy == 6: tile = 7 else: tile = 4 spr = Drawing.Sprite(water_tex) spr.subrect = pygame.Rect(tile % 3 * 16, int(tile / 3) * 16, 16, 16) spr.scale = pygame.math.Vector2(4, 4) spr.pos = pygame.math.Vector2(ix * 64, iy * 64) spr.draw(self.sea_bg)
def createSVG(Part): # projecting with HLR [Visibly, Hidden] = Drawing.project(Part) buffer = startSVG for i in Hidden.Edges: buffer += '<line x1="' + ` i.Vertexes[0].X ` + '" y1="' + ` i.Vertexes[ 0].Y ` + '" x2="' + ` i.Vertexes[1].X ` + '" y2="' + ` i.Vertexes[ 1].Y ` + '" stroke="#fff000" stroke-width="1px" />\n' for i in Visibly.Edges: buffer += '<line x1="' + ` i.Vertexes[0].X ` + '" y1="' + ` i.Vertexes[ 0].Y ` + '" x2="' + ` i.Vertexes[1].X ` + '" y2="' + ` i.Vertexes[ 1].Y ` + '" stroke="#000000" stroke-width="1px" />\n' buffer += '</svg>' return buffer
def getProjected(self,obj,shape,direction): "returns projected edges from a shape and a direction" import Part, Drawing, DraftGeomUtils edges = [] _groups = Drawing.projectEx(shape, direction) for g in _groups[0:5]: if g: edges.append(g) if hasattr(obj,"HiddenLines"): if obj.HiddenLines: for g in _groups[5:]: edges.append(g) #return Part.makeCompound(edges) if hasattr(obj,"Tessellation") and obj.Tessellation: return DraftGeomUtils.cleanProjection(Part.makeCompound(edges), obj.Tessellation, obj.SegmentLength) else: return Part.makeCompound(edges)
def execute(self, obj): if obj.Source: if hasattr(obj.Source.Proxy, "BaseProfile"): p = obj.Source.Proxy.BaseProfile n = obj.Source.Proxy.ExtrusionVector import Drawing svg1 = "" svg2 = "" result = "" svg1 = Drawing.projectToSVG(p, DraftVecUtils.neg(n)) if svg1: w = str( obj.LineWidth / obj.Scale ) #don't let linewidth be influenced by the scale... svg1 = svg1.replace('stroke-width="0.35"', 'stroke-width="' + w + '"') svg1 = svg1.replace('stroke-width="1"', 'stroke-width="' + w + '"') svg1 = svg1.replace('stroke-width:0.01', 'stroke-width:' + w) svg1 = svg1.replace( 'scale(1,-1)', 'scale(' + str(obj.Scale) + ',-' + str(obj.Scale) + ')') if obj.Source.Tag: svg2 = '<text id="tag' + obj.Name + '"' svg2 += ' fill="' + Draft.getrgb(obj.TextColor) + '"' svg2 += ' font-size="' + str(obj.FontSize) + '"' svg2 += ' style="text-anchor:start;text-align:left;' svg2 += ' font-family:' + obj.FontName + '" ' svg2 += ' transform="translate(' + str( obj.TextX) + ',' + str(obj.TextY) + ')">' svg2 += '<tspan>' + obj.Source.Tag + '</tspan></text>\n' result += '<g id="' + obj.Name + '"' result += ' transform="' result += 'rotate(' + str(obj.Rotation) + ',' + str( obj.X) + ',' + str(obj.Y) + ') ' result += 'translate(' + str(obj.X) + ',' + str(obj.Y) + ')' result += '">\n ' result += svg1 result += svg2 result += '</g>' obj.ViewResult = result
def __init__(self, game, room): super().__init__(room) self.game = game self.spr = Drawing.Sprite( pygame.image.load("res/player.png").convert_alpha()) self.frame = 0 self.anim_counter = 0 self.prevPos = self.pos self.gold = 0 self.bombs = 3 self.health = self.health_max = 12 self.hostile = False self.player_room_hook = self.collide_exit self.inventory[0] = Items.BasicMeleeItem("dagger", 1)
def print_sector(self, left, top): lineator = Drawing.Lineator(left, top) lineator.print( "{:>2}{:^3}{:^3}{:^3}{:^3}{:^3}{:^3}{:^3}{:^3}{:^3}{:^3}".format( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) for r in range(Constants.SECTOR_SIZE): lineator.print("{:>2}".format(r + 1), end='') for c in range(Constants.SECTOR_SIZE): coord = Coordinate(r, c) if coord in self.map: lineator.print(' ', self.map[coord].asChar(), ' ', sep='', end='') else: lineator.print(' . ', sep='', end='') lineator.print('') lineator.drawBoundingRect(fill='purple', outline='yellow', background=True) return lineator.bbox
return bb # do something here... svg = [] margin = 10 page = FreeCAD.BoundBox(margin,margin,0,210-margin,290-margin,0) placed_bbox=[] for obj in FreeCADGui.Selection.getSelectionEx(): for face in obj.SubObjects: if type(face) != Part.Face: continue f = face.copy() box = f.BoundBox f.translate(box.Center * -1) #f.translate(FreeCAD.Vector(box.XLength/2, box.YLength/2, box.ZLength/2)) svgproj = Drawing.projectToSVG(f,f.Surface.Axis) FreeCAD.Console.PrintMessage( svgproj) del f l_size=5 root = fromstring(svgproj) del root.attrib['stroke-width'] for node in root.findall('.//circle'): print node x = float(node.attrib.get('cx')) y = float(node.attrib.get('cy')) #node.attrib["style"]='stroke-width:0.35;stroke-miterlimit:4;stroke-dasharray:none;fill:none' l1 = Element('line') l1.attrib['x1']= str(x - l_size) l1.attrib['y1']= str(y) l1.attrib['x2']= str(x + l_size)
def getSVG(shape, opts=None, view_vector=(-1.75, 1.1, 5.0)): """ Export a shape to SVG """ d = {'width':800,'height':240,'marginLeft':200,'marginTop':20} if opts: d.update(opts) #need to guess the scale and the coordinate center uom = guessUnitOfMeasure(shape) width=float(d['width']) height=float(d['height']) marginLeft=float(d['marginLeft']) marginTop=float(d['marginTop']) #TODO: provide option to give 3 views viewVector = FreeCAD.Base.Vector(view_vector) (visibleG0,visibleG1,hiddenG0,hiddenG1) = Drawing.project(shape,viewVector) (hiddenPaths,visiblePaths) = getPaths(Drawing.projectToSVG(shape,viewVector,"ShowHiddenLines")) #this param is totally undocumented! #get bounding box -- these are all in 2-d space bb = visibleG0.BoundBox bb.add(visibleG1.BoundBox) bb.add(hiddenG0.BoundBox) bb.add(hiddenG1.BoundBox) #width pixels for x, height pixesl for y unitScale = min( width / bb.XLength * 0.75 , height / bb.YLength * 0.75 ) #compute amount to translate-- move the top left into view (xTranslate,yTranslate) = ( (0 - bb.XMin) + marginLeft/unitScale ,(0- bb.YMax) - marginTop/unitScale) #compute paths ( again -- had to strip out freecad crap ) hiddenContent = "" for p in hiddenPaths: hiddenContent += PATHTEMPLATE % p visibleContent = "" for p in visiblePaths: visibleContent += PATHTEMPLATE % p svg = SVG_TEMPLATE % ( { 'unitScale': str(unitScale), 'strokeWidth': str(1.0 / unitScale), 'hiddenContent': hiddenContent , 'visibleContent': visibleContent, 'xTranslate': str(xTranslate), 'yTranslate': str(yTranslate), 'width': str(width), 'height': str(height), 'textboxY': str(height - 30), 'uom': str(uom) } ) #svg = SVG_TEMPLATE % ( # {"content": projectedContent} #) return svg
def buildSVG(self, obj,join=False): "creates a svg representation" import Part, DraftGeomUtils if hasattr(obj,"Source"): if obj.Source: if obj.Source.Objects: objs = Draft.getGroupContents(obj.Source.Objects,walls=True) objs = Draft.removeHidden(objs) self.svg = '' # generating SVG if obj.RenderingMode == "Solid": # render using the Arch Vector Renderer import ArchVRM render = ArchVRM.Renderer() render.setWorkingPlane(obj.Source.Placement) render.addObjects(objs) if hasattr(obj,"ShowCut"): render.cut(obj.Source.Shape,obj.ShowCut) else: render.cut(obj.Source.Shape) self.svg += render.getViewSVG(linewidth="LWPlaceholder") self.svg += render.getSectionSVG(linewidth="SWPLaceholder") if hasattr(obj,"ShowCut"): if obj.ShowCut: self.svg += render.getHiddenSVG(linewidth="LWPlaceholder") # print render.info() else: # render using the Drawing module import Drawing, Part shapes = [] hshapes = [] sshapes = [] p = FreeCAD.Placement(obj.Source.Placement) self.direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) for o in objs: if o.isDerivedFrom("Part::Feature"): if o.Shape.isNull(): pass #FreeCAD.Console.PrintWarning(translate("Arch","Skipping empty object: ")+o.Name) elif o.Shape.isValid(): shapes.extend(o.Shape.Solids) else: FreeCAD.Console.PrintWarning(translate("Arch","Skipping invalid object: ")+o.Name) cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(obj.Source.Shape.copy(),shapes) if cutvolume: nsh = [] for sh in shapes: for sol in sh.Solids: if sol.Volume < 0: sol.reverse() c = sol.cut(cutvolume) s = sol.section(cutface) nsh.extend(c.Solids) sshapes.append(s) if hasattr(obj,"ShowCut"): if obj.ShowCut: c = sol.cut(invcutvolume) hshapes.append(c) shapes = nsh if shapes: self.shapes = shapes self.baseshape = Part.makeCompound(shapes) svgf = Drawing.projectToSVG(self.baseshape,self.direction) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width:0.01','stroke-width:LWPlaceholder') self.svg += svgf if hshapes: hshapes = Part.makeCompound(hshapes) svgh = Drawing.projectToSVG(hshapes,self.direction) if svgh: svgh = svgh.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width:0.01','stroke-width:LWPlaceholder') svgh = svgh.replace('fill="none"','fill="none"\nstroke-dasharray="0.09,0.05"') self.svg += svgh if sshapes: edges = [] for s in sshapes: edges.extend(s.Edges) wires = DraftGeomUtils.findWires(edges) faces = [] for w in wires: if (w.ShapeType == "Wire") and w.isClosed(): faces.append(Part.Face(w)) sshapes = Part.makeCompound(faces) svgs = Drawing.projectToSVG(sshapes,self.direction) if svgs: svgs = svgs.replace('stroke-width="0.35"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width="1"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.01','stroke-width:SWPlaceholder') self.svg += svgs
def onChanged(self, obj, prop): if prop in ["Source","RenderingMode","ShowCut"]: import Part, DraftGeomUtils if hasattr(obj,"Source"): if obj.Source: if obj.Source.Objects: objs = Draft.getGroupContents(obj.Source.Objects,walls=True) objs = Draft.removeHidden(objs) # separate spaces self.spaces = [] os = [] for o in objs: if Draft.getType(o) == "Space": self.spaces.append(o) else: os.append(o) objs = os self.svg = '' fillpattern = '<pattern id="sectionfill" patternUnits="userSpaceOnUse" patternTransform="matrix(5,0,0,5,0,0)"' fillpattern += ' x="0" y="0" width="10" height="10">' fillpattern += '<g>' fillpattern += '<rect width="10" height="10" style="stroke:none; fill:#ffffff" /><path style="stroke:#000000; stroke-width:1" d="M0,0 l10,10" /></g></pattern>' # generating SVG if obj.RenderingMode == "Solid": # render using the Arch Vector Renderer import ArchVRM, WorkingPlane wp = WorkingPlane.plane() wp.setFromPlacement(obj.Source.Placement) wp.inverse() render = ArchVRM.Renderer() render.setWorkingPlane(wp) render.addObjects(objs) if hasattr(obj,"ShowCut"): render.cut(obj.Source.Shape,obj.ShowCut) else: render.cut(obj.Source.Shape) self.svg += render.getViewSVG(linewidth="LWPlaceholder") self.svg += fillpattern self.svg += render.getSectionSVG(linewidth="SWPlaceholder",fillpattern="sectionfill") if hasattr(obj,"ShowCut"): if obj.ShowCut: self.svg += render.getHiddenSVG(linewidth="LWPlaceholder") # print render.info() else: # render using the Drawing module import Drawing, Part shapes = [] hshapes = [] sshapes = [] p = FreeCAD.Placement(obj.Source.Placement) self.direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) for o in objs: if o.isDerivedFrom("Part::Feature"): if o.Shape.isNull(): pass #FreeCAD.Console.PrintWarning(translate("Arch","Skipping empty object: ")+o.Name) elif o.Shape.isValid(): if hasattr(obj.Source,"OnlySolids"): if obj.Source.OnlySolids: shapes.extend(o.Shape.Solids) else: shapes.append(o.Shape) else: shapes.extend(o.Shape.Solids) else: FreeCAD.Console.PrintWarning(translate("Arch","Skipping invalid object: ")+o.Name) cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(obj.Source.Shape.copy(),shapes) if cutvolume: nsh = [] for sh in shapes: for sol in sh.Solids: if sol.Volume < 0: sol.reverse() c = sol.cut(cutvolume) s = sol.section(cutface) try: wires = DraftGeomUtils.findWires(s.Edges) for w in wires: f = Part.Face(w) sshapes.append(f) #s = Part.Wire(s.Edges) #s = Part.Face(s) except Part.OCCError: #print "ArchDrawingView: unable to get a face" sshapes.append(s) nsh.extend(c.Solids) #sshapes.append(s) if hasattr(obj,"ShowCut"): if obj.ShowCut: c = sol.cut(invcutvolume) hshapes.append(c) shapes = nsh if shapes: self.shapes = shapes self.baseshape = Part.makeCompound(shapes) svgf = Drawing.projectToSVG(self.baseshape,self.direction) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width:0.01','stroke-width:LWPlaceholder') self.svg += svgf if hshapes: hshapes = Part.makeCompound(hshapes) self.hiddenshape = hshapes svgh = Drawing.projectToSVG(hshapes,self.direction) if svgh: svgh = svgh.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width:0.01','stroke-width:LWPlaceholder') svgh = svgh.replace('fill="none"','fill="none"\nstroke-dasharray="DAPlaceholder"') self.svg += svgh if sshapes: svgs = "" if hasattr(obj,"ShowFill"): if obj.ShowFill: svgs += fillpattern svgs += '<g transform="rotate(180)">\n' for s in sshapes: if s.Edges: f = Draft.getSVG(s,direction=self.direction.negative(),linewidth=0,fillstyle="sectionfill",color=(0,0,0)) svgs += f svgs += "</g>\n" sshapes = Part.makeCompound(sshapes) self.sectionshape = sshapes svgs += Drawing.projectToSVG(sshapes,self.direction) if svgs: svgs = svgs.replace('stroke-width="0.35"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width="1"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.01','stroke-width:SWPlaceholder') svgs = svgs.replace('stroke-width="0.35 px"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.35','stroke-width:SWPlaceholder') self.svg += svgs
kp_pred = [] kp_label = [] for count in range(pred.shape[0]): kp_pred.append(get_kp(pred[count])) kp_label.append(get_kp(label[count])) input_ = net.blobs["data"].data.transpose((2, 3, 1, 0)).astype(np.uint8) # [:,:,:,0]#224 x 224 x 3 x batch mean_value = [104, 116, 122] # Imagenet mean value for count, mean in enumerate(mean_value): input_[:, :, count, :] += mean ch = raw_input("Do you want to watch prediction and label images? Type Y or N. ") if ch == "Y": for n in range(input_.shape[3]): draw.bounding_boxes( input_[:, :, :, n], kp_label[n], "_Label", save=True, name_save="images_result/label_" + str(n).zfill(3) + ".png", ) draw.bounding_boxes( input_[:, :, :, n], kp_pred[n], "_Prediction", save=True, name_save="images_result/pred_" + str(n).zfill(3) + ".png", ) time.sleep(1)
import Drawing as draw vgg_size = cfg.vgg_size def get_kp(label): keypoint = [] if not len(label) == 48: ValueError("Keypoints are not 48") for kp in range(0, len(label), 2): keypoint.append([label[kp], label[kp + 1]]) return keypoint # For a txt file f = open("model/Validation.txt").readlines() imgs = [line.split(" ")[0] for line in f] label = [] for line in range(len(f)): label.append([float(num) * vgg_size / 2 + vgg_size / 2 for num in f[line][:-1].split(" ")[1:]]) if not len(label[-1]) == 48: ValueError("Keypoints are not 48") kp_label = [] for label_ in label: kp_label.append(get_kp(label_)) n = 0 draw.bounding_boxes(cv.imread(imgs[n]), kp_label[n], 0, save=True, name_save="img_kp_" + str(n) + ".png") # for n in np.random.permutation(len(imgs)): # draw.bounding_boxes(cv.imread(imgs[n]), kp_label[n], 0)
def getSVG(section,allOn=False,renderMode="Wireframe",showHidden=False,showFill=False,scale=1,linewidth=1,fontsize=1,techdraw=False,rotation=0): """getSVG(section,[allOn,renderMode,showHidden,showFill,scale,linewidth,fontsize]) : returns an SVG fragment from an Arch section plane. If allOn is True, all cut objects are shown, regardless if they are visible or not. renderMode can be Wireframe (default) or Solid to use the Arch solid renderer. If showHidden is True, the hidden geometry above the section plane is shown in dashed line. If showFill is True, the cut areas get filled with a pattern""" if not section.Objects: return import Part,DraftGeomUtils p = FreeCAD.Placement(section.Placement) direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) objs = Draft.getGroupContents(section.Objects,walls=True,addgroups=True) if not allOn: objs = Draft.removeHidden(objs) # separate spaces and Draft objects spaces = [] nonspaces = [] drafts = [] windows = [] cutface = None for o in objs: if Draft.getType(o) == "Space": spaces.append(o) elif Draft.getType(o) in ["Dimension","Annotation"]: drafts.append(o) elif o.isDerivedFrom("Part::Part2DObject"): drafts.append(o) else: nonspaces.append(o) if Draft.getType(o) == "Window": windows.append(o) objs = nonspaces svg = '' fillpattern = '<pattern id="sectionfill" patternUnits="userSpaceOnUse" patternTransform="matrix(5,0,0,5,0,0)"' fillpattern += ' x="0" y="0" width="10" height="10">' fillpattern += '<g>' fillpattern += '<rect width="10" height="10" style="stroke:none; fill:#ffffff" /><path style="stroke:#000000; stroke-width:1" d="M0,0 l10,10" /></g></pattern>' # generating SVG if renderMode in ["Solid",1]: # render using the Arch Vector Renderer import ArchVRM, WorkingPlane wp = WorkingPlane.plane() wp.setFromPlacement(section.Placement) #wp.inverse() render = ArchVRM.Renderer() render.setWorkingPlane(wp) render.addObjects(objs) if showHidden: render.cut(section.Shape,showHidden) else: render.cut(section.Shape) svg += '<g transform="scale(1,-1)">\n' svg += render.getViewSVG(linewidth="LWPlaceholder") svg += fillpattern svg += render.getSectionSVG(linewidth="SWPlaceholder",fillpattern="sectionfill") if showHidden: svg += render.getHiddenSVG(linewidth="LWPlaceholder") svg += '</g>\n' # print render.info() else: # render using the Drawing module import Drawing, Part shapes,hshapes,sshapes,cutface,cutvolume,invcutvolume = getCutShapes(objs,section,showHidden) if shapes: baseshape = Part.makeCompound(shapes) svgf = Drawing.projectToSVG(baseshape,direction) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width:0.01','stroke-width:LWPlaceholder') svg += svgf if hshapes: hshapes = Part.makeCompound(hshapes) svgh = Drawing.projectToSVG(hshapes,direction) if svgh: svgh = svgh.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width:0.01','stroke-width:LWPlaceholder') svgh = svgh.replace('fill="none"','fill="none"\nstroke-dasharray="DAPlaceholder"') svg += svgh if sshapes: svgs = "" if showFill: #svgs += fillpattern svgs += '<g transform="rotate(180)">\n' for s in sshapes: if s.Edges: #f = Draft.getSVG(s,direction=direction.negative(),linewidth=0,fillstyle="sectionfill",color=(0,0,0)) # temporarily disabling fill patterns f = Draft.getSVG(s,direction=direction.negative(),linewidth=0,fillstyle="#aaaaaa",color=(0,0,0)) svgs += f svgs += "</g>\n" sshapes = Part.makeCompound(sshapes) svgs += Drawing.projectToSVG(sshapes,direction) if svgs: svgs = svgs.replace('stroke-width="0.35"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width="1"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.01','stroke-width:SWPlaceholder') svgs = svgs.replace('stroke-width="0.35 px"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.35','stroke-width:SWPlaceholder') svg += svgs scaledlinewidth = linewidth/scale st = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetFloat("CutLineThickness",2) yt = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetFloat("SymbolLineThickness",0.6) da = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetString("archHiddenPattern","30,10") da = da.replace(" ","") svg = svg.replace('LWPlaceholder', str(scaledlinewidth) + 'px') svg = svg.replace('SWPlaceholder', str(scaledlinewidth*st) + 'px') svg = svg.replace('DAPlaceholder', str(da)) if drafts: if not techdraw: svg += '<g transform="scale(1,-1)">' for d in drafts: svg += Draft.getSVG(d,scale=scale,linewidth=linewidth*yt,fontsize=fontsize,direction=direction,techdraw=techdraw,rotation=rotation) if not techdraw: svg += '</g>' # filter out spaces not cut by the section plane if cutface and spaces: spaces = [s for s in spaces if s.Shape.BoundBox.intersect(cutface.BoundBox)] if spaces: if not techdraw: svg += '<g transform="scale(1,-1)">' for s in spaces: svg += Draft.getSVG(s,scale=scale,linewidth=linewidth*yt,fontsize=fontsize,direction=direction,techdraw=techdraw,rotation=rotation) if not techdraw: svg += '</g>' # add additional edge symbols from windows if cutface and windows: cutwindows = [w.Name for w in windows if w.Shape.BoundBox.intersect(cutface.BoundBox)] if windows: sh = [] for w in windows: if not hasattr(w.Proxy,"sshapes"): w.Proxy.execute(w) if hasattr(w.Proxy,"sshapes"): if w.Proxy.sshapes and (w.Name in cutwindows): c = Part.makeCompound(w.Proxy.sshapes) c.Placement = w.Placement sh.append(c) # buggy for now... #if hasattr(w.Proxy,"vshapes"): # if w.Proxy.vshapes: # c = Part.makeCompound(w.Proxy.vshapes) # c.Placement = w.Placement # sh.append(c) if sh: if not techdraw: svg += '<g transform="scale(1,-1)">' for s in sh: svg += Draft.getSVG(s,scale=scale,linewidth=linewidth*yt,fontsize=fontsize,fillstyle="none",direction=direction,techdraw=techdraw,rotation=rotation) if not techdraw: svg += '</g>' #print "complete node:",svg return svg
sel = Gui.Selection.getSelectionEx() face = sel[0].SubObjects[0] import Drawing open('/tmp/out.dxf', 'w').write(Drawing.projectToDXF(face, App.Vector(0, 0, 1)))
def getSVG(section, renderMode="Wireframe", allOn=False, showHidden=False, scale=1, rotation=0, linewidth=1, lineColor=(0.0,0.0,0.0), fontsize=1, showFill=False, fillColor=(0.8,0.8,0.8), techdraw=False): """getSVG(section, [renderMode, allOn, showHidden, scale, rotation, linewidth, lineColor, fontsize, showFill, fillColor, techdraw]): returns an SVG fragment from an Arch section plane. If allOn is True, all cut objects are shown, regardless if they are visible or not. renderMode can be Wireframe (default) or Solid to use the Arch solid renderer. If showHidden is True, the hidden geometry above the section plane is shown in dashed line. If showFill is True, the cut areas get filled with a pattern. lineColor -- Color of lines for the renderMode "Wireframe". fillColor -- If showFill is True and renderMode is "Wireframe", the cut areas are filled with fillColor. """ if not section.Objects: return "" import Part,DraftGeomUtils p = FreeCAD.Placement(section.Placement) direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) objs = Draft.getGroupContents(section.Objects,walls=True,addgroups=True) if not allOn: objs = Draft.removeHidden(objs) # separate spaces and Draft objects spaces = [] nonspaces = [] drafts = [] windows = [] cutface = None for o in objs: if Draft.getType(o) == "Space": spaces.append(o) elif Draft.getType(o) in ["Dimension","Annotation","Label"]: drafts.append(o) elif o.isDerivedFrom("Part::Part2DObject"): drafts.append(o) else: nonspaces.append(o) if Draft.getType(o) == "Window": windows.append(o) objs = nonspaces archUserParameters = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") scaledLineWidth = linewidth/scale svgLineWidth = str(scaledLineWidth) + 'px' st = archUserParameters.GetFloat("CutLineThickness",2) svgCutLineWidth = str(scaledLineWidth * st) + 'px' yt = archUserParameters.GetFloat("SymbolLineThickness",0.6) svgSymbolLineWidth = str(linewidth * yt) hiddenPattern = archUserParameters.GetString("archHiddenPattern","30,10") svgHiddenPattern = hiddenPattern.replace(" ","") fillpattern = '<pattern id="sectionfill" patternUnits="userSpaceOnUse" patternTransform="matrix(5,0,0,5,0,0)"' fillpattern += ' x="0" y="0" width="10" height="10">' fillpattern += '<g>' fillpattern += '<rect width="10" height="10" style="stroke:none; fill:#ffffff" /><path style="stroke:#000000; stroke-width:1" d="M0,0 l10,10" /></g></pattern>' svgLineColor = Draft.getrgb(lineColor) svg = '' # reading cached version svgcache = None if hasattr(section.Proxy,"svgcache") and section.Proxy.svgcache: svgcache = section.Proxy.svgcache[0] if section.Proxy.svgcache[1] != renderMode: svgcache = None if section.Proxy.svgcache[2] != showHidden: svgcache = None if section.Proxy.svgcache[3] != showFill: svgcache = None # generating SVG if renderMode in ["Solid",1]: if not svgcache: svgcache = '' # render using the Arch Vector Renderer import ArchVRM, WorkingPlane wp = WorkingPlane.plane() wp.setFromPlacement(section.Placement) #wp.inverse() render = ArchVRM.Renderer() render.setWorkingPlane(wp) render.addObjects(objs) if showHidden: render.cut(section.Shape,showHidden) else: render.cut(section.Shape) svgcache += '<g transform="scale(1,-1)">\n' svgcache += render.getViewSVG(linewidth="SVGLINEWIDTH") svgcache += fillpattern svgcache += render.getSectionSVG(linewidth="SVGCUTLINEWIDTH", fillpattern="sectionfill") if showHidden: svgcache += render.getHiddenSVG(linewidth="SVGLINEWIDTH") svgcache += '</g>\n' # print(render.info()) section.Proxy.svgcache = [svgcache,renderMode,showHidden,showFill] else: if not svgcache: svgcache = "" # render using the Drawing module import Drawing, Part shapes,hshapes,sshapes,cutface,cutvolume,invcutvolume = getCutShapes(objs,section,showHidden) if shapes: baseshape = Part.makeCompound(shapes) style = {'stroke': "SVGLINECOLOR", 'stroke-width': "SVGLINEWIDTH"} svgcache += Drawing.projectToSVG( baseshape, direction, hStyle=style, h0Style=style, h1Style=style, vStyle=style, v0Style=style, v1Style=style) if hshapes: hshapes = Part.makeCompound(hshapes) style = {'stroke': "SVGLINECOLOR", 'stroke-width': "SVGLINEWIDTH", 'stroke-dasharray': "SVGHIDDENPATTERN"} svgcache += Drawing.projectToSVG( hshapes, direction, hStyle=style, h0Style=style, h1Style=style, vStyle=style, v0Style=style, v1Style=style) if sshapes: if showFill: #svgcache += fillpattern svgcache += '<g transform="rotate(180)">\n' for s in sshapes: if s.Edges: #svg += Draft.getSVG(s,direction=direction.negative(),linewidth=0,fillstyle="sectionfill",color=(0,0,0)) # temporarily disabling fill patterns svgcache += Draft.getSVG(s, direction=direction.negative(), linewidth=0, fillstyle=Draft.getrgb(fillColor), color=lineColor) svgcache += "</g>\n" sshapes = Part.makeCompound(sshapes) style = {'stroke': "SVGLINECOLOR", 'stroke-width': "SVGCUTLINEWIDTH"} svgcache += Drawing.projectToSVG( sshapes, direction, hStyle=style, h0Style=style, h1Style=style, vStyle=style, v0Style=style, v1Style=style) section.Proxy.svgcache = [svgcache,renderMode,showHidden,showFill] svgcache = svgcache.replace("SVGLINECOLOR",svgLineColor) svgcache = svgcache.replace("SVGLINEWIDTH",svgLineWidth) svgcache = svgcache.replace("SVGHIDDENPATTERN",svgHiddenPattern) svgcache = svgcache.replace("SVGCUTLINEWIDTH",svgCutLineWidth) svg += svgcache if drafts: if not techdraw: svg += '<g transform="scale(1,-1)">' for d in drafts: svg += Draft.getSVG(d, scale=scale, linewidth=svgSymbolLineWidth, fontsize=fontsize, direction=direction, color=lineColor, techdraw=techdraw, rotation=rotation) if not techdraw: svg += '</g>' # filter out spaces not cut by the section plane if cutface and spaces: spaces = [s for s in spaces if s.Shape.BoundBox.intersect(cutface.BoundBox)] if spaces: if not techdraw: svg += '<g transform="scale(1,-1)">' for s in spaces: svg += Draft.getSVG(s, scale=scale, linewidth=svgSymbolLineWidth, fontsize=fontsize, direction=direction, color=lineColor, techdraw=techdraw, rotation=rotation) if not techdraw: svg += '</g>' # add additional edge symbols from windows cutwindows = [] if cutface and windows: cutwindows = [w.Name for w in windows if w.Shape.BoundBox.intersect(cutface.BoundBox)] if windows: sh = [] for w in windows: if not hasattr(w.Proxy,"sshapes"): w.Proxy.execute(w) if hasattr(w.Proxy,"sshapes"): if w.Proxy.sshapes and (w.Name in cutwindows): c = Part.makeCompound(w.Proxy.sshapes) c.Placement = w.Placement sh.append(c) # buggy for now... #if hasattr(w.Proxy,"vshapes"): # if w.Proxy.vshapes: # c = Part.makeCompound(w.Proxy.vshapes) # c.Placement = w.Placement # sh.append(c) if sh: if not techdraw: svg += '<g transform="scale(1,-1)">' for s in sh: svg += Draft.getSVG(s, scale=scale, linewidth=svgSymbolLineWidth, fontsize=fontsize, fillstyle="none", direction=direction, color=lineColor, techdraw=techdraw, rotation=rotation) if not techdraw: svg += '</g>' return svg
import pickle import os import cv2 as cv import numpy as np import sys import random sys.path.insert(0, 'Drawing') from Drawing import imshow import Drawing as draw out_folder = 'data' sub_data = ['images', 'segs'] root = ['full', 'parted'] vgg_size = cfg.vgg_size if __name__ == '__main__': mode = sys.argv[1] if not mode == 'Training' or not mode == 'Validation' or not mode == 'Test': ValueError('Please insert a valid mode between "Training", "Validation" or "Test". Case sensitive.') lines = open(os.path.join(out_folder, mode+'.txt')).readlines() randi = random.randint(0, len(lines)-1) line = lines[randi][:-1].split(' ') img = cv.imread(line[0]) seg = cv.imread(line[1]) for i in range(2, len(line)): seg += (cv.imread(line[i])*i) seg = draw.cmap(seg) imshow(img+seg,0)
def computeAreas(self,obj): if not obj.Shape: return if obj.Shape.isNull(): return if not obj.Shape.isValid(): return if not obj.Shape.Faces: return if not hasattr(obj,"Perimeter"): # check we have a latest version site return if not obj.Terrain: return # compute area fset = [] for f in obj.Shape.Faces: if f.normalAt(0,0).getAngle(FreeCAD.Vector(0,0,1)) < 1.5707: fset.append(f) if fset: import Drawing,Part pset = [] for f in fset: try: pf = Part.Face(Part.Wire(Drawing.project(f,FreeCAD.Vector(0,0,1))[0].Edges)) except Part.OCCError: # error in computing the area. Better set it to zero than show a wrong value if obj.ProjectedArea.Value != 0: print("Error computing areas for ",obj.Label) obj.ProjectedArea = 0 else: pset.append(pf) if pset: self.flatarea = pset.pop() for f in pset: self.flatarea = self.flatarea.fuse(f) self.flatarea = self.flatarea.removeSplitter() if obj.ProjectedArea.Value != self.flatarea.Area: obj.ProjectedArea = self.flatarea.Area # compute perimeter lut = {} for e in obj.Shape.Edges: lut.setdefault(e.hashCode(),[]).append(e) l = 0 for e in lut.values(): if len(e) == 1: # keep only border edges l += e[0].Length if l: if obj.Perimeter.Value != l: obj.Perimeter = l # compute volumes if obj.Terrain.Shape.Solids: shapesolid = obj.Terrain.Shape.copy() else: shapesolid = obj.Terrain.Shape.extrude(obj.ExtrusionVector) addvol = 0 subvol = 0 for sub in obj.Subtractions: subvol += sub.Shape.common(shapesolid).Volume for sub in obj.Additions: addvol += sub.Shape.cut(shapesolid).Volume if obj.SubtractionVolume.Value != subvol: obj.SubtractionVolume = subvol if obj.AdditionVolume.Value != addvol: obj.AdditionVolume = addvol
def updateSVG(self, obj,join=False): "encapsulates a svg fragment into a transformation node" import Part, DraftGeomUtils if hasattr(obj,"Source"): if obj.Source: if obj.Source.Objects: objs = Draft.getGroupContents(obj.Source.Objects) objs = Draft.removeHidden(objs) svg = '' # generating SVG linewidth = obj.LineWidth/obj.Scale if obj.RenderingMode == "Solid": # render using the Arch Vector Renderer import ArchVRM render = ArchVRM.Renderer() render.setWorkingPlane(obj.Source.Placement) render.addObjects(Draft.getGroupContents(objs,walls=True)) render.cut(obj.Source.Shape) svg += render.getViewSVG(linewidth=linewidth) svg += render.getSectionSVG(linewidth=linewidth*2) # print render.info() else: # render using the Drawing module import Drawing, Part shapes = [] p = FreeCAD.Placement(obj.Source.Placement) direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) for o in objs: if o.isDerivedFrom("Part::Feature"): shapes.extend(o.Shape.Solids) cutface,cutvolume = ArchCommands.getCutVolume(obj.Source.Shape.copy(),shapes) if cutvolume: nsh = [] for sh in shapes: for sol in sh.Solids: c = sol.cut(cutvolume) nsh.append(c) shapes = nsh base = Part.makeCompound(shapes) #if shapes: # base = shapes.pop().copy() #for sh in shapes: # try: # base = base.fuse(sh) # except: # print "unable to fuse, passing..." svgf = Drawing.projectToSVG(base,direction) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="' + str(linewidth) + 'px"') svgf = svgf.replace('stroke-width="1"','stroke-width="' + str(linewidth) + 'px"') svgf = svgf.replace('stroke-width:0.01','stroke-width:' + str(linewidth) + 'px') svg += svgf result = '' result += '<g id="' + obj.Name + '"' result += ' transform="' result += 'rotate('+str(obj.Rotation)+','+str(obj.X)+','+str(obj.Y)+') ' result += 'translate('+str(obj.X)+','+str(obj.Y)+') ' result += 'scale('+str(obj.Scale)+','+str(-obj.Scale)+')' result += '">\n' result += svg result += '</g>\n' # print "complete node:",result return result return ''
def getPath(edges=[],wires=[],pathname=None): import Part,DraftGeomUtils svg = "<path " if pathname is None: svg += 'id="%s" ' % obj.Name elif pathname != "": svg += 'id="%s" ' % pathname svg += ' d="' if not wires: egroups = Part.sortEdges(edges) else: egroups = [] for w in wires: w1=w.copy() w1.fixWire() egroups.append(Part.__sortEdges__(w1.Edges)) for egroupindex, edges in enumerate(egroups): edata = "" vs=() #skipped for the first edge for edgeindex,e in enumerate(edges): previousvs = vs # vertexes of an edge (reversed if needed) vs = e.Vertexes if previousvs: if (vs[0].Point-previousvs[-1].Point).Length > 1e-6: vs.reverse() if edgeindex == 0: v = getProj(vs[0].Point, plane) edata += 'M '+ str(v.x) +' '+ str(v.y) + ' ' else: if (vs[0].Point-previousvs[-1].Point).Length > 1e-6: raise ValueError('edges not ordered') iscircle = DraftGeomUtils.geomType(e) == "Circle" isellipse = DraftGeomUtils.geomType(e) == "Ellipse" if iscircle or isellipse: import math if hasattr(FreeCAD,"DraftWorkingPlane"): drawing_plane_normal = FreeCAD.DraftWorkingPlane.axis else: drawing_plane_normal = FreeCAD.Vector(0,0,1) if plane: drawing_plane_normal = plane.axis c = e.Curve if round(c.Axis.getAngle(drawing_plane_normal),2) in [0,3.14]: occversion = Part.OCC_VERSION.split(".") done = False if (int(occversion[0]) >= 7) and (int(occversion[1]) >= 1): # if using occ >= 7.1, use HLR algorithm import Drawing snip = Drawing.projectToSVG(e,drawing_plane_normal) if snip: try: a = "A " + snip.split("path d=\"")[1].split("\"")[0].split("A")[1] except: pass else: edata += a done = True if not done: if len(e.Vertexes) == 1 and iscircle: #complete curve svg = getCircle(e) return svg elif len(e.Vertexes) == 1 and isellipse: #svg = getEllipse(e) #return svg endpoints = (getProj(c.value((c.LastParameter-\ c.FirstParameter)/2.0), plane), \ getProj(vs[-1].Point, plane)) else: endpoints = (getProj(vs[-1].Point), plane) # arc if iscircle: rx = ry = c.Radius rot = 0 else: #ellipse rx = c.MajorRadius ry = c.MinorRadius rot = math.degrees(c.AngleXU * (c.Axis * \ FreeCAD.Vector(0,0,1))) if rot > 90: rot -=180 if rot < -90: rot += 180 #be careful with the sweep flag flag_large_arc = (((e.ParameterRange[1] - \ e.ParameterRange[0]) / math.pi) % 2) > 1 #flag_sweep = (c.Axis * drawing_plane_normal >= 0) \ # == (e.LastParameter > e.FirstParameter) # == (e.Orientation == "Forward") # other method: check the direction of the angle between tangents t1 = e.tangentAt(e.FirstParameter) t2 = e.tangentAt(e.FirstParameter + (e.LastParameter-e.FirstParameter)/10) flag_sweep = (DraftVecUtils.angle(t1,t2,drawing_plane_normal) < 0) for v in endpoints: edata += 'A %s %s %s %s %s %s %s ' % \ (str(rx),str(ry),str(rot),\ str(int(flag_large_arc)),\ str(int(flag_sweep)),str(v.x),str(v.y)) else: edata += getDiscretized(e, plane) elif DraftGeomUtils.geomType(e) == "Line": v = getProj(vs[-1].Point, plane) edata += 'L '+ str(v.x) +' '+ str(v.y) + ' ' else: bspline=e.Curve.toBSpline(e.FirstParameter,e.LastParameter) if bspline.Degree > 3 or bspline.isRational(): try: bspline=bspline.approximateBSpline(0.05,50, 3,'C0') except RuntimeError: print("Debug: unable to approximate bspline") if bspline.Degree <= 3 and not bspline.isRational(): for bezierseg in bspline.toBezier(): if bezierseg.Degree>3: #should not happen raise AssertionError elif bezierseg.Degree==1: edata +='L ' elif bezierseg.Degree==2: edata +='Q ' elif bezierseg.Degree==3: edata +='C ' for pole in bezierseg.getPoles()[1:]: v = getProj(pole, plane) edata += str(v.x) +' '+ str(v.y) + ' ' else: print("Debug: one edge (hash ",e.hashCode(),\ ") has been discretized with parameter 0.1") for linepoint in bspline.discretize(0.1)[1:]: v = getProj(linepoint, plane) edata += 'L '+ str(v.x) +' '+ str(v.y) + ' ' if fill != 'none': edata += 'Z ' if edata in pathdata: # do not draw a path on another identical path return "" else: svg += edata pathdata.append(edata) svg += '" ' svg += 'stroke="' + stroke + '" ' svg += 'stroke-width="' + str(linewidth) + ' px" ' svg += 'style="stroke-width:'+ str(linewidth) svg += ';stroke-miterlimit:4' svg += ';stroke-dasharray:' + lstyle svg += ';fill:' + fill try: svg += ';fill-opacity:' + str(fill_opacity) except NameError: pass svg += ';fill-rule: evenodd "' svg += '/>\n' return svg
# exampel how to use the scripting API of the drawing module # # first of all you need the Part and the Drawing module: import FreeCAD, Part, Drawing # create a small sample part Part.show(Part.makeBox(100,100,100).cut(Part.makeCylinder(80,100)).cut(Part.makeBox(90,40,100)).cut(Part.makeBox(20,85,100))) # direct projection. The G0 means hard edge, the G1 is tangend continues. Shape = App.ActiveDocument.Shape.Shape [visiblyG0,visiblyG1,hiddenG0,hiddenG1] = Drawing.project(Shape) print "visible edges:", len(visiblyG0.Edges) print "hidden edges:", len(hiddenG0.Edges) # all was projected on the Z-plane: print "Bnd Box shape: X=",Shape.BoundBox.XLength," Y=",Shape.BoundBox.YLength," Z=",Shape.BoundBox.ZLength print "Bnd Box project: X=",visiblyG0.BoundBox.XLength," Y=",visiblyG0.BoundBox.YLength," Z=",visiblyG0.BoundBox.ZLength # different projection vector [visiblyG0,visiblyG1,hiddenG0,hiddenG1] = Drawing.project(Shape,Base.Vector(1,1,1)) # project to SVG resultSVG = Drawing.projectToSVG(Shape,App.Vector(1,1,1)) print resultSVG # And now the parametric way # # insert a Page object and assign a template App.activeDocument().addObject('Drawing::FeaturePage','Page') App.activeDocument().Page.Template = App.ConfigGet('AppHomePath')+'Mod/Drawing/Templates/A3_Landscape.svg' # create a view on the "Shape" object, define the position and scale and assign it to a Page
def getSVG(section,allOn=False,renderMode="Wireframe",showHidden=False,showFill=False,scale=1,linewidth=1,fontsize=1): """getSVG(section,[allOn,renderMode,showHidden,showFill,scale,linewidth,fontsize]) : returns an SVG fragment from an Arch section plane. If allOn is True, all cut objects are shown, regardless if they are visible or not. renderMode can be Wireframe (default) or Solid to use the Arch solid renderer. If showHidden is True, the hidden geometry above the section plane is shown in dashed line. If showFill is True, the cut areas get filled with a pattern""" if not section.Objects: return import DraftGeomUtils p = FreeCAD.Placement(section.Placement) direction = p.Rotation.multVec(FreeCAD.Vector(0,0,1)) objs = Draft.getGroupContents(section.Objects,walls=True,addgroups=True) if not allOn: objs = Draft.removeHidden(objs) # separate spaces spaces = [] nonspaces = [] for o in objs: if Draft.getType(o) == "Space": spaces.append(o) else: nonspaces.append(o) objs = nonspaces svg = '' fillpattern = '<pattern id="sectionfill" patternUnits="userSpaceOnUse" patternTransform="matrix(5,0,0,5,0,0)"' fillpattern += ' x="0" y="0" width="10" height="10">' fillpattern += '<g>' fillpattern += '<rect width="10" height="10" style="stroke:none; fill:#ffffff" /><path style="stroke:#000000; stroke-width:1" d="M0,0 l10,10" /></g></pattern>' # generating SVG if renderMode == "Solid": # render using the Arch Vector Renderer import ArchVRM, WorkingPlane wp = WorkingPlane.plane() wp.setFromPlacement(section.Placement) #wp.inverse() render = ArchVRM.Renderer() render.setWorkingPlane(wp) render.addObjects(objs) if showHidden: render.cut(section.Shape,showHidden) else: render.cut(section.Shape) svg += '<g transform="scale(1,-1)">\n' svg += render.getViewSVG(linewidth="LWPlaceholder") svg += fillpattern svg += render.getSectionSVG(linewidth="SWPlaceholder",fillpattern="sectionfill") if showHidden: svg += render.getHiddenSVG(linewidth="LWPlaceholder") svg += '</g>\n' # print render.info() else: # render using the Drawing module import Drawing, Part shapes = [] hshapes = [] sshapes = [] for o in objs: if o.isDerivedFrom("Part::Feature"): if o.Shape.isNull(): pass elif o.Shape.isValid(): if section.OnlySolids: shapes.extend(o.Shape.Solids) else: shapes.append(o.Shape) else: print section.Label,": Skipping invalid object:",o.Label cutface,cutvolume,invcutvolume = ArchCommands.getCutVolume(section.Shape.copy(),shapes) if cutvolume: nsh = [] for sh in shapes: for sol in sh.Solids: if sol.Volume < 0: sol.reverse() c = sol.cut(cutvolume) s = sol.section(cutface) try: wires = DraftGeomUtils.findWires(s.Edges) for w in wires: f = Part.Face(w) sshapes.append(f) #s = Part.Wire(s.Edges) #s = Part.Face(s) except Part.OCCError: #print "ArchDrawingView: unable to get a face" sshapes.append(s) nsh.extend(c.Solids) #sshapes.append(s) if showHidden: c = sol.cut(invcutvolume) hshapes.append(c) shapes = nsh if shapes: baseshape = Part.makeCompound(shapes) svgf = Drawing.projectToSVG(baseshape,direction) if svgf: svgf = svgf.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgf = svgf.replace('stroke-width:0.01','stroke-width:LWPlaceholder') svg += svgf if hshapes: hshapes = Part.makeCompound(hshapes) svgh = Drawing.projectToSVG(hshapes,direction) if svgh: svgh = svgh.replace('stroke-width="0.35"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width="1"','stroke-width="LWPlaceholder"') svgh = svgh.replace('stroke-width:0.01','stroke-width:LWPlaceholder') svgh = svgh.replace('fill="none"','fill="none"\nstroke-dasharray="DAPlaceholder"') svg += svgh if sshapes: svgs = "" if showFill: svgs += fillpattern svgs += '<g transform="rotate(180)">\n' for s in sshapes: if s.Edges: f = Draft.getSVG(s,direction=direction.negative(),linewidth=0,fillstyle="sectionfill",color=(0,0,0)) svgs += f svgs += "</g>\n" sshapes = Part.makeCompound(sshapes) svgs += Drawing.projectToSVG(sshapes,direction) if svgs: svgs = svgs.replace('stroke-width="0.35"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width="1"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.01','stroke-width:SWPlaceholder') svgs = svgs.replace('stroke-width="0.35 px"','stroke-width="SWPlaceholder"') svgs = svgs.replace('stroke-width:0.35','stroke-width:SWPlaceholder') svg += svgs linewidth = linewidth/scale st = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetFloat("CutLineThickness",2) da = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetString("archHiddenPattern","30,10") da = da.replace(" ","") svg = svg.replace('LWPlaceholder', str(linewidth) + 'px') svg = svg.replace('SWPlaceholder', str(linewidth*st) + 'px') svg = svg.replace('DAPlaceholder', str(da)) if spaces and round(direction.getAngle(FreeCAD.Vector(0,0,1)),Draft.precision()) in [0,round(math.pi,Draft.precision())]: svg += '<g transform="scale(1,-1)">' for s in spaces: svg += Draft.getSVG(s,scale=scale,fontsize=fontsize,direction=direction) svg += '</g>' # print "complete node:",svg return svg