Code

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