merger to harmonize svg patches
[org.ibex.core.git] / src / org / ibex / graphics / Path.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the GNU General Public License version 2 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 // FIXME
6 package org.ibex.graphics;
7 import java.util.*;
8 import org.ibex.util.*;
9
10 /** an abstract path; may contain splines and arcs */
11 public class Path {
12
13     public static final float PX_PER_INCH = 72;
14     public static final float INCHES_PER_CM = (float)0.3937;
15     public static final float INCHES_PER_MM = INCHES_PER_CM / 10;
16     private static final int DEFAULT_PATHLEN = 1000;
17     private static final float PI = (float)Math.PI;
18
19     // the number of vertices on this path
20     int numvertices = 0;
21
22     // the vertices of the path
23     float[] x = new float[DEFAULT_PATHLEN];
24     float[] y = new float[DEFAULT_PATHLEN];
25
26     // the type of each edge; type[i] is the type of the edge from x[i],y[i] to x[i+1],y[i+1]
27     byte[] type = new byte[DEFAULT_PATHLEN];
28
29     // bezier control points
30     float[] c1x = new float[DEFAULT_PATHLEN];  // or rx (arcto)
31     float[] c1y = new float[DEFAULT_PATHLEN];  // or ry (arcto)
32     float[] c2x = new float[DEFAULT_PATHLEN];  // or x-axis-rotation (arcto)
33     float[] c2y = new float[DEFAULT_PATHLEN];  // or large-arc << 1 | sweep (arcto)
34
35     boolean closed = false;
36
37     static final byte TYPE_MOVETO = 0;
38     static final byte TYPE_LINETO = 1;
39     static final byte TYPE_ARCTO = 2;
40     static final byte TYPE_CUBIC = 3;
41     static final byte TYPE_QUADRADIC = 4;
42
43     // FIXME: hack
44     private String toString;
45     public String toString() { return toString; }
46
47     public Path(String s) {
48         this.toString = s;
49         Tokenizer t = new Tokenizer(s);
50         char last_command = 'M';
51         boolean first = true;
52         while(t.hasMoreTokens()) {
53             char command = t.parseCommand();
54             if (first && command == 'm') command = 'M';
55             if (first && command != 'M') throw new RuntimeException("the first command of a path must be 'M'");
56             first = false;
57             boolean relative = Character.toLowerCase(command) == command;
58             command = Character.toLowerCase(command);
59             parseSingleCommandAndArguments(t, command, relative);
60             last_command = command;
61         }
62     }
63
64     public long transform(Affine a, boolean forReal) { return transform(a, forReal, true); }
65     public long transform(Affine a, boolean forReal, boolean widthheight) {
66         float minx = Integer.MAX_VALUE; float miny = Integer.MAX_VALUE;
67         float maxx = Integer.MIN_VALUE; float maxy = Integer.MIN_VALUE;
68         for(int i=0; i<numvertices; i++) {
69             if (type[i] == TYPE_ARCTO) { /* FIXME!!! WRONG!!!! */ continue; }
70             float x   = a.multiply_px(this.x[i],   this.y[i]);    if (x>maxx) maxx = x; if (x<minx) minx = x;
71             float y   = a.multiply_py(this.x[i],   this.y[i]);    if (y>maxy) maxy = y; if (y<miny) miny = y;
72             float c1x = a.multiply_px(this.c1x[i], this.c1y[i]);  if (c1x>maxx) maxx = c1x; if (c1x<minx) minx = c1x;
73             float c1y = a.multiply_py(this.c1x[i], this.c1y[i]);  if (c1y>maxy) maxy = c1y; if (c1y<miny) miny = c1y;
74             float c2x = a.multiply_px(this.c2x[i], this.c2y[i]);  if (c2x>maxx) maxx = c2x; if (c2x<minx) minx = c2x;
75             float c2y = a.multiply_py(this.c2x[i], this.c2y[i]);  if (c2y>maxy) maxy = c2y; if (c2y<miny) miny = c2y;
76             if (forReal) {
77                 this.x[i] = x; this.y[i] = y;
78                 this.c1x[i] = c1x; this.c1y[i] = c1y;
79                 this.c2x[i] = c2x; this.c2y[i] = c2y;
80             }
81         }
82         if (widthheight) return ((((long)Float.floatToIntBits(maxx - minx)) << 32) | ((long)Float.floatToIntBits(maxy - miny)));
83         else return ((((long)Float.floatToIntBits(minx)) << 32) | ((long)Float.floatToIntBits(miny)));
84     }
85
86     public void alignToOrigin() {
87         float minx = Integer.MAX_VALUE; float miny = Integer.MAX_VALUE;
88         for(int i=0; i<numvertices; i++) { if (x[i] < minx) minx = x[i]; if (y[i] < miny) miny = y[i]; }
89         for(int i=0; i<numvertices; i++) {
90             x[i] -= minx; y[i] -= miny;
91             if (type[i] == TYPE_ARCTO) continue;
92             c1x[i] -= minx; c2x[i] -= minx; c1y[i] -= miny; c2y[i] -= miny;
93         }
94     }
95
96
97     public static class Tokenizer {
98         // FIXME: check array bounds exception for improperly terminated string
99         String s;
100         int i = 0;
101         char lastCommand = 'M';
102         public Tokenizer(String s) { this.s = s; }
103             
104         public static Path parse(String s) {
105             if (s == null) return null;
106             Tokenizer t = new Tokenizer(s);
107             Path ret = new Path(s);
108             char last_command = 'M';
109             boolean first = true;
110             while(t.hasMoreTokens()) {
111                 char command = t.parseCommand();
112                 if (first && command != 'M') throw new RuntimeException("the first command of a path must be 'M'");
113                 first = false;
114                 boolean relative = Character.toLowerCase(command) == command;
115                 command = Character.toLowerCase(command);
116                 ret.parseSingleCommandAndArguments(t, command, relative);
117                 last_command = command;
118             }
119             return ret;
120         }
121
122         private void consumeWhitespace() {
123             while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
124             if (i < s.length() && s.charAt(i) == ',') i++;
125             while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
126         }
127         public boolean hasMoreTokens() { consumeWhitespace(); return i < s.length(); }
128         public char parseCommand() {
129             consumeWhitespace();
130             char c = s.charAt(i);
131             if (!Character.isLetter(c)) return lastCommand;
132             i++;
133             return lastCommand = c;
134         }
135         public float parseFloat() {
136             consumeWhitespace();
137             int start = i;
138             float multiplier = 1;
139             for(; i < s.length(); i++) {
140                 char c = s.charAt(i);
141                 if (Character.isWhitespace(c) || c == ',' || (c == '-' && i != start)) break;
142                 if (!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '-')) {
143                     if (c == '%') {                                // FIXME
144                     } else if (s.regionMatches(i, "pt", 0, i+2)) { // FIXME
145                     } else if (s.regionMatches(i, "em", 0, i+2)) { // FIXME
146                     } else if (s.regionMatches(i, "pc", 0, i+2)) { // FIXME
147                     } else if (s.regionMatches(i, "ex", 0, i+2)) { // FIXME
148                     } else if (s.regionMatches(i, "mm", 0, i+2)) { i += 2; multiplier = INCHES_PER_MM * PX_PER_INCH; break;
149                     } else if (s.regionMatches(i, "cm", 0, i+2)) { i += 2; multiplier = INCHES_PER_CM * PX_PER_INCH; break;
150                     } else if (s.regionMatches(i, "in", 0, i+2)) { i += 2; multiplier = PX_PER_INCH; break;
151                     } else if (s.regionMatches(i, "px", 0, i+2)) { i += 2; break;
152                     } else if (Character.isLetter(c)) break;
153                     throw new RuntimeException("didn't expect character \"" + c + "\" in a numeric constant");
154                 }
155             }
156             //if (start == i) throw new RuntimeException("FIXME");
157             if (start == i) return (float)0.0;
158             try {
159                 return Float.parseFloat(s.substring(start, i)) * multiplier;
160             } catch (NumberFormatException nfe) {
161                 Log.warn(Path.class, "offending string was \"" + s.substring(start, i) + "\"");
162                 throw nfe;
163             }
164         }
165     }
166
167     /** Creates a concrete vector path transformed through the given matrix. */
168     public void addTo(Polygon ret, Affine a) {
169         float NUMSTEPS = 5;  // FIXME
170         ret.x[0] = a.multiply_px(x[0], y[0]);
171         ret.y[0] = a.multiply_py(x[0], y[0]);
172
173         for(int i=0; i<numvertices; i++) {
174             if (type[i] == TYPE_LINETO) {
175                 float rx = x[i+1];
176                 float ry = y[i+1];
177                 ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
178
179             } else if (type[i] == TYPE_MOVETO) {
180                 float rx = x[i+1];
181                 float ry = y[i+1];
182                 ret.newcontour();
183                 ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
184
185             } else if (type[i] == TYPE_ARCTO) {
186                 float rx = c1x[i];
187                 float ry = c1y[i];
188                 float phi = c2x[i];
189                 float fa = ((int)c2y[i]) >> 1;
190                 float fs = ((int)c2y[i]) & 1;
191                 float x1 = x[i];
192                 float y1 = y[i];
193                 float x2 = x[i+1];
194                 float y2 = y[i+1];
195
196                 // F.6.5: given x1,y1,x2,y2,fa,fs, compute cx,cy,theta1,dtheta
197                 float x1_ = (float)Math.cos(phi) * (x1 - x2) / 2 + (float)Math.sin(phi) * (y1 - y2) / 2;
198                 float y1_ = -1 * (float)Math.sin(phi) * (x1 - x2) / 2 + (float)Math.cos(phi) * (y1 - y2) / 2;
199                 float tmp = (float)Math.sqrt((rx * rx * ry * ry - rx * rx * y1_ * y1_ - ry * ry * x1_ * x1_) /
200                                              (rx * rx * y1_ * y1_ + ry * ry * x1_ * x1_));
201                 float cx_ = (fa == fs ? -1 : 1) * tmp * (rx * y1_ / ry);
202                 float cy_ = (fa == fs ? -1 : 1) * -1 * tmp * (ry * x1_ / rx);
203                 float cx = (float)Math.cos(phi) * cx_ - (float)Math.sin(phi) * cy_ + (x1 + x2) / 2;
204                 float cy = (float)Math.sin(phi) * cx_ + (float)Math.cos(phi) * cy_ + (y1 + y2) / 2;
205
206                 // F.6.4 Conversion from center to endpoint parameterization
207                 float ux = 1, uy = 0, vx = (x1_ - cx_) / rx, vy = (y1_ - cy_) / ry;
208                 float det = ux * vy - uy * vx;
209                 float theta1 = (det < 0 ? -1 : 1) *
210                     (float)Math.acos((ux * vx + uy * vy) / 
211                                      ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
212                 ux = (x1_ - cx_) / rx; uy = (y1_ - cy_) / ry;
213                 vx = (-1 * x1_ - cx_) / rx; vy = (-1 * y1_ - cy_) / ry;
214                 det = ux * vy - uy * vx;
215                 float dtheta = (det < 0 ? -1 : 1) *
216                     (float)Math.acos((ux * vx + uy * vy) / 
217                                      ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
218                 dtheta = dtheta % (float)(2 * Math.PI);
219
220                 if (fs == 0 && dtheta > 0) theta1 -= 2 * PI; 
221                 if (fs == 1 && dtheta < 0) theta1 += 2 * PI;
222
223                 if (fa == 1 && dtheta < 0) dtheta = 2 * PI + dtheta;
224                 else if (fa == 1 && dtheta > 0) dtheta = -1 * (2 * PI - dtheta);
225
226                 // FIXME: integrate F.6.6
227                 // FIXME: isn't quite ending where it should...
228
229                 // F.6.3: Parameterization alternatives
230                 float theta = theta1;
231                 for(int j=0; j<NUMSTEPS; j++) {
232                     float rasterx = rx * (float)Math.cos(theta) * (float)Math.cos(phi) -
233                         ry * (float)Math.sin(theta) * (float)Math.sin(phi) + cx;
234                     float rastery = rx * (float)Math.cos(theta) * (float)Math.sin(phi) +
235                         ry * (float)Math.cos(phi) * (float)Math.sin(theta) + cy;
236                     ret.add(a.multiply_px(rasterx, rastery), a.multiply_py(rasterx, rastery));
237                     theta += dtheta / NUMSTEPS;
238                 }
239
240             } else if (type[i] == TYPE_CUBIC) {
241
242                 float ax = x[i+1] - 3 * c2x[i] + 3 * c1x[i] - x[i];
243                 float bx = 3 * c2x[i] - 6 * c1x[i] + 3 * x[i];
244                 float cx = 3 * c1x[i] - 3 * x[i];
245                 float dx = x[i];
246                 float ay = y[i+1] - 3 * c2y[i] + 3 * c1y[i] - y[i];
247                 float by = 3 * c2y[i] - 6 * c1y[i] + 3 * y[i];
248                 float cy = 3 * c1y[i] - 3 * y[i];
249                 float dy = y[i];
250                     
251                 float x0 = a.multiply_px(x[i], y[i]);
252                 float y0 = a.multiply_py(x[i], y[i]);
253                 float x1 = a.multiply_px(x[i+1], y[i+1]);
254                 float y1 = a.multiply_py(x[i+1], y[i+1]);
255                 float steps = (float)Math.sqrt( (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0) );
256
257                 for(float t=0; t<1; t += 1 / (steps/20)) {
258                     float rx = ax * t * t * t + bx * t * t + cx * t + dx;
259                     float ry = ay * t * t * t + by * t * t + cy * t + dy;
260                     ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
261                 }
262
263
264             } else if (type[i] == TYPE_QUADRADIC) {
265
266                 float bx = x[i+1] - 2 * c1x[i] + x[i];
267                 float cx = 2 * c1x[i] - 2 * x[i];
268                 float dx = x[i];
269                 float by = y[i+1] - 2 * c1y[i] + y[i];
270                 float cy = 2 * c1y[i] - 2 * y[i];
271                 float dy = y[i];
272                         
273                 float x0 = a.multiply_px(x[i], y[i]);
274                 float y0 = a.multiply_py(x[i], y[i]);
275                 float x1 = a.multiply_px(x[i+1], y[i+1]);
276                 float y1 = a.multiply_py(x[i+1], y[i+1]);
277                 float steps = (float)Math.sqrt( (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0) );
278
279                 for(float t=0; t<1; t += 1 / (steps/20)) {
280                     float rx = bx * t * t + cx * t + dx;
281                     float ry = by * t * t + cy * t + dy;
282                     ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
283                 }
284
285             }
286         }
287     }
288
289     protected void parseSingleCommandAndArguments(Tokenizer t, char command, boolean relative) {
290         if (numvertices == 0 && command != 'm')
291             throw new RuntimeException("first command MUST be an 'm', not a " + command);
292         if (numvertices > x.length - 2) {
293             float[] new_x = new float[x.length * 2]; System.arraycopy(x, 0, new_x, 0, x.length); x = new_x;
294             float[] new_y = new float[y.length * 2]; System.arraycopy(y, 0, new_y, 0, y.length); y = new_y;
295         }
296         switch(command) {
297             case 'z': {
298                 int where;
299                 type[numvertices-1] = TYPE_LINETO;
300                 for(where = numvertices-2; where >= 0 && type[where] != TYPE_MOVETO; where--);
301                 x[numvertices] = x[where+1];
302                 y[numvertices] = y[where+1];
303                 numvertices++;
304                 closed = true;
305                 // FIXME: actually, we should search back to the last 'z' or 'm', not just 'm'
306                 break;
307             }
308
309             case 'm': {
310                 if (numvertices > 0) type[numvertices-1] = TYPE_MOVETO;
311                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
312                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
313                 if (numvertices > 2 && type[numvertices-2] == TYPE_MOVETO) {
314                     x[numvertices-1] = x[numvertices];
315                     y[numvertices-1] = y[numvertices];
316                 } else {
317                     numvertices++;
318                 }
319                 break;
320             }
321
322             case 'l': case 'h': case 'v': {
323                 type[numvertices-1] = TYPE_LINETO;
324                 float first = t.parseFloat(), second;
325                 if (command == 'h') {
326                     second = relative ? 0 : y[numvertices - 1];
327                 } else if (command == 'v') {
328                     second = first; first = relative ? 0 : x[numvertices - 1];
329                 } else {
330                     second = t.parseFloat();
331                 }
332                 x[numvertices] = first + (relative ? x[numvertices - 1] : 0);
333                 y[numvertices] = second + (relative ? y[numvertices - 1] : 0);
334                 numvertices++;
335                 break;
336             }
337             
338             case 'a': {
339                 type[numvertices-1] = TYPE_ARCTO;
340                 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
341                 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
342                 c2x[numvertices-1] = (t.parseFloat() / 360) * 2 * PI;
343                 c2y[numvertices-1] = (((int)t.parseFloat()) << 1) | (int)t.parseFloat();
344                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
345                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
346                 numvertices++;
347                 break;
348             }
349
350             case 's': case 'c': {
351                 type[numvertices-1] = TYPE_CUBIC;
352                 if (command == 'c') {
353                     c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
354                     c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
355                 } else if (numvertices > 1 && type[numvertices-2] == TYPE_CUBIC) {
356                     c1x[numvertices-1] = 2 * x[numvertices - 1] - c2x[numvertices-2];
357                     c1y[numvertices-1] = 2 * y[numvertices - 1] - c2y[numvertices-2];
358                 } else {
359                     c1x[numvertices-1] = x[numvertices-1];
360                     c1y[numvertices-1] = y[numvertices-1];
361                 }
362                 c2x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
363                 c2y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
364                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
365                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
366                 numvertices++;
367                 break;
368             }
369
370             case 't': case 'q': {
371                 type[numvertices-1] = TYPE_QUADRADIC;
372                 if (command == 'q') {
373                     c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
374                     c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
375                 } else if (numvertices > 1 && type[numvertices-2] == TYPE_QUADRADIC) {
376                     c1x[numvertices-1] = 2 * x[numvertices - 1] - c1x[numvertices-2];
377                     c1y[numvertices-1] = 2 * y[numvertices - 1] - c1y[numvertices-2];
378                 } else {
379                     c1x[numvertices-1] = x[numvertices-1];
380                     c1y[numvertices-1] = y[numvertices-1];
381                 }
382                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
383                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
384                 numvertices++;
385                 break;
386             }
387
388             default:
389                 // FIXME
390         }
391
392         /*
393         // invariant: after this loop, no two lines intersect other than at a vertex
394         // FIXME: cleanup
395         int index = numvertices - 2;
396         for(int i=0; i<Math.min(numvertices - 3, index); i++) {
397         for(int j = index; j < numvertices - 1; j++) {
398
399         // I'm not sure how to deal with vertical lines...
400         if (x[i+1] == x[i] || x[j+1] == x[j]) continue;
401                         
402         float islope = (y[i+1] - y[i]) / (x[i+1] - x[i]);
403         float jslope = (y[j+1] - y[j]) / (x[j+1] - x[j]);
404         if (islope == jslope) continue;   // parallel lines can't intersect
405                         
406         float _x = (islope * x[i] - jslope * x[j] + y[j] - y[i]) / (islope - jslope);
407         float _y = islope * (_x - x[i]) + y[i];
408                         
409         if (_x > Math.min(x[i+1], x[i]) && _x < Math.max(x[i+1], x[i]) &&
410         _x > Math.min(x[j+1], x[j]) && _x < Math.max(x[j+1], x[j])) {
411         // FIXME: something's not right in here.  See if we can do without fracturing line 'i'.
412         for(int k = ++numvertices; k>i; k--) { x[k] = x[k - 1]; y[k] = y[k - 1]; }
413         x[i+1] = _x;
414         y[i+1] = _y;
415         x[numvertices] = x[numvertices - 1];  x[numvertices - 1] = _x;
416         y[numvertices] = y[numvertices - 1];  y[numvertices - 1] = _y;
417         edges[numedges++] = numvertices - 1; numvertices++;
418         index++;
419         break;  // actually 'continue' the outermost loop
420         }
421         }
422         }
423         */
424
425     }
426
427 }