Code

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