added smoother vectorization to Path.java, did some reorg
[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     // FIXME: hack
98     private String toString;
99     private Path(String s) { this.toString = s; }
100     public String toString() { return toString; }
101
102     public static class Tokenizer {
103         // FIXME: check array bounds exception for improperly terminated string
104         String s;
105         int i = 0;
106         char lastCommand = 'M';
107         public Tokenizer(String s) { this.s = s; }
108             
109         public static Path parse(String s) {
110             if (s == null) return null;
111             Tokenizer t = new Tokenizer(s);
112             Path ret = new Path(s);
113             char last_command = 'M';
114             boolean first = true;
115             while(t.hasMoreTokens()) {
116                 char command = t.parseCommand();
117                 if (first && command != 'M') throw new RuntimeException("the first command of a path must be 'M'");
118                 first = false;
119                 boolean relative = Character.toLowerCase(command) == command;
120                 command = Character.toLowerCase(command);
121                 ret.parseSingleCommandAndArguments(t, command, relative);
122                 last_command = command;
123             }
124             return ret;
125         }
126
127         private void consumeWhitespace() {
128             while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
129             if (i < s.length() && s.charAt(i) == ',') i++;
130             while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
131         }
132         public boolean hasMoreTokens() { consumeWhitespace(); return i < s.length(); }
133         public char parseCommand() {
134             consumeWhitespace();
135             char c = s.charAt(i);
136             if (!Character.isLetter(c)) return lastCommand;
137             i++;
138             return lastCommand = c;
139         }
140         public float parseFloat() {
141             consumeWhitespace();
142             int start = i;
143             float multiplier = 1;
144             for(; i < s.length(); i++) {
145                 char c = s.charAt(i);
146                 if (Character.isWhitespace(c) || c == ',' || (c == '-' && i != start)) break;
147                 if (!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '-')) {
148                     if (c == '%') {                                // FIXME
149                     } else if (s.regionMatches(i, "pt", 0, i+2)) { // FIXME
150                     } else if (s.regionMatches(i, "em", 0, i+2)) { // FIXME
151                     } else if (s.regionMatches(i, "pc", 0, i+2)) { // FIXME
152                     } else if (s.regionMatches(i, "ex", 0, i+2)) { // FIXME
153                     } else if (s.regionMatches(i, "mm", 0, i+2)) { i += 2; multiplier = INCHES_PER_MM * PX_PER_INCH; break;
154                     } else if (s.regionMatches(i, "cm", 0, i+2)) { i += 2; multiplier = INCHES_PER_CM * PX_PER_INCH; break;
155                     } else if (s.regionMatches(i, "in", 0, i+2)) { i += 2; multiplier = PX_PER_INCH; break;
156                     } else if (s.regionMatches(i, "px", 0, i+2)) { i += 2; break;
157                     } else if (Character.isLetter(c)) break;
158                     throw new RuntimeException("didn't expect character \"" + c + "\" in a numeric constant");
159                 }
160             }
161             //if (start == i) throw new RuntimeException("FIXME");
162             if (start == i) return (float)0.0;
163             try {
164                 return Float.parseFloat(s.substring(start, i)) * multiplier;
165             } catch (NumberFormatException nfe) {
166                 Log.warn(Path.class, "offending string was \"" + s.substring(start, i) + "\"");
167                 throw nfe;
168             }
169         }
170     }
171
172     /** Creates a concrete vector path transformed through the given matrix. */
173     public void addTo(Polygon ret, Affine a) {
174         long start = System.currentTimeMillis(); try {
175         float NUMSTEPS = 5;  // FIXME
176         ret.x[0] = a.multiply_px(x[0], y[0]);
177         ret.y[0] = a.multiply_py(x[0], y[0]);
178
179         for(int i=0; i<numvertices; i++) {
180             if (type[i] == TYPE_LINETO) {
181                 float rx = x[i+1];
182                 float ry = y[i+1];
183                 ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
184
185             } else if (type[i] == TYPE_MOVETO) {
186                 float rx = x[i+1];
187                 float ry = y[i+1];
188                 ret.newcontour();
189                 ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
190
191             } else if (type[i] == TYPE_ARCTO) {
192                 float rx = c1x[i];
193                 float ry = c1y[i];
194                 float phi = c2x[i];
195                 float fa = ((int)c2y[i]) >> 1;
196                 float fs = ((int)c2y[i]) & 1;
197                 float x1 = x[i];
198                 float y1 = y[i];
199                 float x2 = x[i+1];
200                 float y2 = y[i+1];
201
202                 // F.6.5: given x1,y1,x2,y2,fa,fs, compute cx,cy,theta1,dtheta
203                 float x1_ = (float)Math.cos(phi) * (x1 - x2) / 2 + (float)Math.sin(phi) * (y1 - y2) / 2;
204                 float y1_ = -1 * (float)Math.sin(phi) * (x1 - x2) / 2 + (float)Math.cos(phi) * (y1 - y2) / 2;
205                 float tmp = (float)Math.sqrt((rx * rx * ry * ry - rx * rx * y1_ * y1_ - ry * ry * x1_ * x1_) /
206                                              (rx * rx * y1_ * y1_ + ry * ry * x1_ * x1_));
207                 float cx_ = (fa == fs ? -1 : 1) * tmp * (rx * y1_ / ry);
208                 float cy_ = (fa == fs ? -1 : 1) * -1 * tmp * (ry * x1_ / rx);
209                 float cx = (float)Math.cos(phi) * cx_ - (float)Math.sin(phi) * cy_ + (x1 + x2) / 2;
210                 float cy = (float)Math.sin(phi) * cx_ + (float)Math.cos(phi) * cy_ + (y1 + y2) / 2;
211
212                 // F.6.4 Conversion from center to endpoint parameterization
213                 float ux = 1, uy = 0, vx = (x1_ - cx_) / rx, vy = (y1_ - cy_) / ry;
214                 float det = ux * vy - uy * vx;
215                 float theta1 = (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                 ux = (x1_ - cx_) / rx; uy = (y1_ - cy_) / ry;
219                 vx = (-1 * x1_ - cx_) / rx; vy = (-1 * y1_ - cy_) / ry;
220                 det = ux * vy - uy * vx;
221                 float dtheta = (det < 0 ? -1 : 1) *
222                     (float)Math.acos((ux * vx + uy * vy) / 
223                                      ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
224                 dtheta = dtheta % (float)(2 * Math.PI);
225
226                 if (fs == 0 && dtheta > 0) theta1 -= 2 * PI; 
227                 if (fs == 1 && dtheta < 0) theta1 += 2 * PI;
228
229                 if (fa == 1 && dtheta < 0) dtheta = 2 * PI + dtheta;
230                 else if (fa == 1 && dtheta > 0) dtheta = -1 * (2 * PI - dtheta);
231
232                 // FIXME: integrate F.6.6
233                 // FIXME: isn't quite ending where it should...
234
235                 // F.6.3: Parameterization alternatives
236                 float theta = theta1;
237                 for(int j=0; j<NUMSTEPS; j++) {
238                     float rasterx = rx * (float)Math.cos(theta) * (float)Math.cos(phi) -
239                         ry * (float)Math.sin(theta) * (float)Math.sin(phi) + cx;
240                     float rastery = rx * (float)Math.cos(theta) * (float)Math.sin(phi) +
241                         ry * (float)Math.cos(phi) * (float)Math.sin(theta) + cy;
242                     ret.add(a.multiply_px(rasterx, rastery), a.multiply_py(rasterx, rastery));
243                     theta += dtheta / NUMSTEPS;
244                 }
245
246             } else if (type[i] == TYPE_CUBIC) {
247
248                 float ax = x[i+1] - 3 * c2x[i] + 3 * c1x[i] - x[i];
249                 float bx = 3 * c2x[i] - 6 * c1x[i] + 3 * x[i];
250                 float cx = 3 * c1x[i] - 3 * x[i];
251                 float dx = x[i];
252                 float ay = y[i+1] - 3 * c2y[i] + 3 * c1y[i] - y[i];
253                 float by = 3 * c2y[i] - 6 * c1y[i] + 3 * y[i];
254                 float cy = 3 * c1y[i] - 3 * y[i];
255                 float dy = y[i];
256                     
257                 float x0 = a.multiply_px(x[i], y[i]);
258                 float y0 = a.multiply_py(x[i], y[i]);
259                 float x1 = a.multiply_px(x[i+1], y[i+1]);
260                 float y1 = a.multiply_py(x[i+1], y[i+1]);
261                 float steps = (float)Math.sqrt( (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0) );
262
263                 for(float t=0; t<1; t += 1 / (steps/20)) {
264                     float rx = ax * t * t * t + bx * t * t + cx * t + dx;
265                     float ry = ay * t * t * t + by * t * t + cy * t + dy;
266                     ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
267                 }
268
269
270             } else if (type[i] == TYPE_QUADRADIC) {
271
272                 float bx = x[i+1] - 2 * c1x[i] + x[i];
273                 float cx = 2 * c1x[i] - 2 * x[i];
274                 float dx = x[i];
275                 float by = y[i+1] - 2 * c1y[i] + y[i];
276                 float cy = 2 * c1y[i] - 2 * y[i];
277                 float dy = y[i];
278                         
279                 float x0 = a.multiply_px(x[i], y[i]);
280                 float y0 = a.multiply_py(x[i], y[i]);
281                 float x1 = a.multiply_px(x[i+1], y[i+1]);
282                 float y1 = a.multiply_py(x[i+1], y[i+1]);
283                 float steps = (float)Math.sqrt( (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0) );
284
285                 for(float t=0; t<1; t += 1 / (steps/20)) {
286                     float rx = bx * t * t + cx * t + dx;
287                     float ry = by * t * t + cy * t + dy;
288                     ret.add(a.multiply_px(rx, ry), a.multiply_py(rx, ry));
289                 }
290
291             }
292         }
293         } finally { Scheduler.rasterizing += System.currentTimeMillis() - start; }
294     }
295
296     protected void parseSingleCommandAndArguments(Tokenizer t, char command, boolean relative) {
297         if (numvertices == 0 && command != 'm')
298             throw new RuntimeException("first command MUST be an 'm', not a " + command);
299         if (numvertices > x.length - 2) {
300             float[] new_x = new float[x.length * 2]; System.arraycopy(x, 0, new_x, 0, x.length); x = new_x;
301             float[] new_y = new float[y.length * 2]; System.arraycopy(y, 0, new_y, 0, y.length); y = new_y;
302         }
303         switch(command) {
304             case 'z': {
305                 int where;
306                 type[numvertices-1] = TYPE_LINETO;
307                 for(where = numvertices-2; where >= 0 && type[where] != TYPE_MOVETO; where--);
308                 x[numvertices] = x[where+1];
309                 y[numvertices] = y[where+1];
310                 numvertices++;
311                 closed = true;
312                 // FIXME: actually, we should search back to the last 'z' or 'm', not just 'm'
313                 break;
314             }
315
316             case 'm': {
317                 if (numvertices > 0) type[numvertices-1] = TYPE_MOVETO;
318                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
319                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
320                 if (numvertices > 2 && type[numvertices-2] == TYPE_MOVETO) {
321                     x[numvertices-1] = x[numvertices];
322                     y[numvertices-1] = y[numvertices];
323                 } else {
324                     numvertices++;
325                 }
326                 break;
327             }
328
329             case 'l': case 'h': case 'v': {
330                 type[numvertices-1] = TYPE_LINETO;
331                 float first = t.parseFloat(), second;
332                 if (command == 'h') {
333                     second = relative ? 0 : y[numvertices - 1];
334                 } else if (command == 'v') {
335                     second = first; first = relative ? 0 : x[numvertices - 1];
336                 } else {
337                     second = t.parseFloat();
338                 }
339                 x[numvertices] = first + (relative ? x[numvertices - 1] : 0);
340                 y[numvertices] = second + (relative ? y[numvertices - 1] : 0);
341                 numvertices++;
342                 break;
343             }
344             
345             case 'a': {
346                 type[numvertices-1] = TYPE_ARCTO;
347                 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
348                 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
349                 c2x[numvertices-1] = (t.parseFloat() / 360) * 2 * PI;
350                 c2y[numvertices-1] = (((int)t.parseFloat()) << 1) | (int)t.parseFloat();
351                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
352                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
353                 numvertices++;
354                 break;
355             }
356
357             case 's': case 'c': {
358                 type[numvertices-1] = TYPE_CUBIC;
359                 if (command == 'c') {
360                     c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
361                     c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
362                 } else if (numvertices > 1 && type[numvertices-2] == TYPE_CUBIC) {
363                     c1x[numvertices-1] = 2 * x[numvertices - 1] - c2x[numvertices-2];
364                     c1y[numvertices-1] = 2 * y[numvertices - 1] - c2y[numvertices-2];
365                 } else {
366                     c1x[numvertices-1] = x[numvertices-1];
367                     c1y[numvertices-1] = y[numvertices-1];
368                 }
369                 c2x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
370                 c2y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
371                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
372                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
373                 numvertices++;
374                 break;
375             }
376
377             case 't': case 'q': {
378                 type[numvertices-1] = TYPE_QUADRADIC;
379                 if (command == 'q') {
380                     c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
381                     c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
382                 } else if (numvertices > 1 && type[numvertices-2] == TYPE_QUADRADIC) {
383                     c1x[numvertices-1] = 2 * x[numvertices - 1] - c1x[numvertices-2];
384                     c1y[numvertices-1] = 2 * y[numvertices - 1] - c1y[numvertices-2];
385                 } else {
386                     c1x[numvertices-1] = x[numvertices-1];
387                     c1y[numvertices-1] = y[numvertices-1];
388                 }
389                 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
390                 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
391                 numvertices++;
392                 break;
393             }
394
395             default:
396                 // FIXME
397         }
398
399         /*
400         // invariant: after this loop, no two lines intersect other than at a vertex
401         // FIXME: cleanup
402         int index = numvertices - 2;
403         for(int i=0; i<Math.min(numvertices - 3, index); i++) {
404         for(int j = index; j < numvertices - 1; j++) {
405
406         // I'm not sure how to deal with vertical lines...
407         if (x[i+1] == x[i] || x[j+1] == x[j]) continue;
408                         
409         float islope = (y[i+1] - y[i]) / (x[i+1] - x[i]);
410         float jslope = (y[j+1] - y[j]) / (x[j+1] - x[j]);
411         if (islope == jslope) continue;   // parallel lines can't intersect
412                         
413         float _x = (islope * x[i] - jslope * x[j] + y[j] - y[i]) / (islope - jslope);
414         float _y = islope * (_x - x[i]) + y[i];
415                         
416         if (_x > Math.min(x[i+1], x[i]) && _x < Math.max(x[i+1], x[i]) &&
417         _x > Math.min(x[j+1], x[j]) && _x < Math.max(x[j+1], x[j])) {
418         // FIXME: something's not right in here.  See if we can do without fracturing line 'i'.
419         for(int k = ++numvertices; k>i; k--) { x[k] = x[k - 1]; y[k] = y[k - 1]; }
420         x[i+1] = _x;
421         y[i+1] = _y;
422         x[numvertices] = x[numvertices - 1];  x[numvertices - 1] = _x;
423         y[numvertices] = y[numvertices - 1];  y[numvertices - 1] = _y;
424         edges[numedges++] = numvertices - 1; numvertices++;
425         index++;
426         break;  // actually 'continue' the outermost loop
427         }
428         }
429         }
430         */
431
432     }
433
434 }