1 #!/usr/bin/env python
2 '''
3 Copyright (C) 2005,2007,2008 Aaron Spike, aaron@ekips.org
4 Copyright (C) 2008,2010 Alvin Penner, penner@vaxxine.com
6 - template dxf_outlines.dxf added Feb 2008 by Alvin Penner
7 - ROBO-Master output option added Aug 2008
8 - ROBO-Master multispline output added Sept 2008
9 - LWPOLYLINE output modification added Dec 2008
10 - toggle between LINE/LWPOLYLINE added Jan 2010
11 - support for transform elements added July 2010
12 - support for layers added July 2010
14 This program is free software; you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation; either version 2 of the License, or
17 (at your option) any later version.
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 '''
28 import inkex, simplestyle, simpletransform, cubicsuperpath, coloreffect, dxf_templates, math
29 import gettext
30 _ = gettext.gettext
32 try:
33 from numpy import *
34 from numpy.linalg import solve
35 except:
36 inkex.errormsg(_("Failed to import the numpy or numpy.linalg modules. These modules are required by this extension. Please install them and try again."))
37 inkex.sys.exit()
39 def pointdistance((x1,y1),(x2,y2)):
40 return math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2))
42 def get_fit(u, csp, col):
43 return (1-u)**3*csp[0][col] + 3*(1-u)**2*u*csp[1][col] + 3*(1-u)*u**2*csp[2][col] + u**3*csp[3][col]
45 def get_matrix(u, i, j):
46 if j == i + 2:
47 return (u[i]-u[i-1])*(u[i]-u[i-1])/(u[i+2]-u[i-1])/(u[i+1]-u[i-1])
48 elif j == i + 1:
49 return ((u[i]-u[i-1])*(u[i+2]-u[i])/(u[i+2]-u[i-1]) + (u[i+1]-u[i])*(u[i]-u[i-2])/(u[i+1]-u[i-2]))/(u[i+1]-u[i-1])
50 elif j == i:
51 return (u[i+1]-u[i])*(u[i+1]-u[i])/(u[i+1]-u[i-2])/(u[i+1]-u[i-1])
52 else:
53 return 0
55 class MyEffect(inkex.Effect):
56 def __init__(self):
57 inkex.Effect.__init__(self)
58 self.OptionParser.add_option("-R", "--ROBO", action="store", type="string", dest="ROBO")
59 self.OptionParser.add_option("-P", "--POLY", action="store", type="string", dest="POLY")
60 self.OptionParser.add_option("--tab", action="store", type="string", dest="tab")
61 self.OptionParser.add_option("--inputhelp", action="store", type="string", dest="inputhelp")
62 self.dxf = []
63 self.handle = 255 # handle for DXF ENTITY
64 self.layers = ['0']
65 self.layer = '0' # mandatory layer
66 self.csp_old = [[0.0,0.0]]*4 # previous spline
67 self.d = array([0], float) # knot vector
68 self.poly = [[0.0,0.0]] # LWPOLYLINE data
69 def output(self):
70 print ''.join(self.dxf)
71 def dxf_add(self, str):
72 self.dxf.append(str)
73 def dxf_line(self,csp):
74 self.handle += 1
75 self.dxf_add(" 0\nLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbLine\n" % (self.handle, self.layer, self.color))
76 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n 11\n%f\n 21\n%f\n 31\n0.0\n" % (csp[0][0],csp[0][1],csp[1][0],csp[1][1]))
77 def LWPOLY_line(self,csp):
78 if (abs(csp[0][0] - self.poly[-1][0]) > .0001
79 or abs(csp[0][1] - self.poly[-1][1]) > .0001):
80 self.LWPOLY_output() # terminate current polyline
81 self.poly = [csp[0]] # initiallize new polyline
82 self.color_LWPOLY = self.color
83 self.layer_LWPOLY = self.layer
84 self.poly.append(csp[1])
85 def LWPOLY_output(self):
86 if len(self.poly) == 1:
87 return
88 self.handle += 1
89 self.dxf_add(" 0\nLWPOLYLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbPolyline\n 90\n%d\n 70\n0\n" % (self.handle, self.layer_LWPOLY, self.color_LWPOLY, len(self.poly)))
90 for i in range(len(self.poly)):
91 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (self.poly[i][0],self.poly[i][1]))
92 def dxf_spline(self,csp):
93 knots = 8
94 ctrls = 4
95 self.handle += 1
96 self.dxf_add(" 0\nSPLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbSpline\n" % (self.handle, self.layer, self.color))
97 self.dxf_add(" 70\n8\n 71\n3\n 72\n%d\n 73\n%d\n 74\n0\n" % (knots, ctrls))
98 for i in range(2):
99 for j in range(4):
100 self.dxf_add(" 40\n%d\n" % i)
101 for i in csp:
102 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (i[0],i[1]))
103 def ROBO_spline(self,csp):
104 # this spline has zero curvature at the endpoints, as in ROBO-Master
105 if (abs(csp[0][0] - self.csp_old[3][0]) > .0001
106 or abs(csp[0][1] - self.csp_old[3][1]) > .0001
107 or abs((csp[1][1]-csp[0][1])*(self.csp_old[3][0]-self.csp_old[2][0]) - (csp[1][0]-csp[0][0])*(self.csp_old[3][1]-self.csp_old[2][1])) > .001):
108 self.ROBO_output() # terminate current spline
109 self.xfit = array([csp[0][0]], float) # initiallize new spline
110 self.yfit = array([csp[0][1]], float)
111 self.d = array([0], float)
112 self.color_ROBO = self.color
113 self.layer_ROBO = self.layer
114 self.xfit = concatenate((self.xfit, zeros((3)))) # append to current spline
115 self.yfit = concatenate((self.yfit, zeros((3))))
116 self.d = concatenate((self.d, zeros((3))))
117 for i in range(1, 4):
118 j = len(self.d) + i - 4
119 self.xfit[j] = get_fit(i/3.0, csp, 0)
120 self.yfit[j] = get_fit(i/3.0, csp, 1)
121 self.d[j] = self.d[j-1] + pointdistance((self.xfit[j-1],self.yfit[j-1]),(self.xfit[j],self.yfit[j]))
122 self.csp_old = csp
123 def ROBO_output(self):
124 if len(self.d) == 1:
125 return
126 fits = len(self.d)
127 ctrls = fits + 2
128 knots = ctrls + 4
129 self.xfit = concatenate((self.xfit, zeros((2)))) # pad with 2 endpoint constraints
130 self.yfit = concatenate((self.yfit, zeros((2)))) # pad with 2 endpoint constraints
131 self.d = concatenate((self.d, zeros((6)))) # pad with 3 duplicates at each end
132 self.d[fits+2] = self.d[fits+1] = self.d[fits] = self.d[fits-1]
133 solmatrix = zeros((ctrls,ctrls), dtype=float)
134 for i in range(fits):
135 solmatrix[i,i] = get_matrix(self.d, i, i)
136 solmatrix[i,i+1] = get_matrix(self.d, i, i+1)
137 solmatrix[i,i+2] = get_matrix(self.d, i, i+2)
138 solmatrix[fits, 0] = self.d[2]/self.d[fits-1] # curvature at start = 0
139 solmatrix[fits, 1] = -(self.d[1] + self.d[2])/self.d[fits-1]
140 solmatrix[fits, 2] = self.d[1]/self.d[fits-1]
141 solmatrix[fits+1, fits-1] = (self.d[fits-1] - self.d[fits-2])/self.d[fits-1] # curvature at end = 0
142 solmatrix[fits+1, fits] = (self.d[fits-3] + self.d[fits-2] - 2*self.d[fits-1])/self.d[fits-1]
143 solmatrix[fits+1, fits+1] = (self.d[fits-1] - self.d[fits-3])/self.d[fits-1]
144 xctrl = solve(solmatrix, self.xfit)
145 yctrl = solve(solmatrix, self.yfit)
146 self.handle += 1
147 self.dxf_add(" 0\nSPLINE\n 5\n%x\n100\nAcDbEntity\n 8\n%s\n 62\n%d\n100\nAcDbSpline\n" % (self.handle, self.layer_ROBO, self.color_ROBO))
148 self.dxf_add(" 70\n0\n 71\n3\n 72\n%d\n 73\n%d\n 74\n%d\n" % (knots, ctrls, fits))
149 for i in range(knots):
150 self.dxf_add(" 40\n%f\n" % self.d[i-3])
151 for i in range(ctrls):
152 self.dxf_add(" 10\n%f\n 20\n%f\n 30\n0.0\n" % (xctrl[i],yctrl[i]))
153 for i in range(fits):
154 self.dxf_add(" 11\n%f\n 21\n%f\n 31\n0.0\n" % (self.xfit[i],self.yfit[i]))
156 def process_path(self, node, mat):
157 rgb = (0,0,0)
158 style = node.get('style')
159 if style:
160 style = simplestyle.parseStyle(style)
161 if style.has_key('stroke'):
162 if style['stroke'] and style['stroke'] != 'none':
163 rgb = simplestyle.parseColor(style['stroke'])
164 hsl = coloreffect.ColorEffect.rgb_to_hsl(coloreffect.ColorEffect(),rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0)
165 self.color = 7 # default is black
166 if hsl[2]:
167 self.color = 1 + (int(6*hsl[0] + 0.5) % 6) # use 6 hues
168 d = node.get('d')
169 if d:
170 p = cubicsuperpath.parsePath(d)
171 trans = node.get('transform')
172 if trans:
173 mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
174 simpletransform.applyTransformToPath(mat, p)
175 for sub in p:
176 for i in range(len(sub)-1):
177 s = sub[i]
178 e = sub[i+1]
179 if s[1] == s[2] and e[0] == e[1]:
180 if (self.options.POLY == 'true'):
181 self.LWPOLY_line([s[1],e[1]])
182 else:
183 self.dxf_line([s[1],e[1]])
184 elif (self.options.ROBO == 'true'):
185 self.ROBO_spline([s[1],s[2],e[0],e[1]])
186 else:
187 self.dxf_spline([s[1],s[2],e[0],e[1]])
189 def process_group(self, group):
190 if group.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
191 layer = group.get(inkex.addNS('label', 'inkscape'))
192 layer = layer.replace(' ', '_')
193 if layer in self.layers:
194 self.layer = layer
195 trans = group.get('transform')
196 if trans:
197 self.groupmat.append(simpletransform.composeTransform(self.groupmat[-1], simpletransform.parseTransform(trans)))
198 for node in group:
199 if node.tag == inkex.addNS('path','svg'):
200 self.process_path(node, self.groupmat[-1])
201 if node.tag == inkex.addNS('g','svg'):
202 self.process_group(node)
203 if trans:
204 self.groupmat.pop()
206 def effect(self):
207 #References: Minimum Requirements for Creating a DXF File of a 3D Model By Paul Bourke
208 # NURB Curves: A Guide for the Uninitiated By Philip J. Schneider
209 # The NURBS Book By Les Piegl and Wayne Tiller (Springer, 1995)
210 self.dxf_add("999\nDXF created by Inkscape\n")
211 self.dxf_add(dxf_templates.r14_header)
212 for node in self.document.getroot().xpath('//svg:g', namespaces=inkex.NSS):
213 if node.get(inkex.addNS('groupmode', 'inkscape')) == 'layer':
214 layer = node.get(inkex.addNS('label', 'inkscape'))
215 layer = layer.replace(' ', '_')
216 if layer and not layer in self.layers:
217 self.layers.append(layer)
218 self.dxf_add(" 2\nLAYER\n 5\n2\n100\nAcDbSymbolTable\n 70\n%s\n" % len(self.layers))
219 for i in range(len(self.layers)):
220 self.dxf_add(" 0\nLAYER\n 5\n%x\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n%s\n 70\n0\n 6\nCONTINUOUS\n" % (i + 80, self.layers[i]))
221 self.dxf_add(dxf_templates.r14_style)
223 scale = 25.4/90.0
224 h = inkex.unittouu(self.document.getroot().xpath('@height', namespaces=inkex.NSS)[0])
225 self.groupmat = [[[scale, 0.0, 0.0], [0.0, -scale, h*scale]]]
226 doc = self.document.getroot()
227 self.process_group(doc)
228 if self.options.ROBO == 'true':
229 self.ROBO_output()
230 if self.options.POLY == 'true':
231 self.LWPOLY_output()
232 self.dxf_add(dxf_templates.r14_footer)
234 if __name__ == '__main__':
235 e = MyEffect()
236 e.affect()
239 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99