Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf8 -*-
- #***************************************************************************
- #* *
- #* Copyright (c) 2009 Yorik van Havre <yorik@gmx.fr> *
- #* Dan Falck ddfalck@gmail.com *
- #* This program is free software; you can redistribute it and/or modify *
- #* it under the terms of the GNU General Public License (GPL) *
- #* as published by the Free Software Foundation; either version 2 of *
- #* the License, or (at your option) any later version. *
- #* for detail see the LICENCE text file. *
- #* *
- #* This program is distributed in the hope that it will be useful, *
- #* but WITHOUT ANY WARRANTY; without even the implied warranty of *
- #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- #* GNU Library General Public License for more details. *
- #* *
- #* You should have received a copy of the GNU Library General Public *
- #* License along with this program; if not, write to the Free Software *
- #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
- #* USA *
- #* *
- #***************************************************************************
- __title__="FreeCAD DXF to Sketcher importer"
- __author__ = "Yorik van Havre <yorik@gmx.fr>, Dan Falck <ddfalck@gmail.com>"
- __url__ = ["http://yorik.orgfree.com","http://free-cad.sourceforge.net"]
- '''
- This script uses a DXF-parsing library created by Stani,
- Kitsu and Migius for Blender
- imports:
- line, arcs, circles,
- to the constraints Sketcher
- '''
- import FreeCAD, os, Part, math, re, string, Mesh, Draft
- from draftlibs import fcvec, dxfColorMap, dxfLibrary, fcgeo
- from draftlibs.dxfReader import readDXF
- from FreeCAD import Vector
- from importDXF import decodeName,locateLayer,calcBulge,getGroup,getACI,rawValue,vec,fcformat
- from Sketcher import *
- from PyQt4 import QtGui
- try: import FreeCADGui
- except: gui = False
- else: gui = True
- try: draftui = FreeCADGui.draftToolBar
- except: draftui = None
- pythonopen = open # to distinguish python built-in open function from the one declared here
- prec = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft").GetInt("precision")
- def drawLine(line):
- "returns a Sketch line from a dxf line"
- if (len(line.points) > 1):
- v1=vec(line.points[0])
- v2=vec(line.points[1])
- if not fcvec.equals(v1,v2):
- try:
- return Part.Line((v1),(v2))
- except:
- warn(line)
- return None
- def drawArc(arc):
- "returns a Part shape from a dxf arc"
- v=vec(arc.loc)
- d=FreeCAD.Vector(0,0,1)
- firstangle=math.radians(arc.start_angle)
- lastangle=math.radians(arc.end_angle)
- try:
- return v, d, arc.radius,firstangle,lastangle
- except:
- warn(arc)
- return None
- def drawCircle(circle):
- "returns a Part shape from a dxf circle"
- v = vec(circle.loc)
- d=FreeCAD.Vector(0,0,1)
- curve = Part.Circle()
- curve.Radius = circle.radius
- curve.Center = v
- #print v,d,circle.radius
- try:
- return v, d, circle.radius
- except:
- warn(circle)
- return None
- #def drawPolyline(polyline,count):
- # "returns a Part shape from a dxf polyline"
- # if (len(polyline.points) > 1):
- # edges = []
- # curves = False
- # verts = []
- # for p in range(len(polyline.points)-1):
- # p1 = polyline.points[p]
- # p2 = polyline.points[p+1]
- # v1 = FreeCAD.Vector(round(p1[0],prec),round(p1[1],prec),round(p2[2],prec))
- # v2 = FreeCAD.Vector(round(p2[0],prec),round(p2[1],prec),round(p2[2],prec))
- # verts.append(v1)
- # if not fcvec.equals(v1,v2):
- # if polyline.points[p].bulge:
- # curves = True
- # cv = calcBulge(v1,polyline.points[p].bulge,v2)
- # if fcvec.isColinear([v1,cv,v2]):
- # #try: edges.append(Part.Line(v1,v2).toShape())
- # try: f.addGeometry(Part.Line((v1),(v2)))
- # count = count +1
- # except: warn(polyline)
- # else:
- # #try: edges.append(Part.Arc(v1,cv,v2).toShape())
- # try: f.addGeometry(Part.Arc(v1,cv,v2))
- # count = count +1
- # except: warn(polyline)
- # else:
- # #try: edges.append(Part.Line(v1,v2).toShape())
- # try: f.addGeometry(Part.Line((v1),(v2)))
- # count = count +1
- # except: warn(polyline)
- # verts.append(v2)
- # if polyline.closed:
- # p1 = polyline.points[len(polyline.points)-1]
- # p2 = polyline.points[0]
- # v1 = FreeCAD.Vector(round(p1[0],prec),round(p1[1],prec),round(p1[2],prec))
- # v2 = FreeCAD.Vector(round(p2[0],prec),round(p2[1],prec),round(p2[2],prec))
- # cv = calcBulge(v1,polyline.points[-1].bulge,v2)
- # if not fcvec.equals(v1,v2):
- # if fcvec.isColinear([v1,cv,v2]):
- # #try: edges.append(Part.Line(v1,v2).toShape())
- # try: f.addGeometry(Part.Line((v1),(v2)))
- # count = count +1
- # except: warn(polyline)
- # else:
- # #try: edges.append(Part.Arc(v1,cv,v2).toShape())
- # try: f.addGeometry(Part.Arc(v1,cv,v2))
- # count = count +1
- # except: warn(polyline)
- # return count
- def addObject(shape,name="Shape",layer=None):
- "adds a new object to the document with passed arguments"
- if isinstance(shape,Part.Shape):
- newob=doc.addObject("Part::Feature",name)
- newob.Shape = shape
- else:
- newob = shape
- if layer:
- lay=locateLayer(layer)
- lay.addObject(newob)
- return newob
- #def addToBlock(shape,layer):
- # "adds given shape to the layer dict"
- # if layer in layerBlocks:
- # layerBlocks[layer].append(shape)
- # else:
- # layerBlocks[layer] = [shape]
- def new_sketch(sketch_name):
- FreeCAD.ActiveDocument.addObject("Sketcher::SketchObject",sketch_name)
- def processdxf(document,filename):
- "this does the translation of the dxf contents into FreeCAD Part objects"
- global drawing # for debugging - so drawing is still accessible to python after the script
- FreeCAD.Console.PrintMessage("opening "+filename+"...\n")
- drawing = readDXF(filename)
- global layers
- layers = []
- global doc
- doc = document
- global blockshapes
- blockshapes = {}
- global badobjects
- badobjects = []
- global layerBlocks
- layerBlocks = {}
- App = FreeCAD
- f = App.activeDocument().addObject("Sketcher::SketchObject","newSketch")
- # getting config parameters
- global fmt
- fmt = fcformat(drawing)
- shapes = []
- count = 0
- # drawing lines
- sketch = 'f'
- lines = drawing.entities.get_type("line")
- if lines: FreeCAD.Console.PrintMessage("drawing "+str(len(lines))+" lines...\n")
- for line in lines:
- if fmt.dxflayout or (not rawValue(line,67)):
- shape = drawLine(line)
- if shape:
- f.addGeometry(shape)
- if line.layer == 'Construction':
- f.toggleConstruction(count)
- count = count +1
- FreeCAD.Console.PrintMessage("count = "+ str(count) + "\n")
- FreeCAD.Console.PrintMessage("layer = "+ line.layer + "\n")
- # drawing arcs
- arcs = drawing.entities.get_type("arc")
- if arcs: FreeCAD.Console.PrintMessage("drawing "+str(len(arcs))+" arcs...\n")
- for arc in arcs:
- if fmt.dxflayout or (not rawValue(arc,67)):
- shape = drawArc(arc)
- #print shape
- if shape:
- f.addGeometry(Part.ArcOfCircle(Part.Circle(shape[0],shape[1],shape[2]),shape[3],shape[4]))
- if arc.layer == 'Construction':
- f.toggleConstruction(count)
- count = count +1
- FreeCAD.Console.PrintMessage("count = "+ str(count) + "\n")
- # drawing circles
- circles = drawing.entities.get_type("circle")
- if circles: FreeCAD.Console.PrintMessage("drawing "+str(len(circles))+" circles...\n")
- for circle in circles:
- if fmt.dxflayout or (not rawValue(circle,67)):
- shape = drawCircle(circle)
- if shape:
- f.addGeometry(Part.Circle((shape[0]), (shape[1]), (shape[2]) ) )
- if circle.layer == 'Construction':
- f.toggleConstruction(count)
- count = count +1
- FreeCAD.Console.PrintMessage("count = "+ str(count) + "\n")
- # drawing polylines
- # pls = drawing.entities.get_type("lwpolyline")
- # pls.extend(drawing.entities.get_type("polyline"))
- # polylines = []
- # meshes = []
- # for p in pls:
- # if hasattr(p,"flags"):
- # if p.flags in [16,64]:
- # meshes.append(p)
- # else:
- # polylines.append(p)
- # else:
- # polylines.append(p)
- # if polylines: FreeCAD.Console.PrintMessage("drawing "+str(len(polylines))+" polylines...\n")
- # for polyline in polylines:
- # if fmt.dxflayout or (not rawValue(polyline,67)):
- # shape = drawPolyline(polyline,count)
- # if shape:
- # if fmt.join:
- # if isinstance(shape,Part.Shape):
- # shapes.append(shape)
- # else:
- # shapes.append(shape.Shape)
- # elif fmt.makeBlocks:
- # if isinstance(shape,Part.Shape):
- # addToBlock(shape,polyline.layer)
- # else:
- # addToBlock(shape.Shape,polyline.layer)
- # else:
- # newob = addObject(shape,"Polyline",polyline.layer)
- # if gui: fmt.formatObject(newob,polyline)
- # finishing
- doc.recompute()
- FreeCAD.Console.PrintMessage("successfully imported "+filename+"\n")
- if badobjects: print "dxf: ",len(badobjects)," objects were not imported"
- del fmt
- del doc
- del blockshapes
- def warn(dxfobject):
- "outputs a warning if a dxf object couldn't be imported"
- print "dxf: couldn't import", dxfobject
- badobjects.append(dxfobject)
- def open(filename):
- "called when freecad opens a file."
- docname = os.path.splitext(os.path.basename(filename))[0]
- doc = FreeCAD.newDocument(docname)
- doc.Label = decodeName(docname)
- processdxf(doc,filename)
- return doc
- def insert(filename,docname):
- "called when freecad imports a file"
- #groupname = os.path.splitext(os.path.basename(filename))[0]
- try:
- doc=FreeCAD.getDocument(docname)
- except:
- doc=FreeCAD.newDocument(docname)
- #importgroup = doc.addObject("App::DocumentObjectGroup",groupname)
- #importgroup.Label = decodeName(groupname)
- processdxf(doc,filename)
- for l in layers:
- importgroup.addObject(l)
- doc = FreeCAD.ActiveDocument.Name
- filename = QtGui.QFileDialog.getOpenFileName(QtGui.qApp.activeWindow(),'Open DXF file','*.txt')
- insert(filename,doc)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement