Code

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