2 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
3 package org.ibex.graphics;
6 /** an abstract path; may contain splines and arcs */
9 public static final float PX_PER_INCH = 72;
10 public static final float INCHES_PER_CM = (float)0.3937;
11 public static final float INCHES_PER_MM = INCHES_PER_CM / 10;
12 private static final int DEFAULT_PATHLEN = 1000;
13 private static final float PI = (float)Math.PI;
15 // the number of vertices on this path
18 // the vertices of the path
19 float[] x = new float[DEFAULT_PATHLEN];
20 float[] y = new float[DEFAULT_PATHLEN];
22 // 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]
23 byte[] type = new byte[DEFAULT_PATHLEN];
25 // bezier control points
26 float[] c1x = new float[DEFAULT_PATHLEN]; // or rx (arcto)
27 float[] c1y = new float[DEFAULT_PATHLEN]; // or ry (arcto)
28 float[] c2x = new float[DEFAULT_PATHLEN]; // or x-axis-rotation (arcto)
29 float[] c2y = new float[DEFAULT_PATHLEN]; // or large-arc << 1 | sweep (arcto)
31 boolean closed = false;
33 static final byte TYPE_MOVETO = 0;
34 static final byte TYPE_LINETO = 1;
35 static final byte TYPE_ARCTO = 2;
36 static final byte TYPE_CUBIC = 3;
37 static final byte TYPE_QUADRADIC = 4;
39 public static class Tokenizer {
40 // FIXME: check array bounds exception for improperly terminated string
43 char lastCommand = 'M';
44 public Tokenizer(String s) { this.s = s; }
46 public static Path parse(String s) {
47 if (s == null) return null;
48 Tokenizer t = new Tokenizer(s);
49 Path ret = new Path();
50 char last_command = 'M';
52 while(t.hasMoreTokens()) {
53 char command = t.parseCommand();
54 if (first && command != 'M') throw new RuntimeException("the first command of a path must be 'M'");
56 boolean relative = Character.toLowerCase(command) == command;
57 command = Character.toLowerCase(command);
58 ret.parseSingleCommandAndArguments(t, command, relative);
59 last_command = command;
64 private void consumeWhitespace() {
65 while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
66 if (i < s.length() && s.charAt(i) == ',') i++;
67 while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
69 public boolean hasMoreTokens() { consumeWhitespace(); return i < s.length(); }
70 public char parseCommand() {
73 if (!Character.isLetter(c)) return lastCommand;
75 return lastCommand = c;
77 public float parseFloat() {
81 for(; i < s.length(); i++) {
83 if (Character.isWhitespace(c) || c == ',' || (c == '-' && i != start)) break;
84 if (!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '-')) {
85 if (c == '%') { // FIXME
86 } else if (s.regionMatches(i, "pt", 0, i+2)) { // FIXME
87 } else if (s.regionMatches(i, "em", 0, i+2)) { // FIXME
88 } else if (s.regionMatches(i, "pc", 0, i+2)) { // FIXME
89 } else if (s.regionMatches(i, "ex", 0, i+2)) { // FIXME
90 } else if (s.regionMatches(i, "mm", 0, i+2)) { i += 2; multiplier = INCHES_PER_MM * PX_PER_INCH; break;
91 } else if (s.regionMatches(i, "cm", 0, i+2)) { i += 2; multiplier = INCHES_PER_CM * PX_PER_INCH; break;
92 } else if (s.regionMatches(i, "in", 0, i+2)) { i += 2; multiplier = PX_PER_INCH; break;
93 } else if (s.regionMatches(i, "px", 0, i+2)) { i += 2; break;
94 } else if (Character.isLetter(c)) break;
95 throw new RuntimeException("didn't expect character \"" + c + "\" in a numeric constant");
98 if (start == i) throw new RuntimeException("FIXME");
99 return Float.parseFloat(s.substring(start, i)) * multiplier;
103 /** Creates a concrete vector path transformed through the given matrix. */
104 public Raster realize(Affine a) {
106 Raster ret = new Raster();
107 int NUMSTEPS = 5; // FIXME
109 ret.x[0] = (int)Math.round(a.multiply_px(x[0], y[0]));
110 ret.y[0] = (int)Math.round(a.multiply_py(x[0], y[0]));
112 for(int i=1; i<numvertices; i++) {
113 if (type[i] == TYPE_LINETO) {
116 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
117 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
118 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
120 } else if (type[i] == TYPE_MOVETO) {
123 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
124 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
127 } else if (type[i] == TYPE_ARCTO) {
131 float fa = ((int)c2y[i]) >> 1;
132 float fs = ((int)c2y[i]) & 1;
138 // F.6.5: given x1,y1,x2,y2,fa,fs, compute cx,cy,theta1,dtheta
139 float x1_ = (float)Math.cos(phi) * (x1 - x2) / 2 + (float)Math.sin(phi) * (y1 - y2) / 2;
140 float y1_ = -1 * (float)Math.sin(phi) * (x1 - x2) / 2 + (float)Math.cos(phi) * (y1 - y2) / 2;
141 float tmp = (float)Math.sqrt((rx * rx * ry * ry - rx * rx * y1_ * y1_ - ry * ry * x1_ * x1_) /
142 (rx * rx * y1_ * y1_ + ry * ry * x1_ * x1_));
143 float cx_ = (fa == fs ? -1 : 1) * tmp * (rx * y1_ / ry);
144 float cy_ = (fa == fs ? -1 : 1) * -1 * tmp * (ry * x1_ / rx);
145 float cx = (float)Math.cos(phi) * cx_ - (float)Math.sin(phi) * cy_ + (x1 + x2) / 2;
146 float cy = (float)Math.sin(phi) * cx_ + (float)Math.cos(phi) * cy_ + (y1 + y2) / 2;
148 // F.6.4 Conversion from center to endpoint parameterization
149 float ux = 1, uy = 0, vx = (x1_ - cx_) / rx, vy = (y1_ - cy_) / ry;
150 float det = ux * vy - uy * vx;
151 float theta1 = (det < 0 ? -1 : 1) *
152 (float)Math.acos((ux * vx + uy * vy) /
153 ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
154 ux = (x1_ - cx_) / rx; uy = (y1_ - cy_) / ry;
155 vx = (-1 * x1_ - cx_) / rx; vy = (-1 * y1_ - cy_) / ry;
156 det = ux * vy - uy * vx;
157 float dtheta = (det < 0 ? -1 : 1) *
158 (float)Math.acos((ux * vx + uy * vy) /
159 ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
160 dtheta = dtheta % (float)(2 * Math.PI);
162 if (fs == 0 && dtheta > 0) theta1 -= 2 * PI;
163 if (fs == 1 && dtheta < 0) theta1 += 2 * PI;
165 if (fa == 1 && dtheta < 0) dtheta = 2 * PI + dtheta;
166 else if (fa == 1 && dtheta > 0) dtheta = -1 * (2 * PI - dtheta);
168 // FIXME: integrate F.6.6
169 // FIXME: isn't quite ending where it should...
171 // F.6.3: Parameterization alternatives
172 float theta = theta1;
173 for(int j=0; j<NUMSTEPS; j++) {
174 float rasterx = rx * (float)Math.cos(theta) * (float)Math.cos(phi) -
175 ry * (float)Math.sin(theta) * (float)Math.sin(phi) + cx;
176 float rastery = rx * (float)Math.cos(theta) * (float)Math.sin(phi) +
177 ry * (float)Math.cos(phi) * (float)Math.sin(theta) + cy;
178 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rasterx, rastery));
179 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rasterx, rastery));
180 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
181 theta += dtheta / NUMSTEPS;
184 } else if (type[i] == TYPE_CUBIC) {
186 float ax = x[i+1] - 3 * c2x[i] + 3 * c1x[i] - x[i];
187 float bx = 3 * c2x[i] - 6 * c1x[i] + 3 * x[i];
188 float cx = 3 * c1x[i] - 3 * x[i];
190 float ay = y[i+1] - 3 * c2y[i] + 3 * c1y[i] - y[i];
191 float by = 3 * c2y[i] - 6 * c1y[i] + 3 * y[i];
192 float cy = 3 * c1y[i] - 3 * y[i];
195 for(float t=0; t<1; t += 1 / (float)NUMSTEPS) {
196 float rx = ax * t * t * t + bx * t * t + cx * t + dx;
197 float ry = ay * t * t * t + by * t * t + cy * t + dy;
198 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
199 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
200 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
204 } else if (type[i] == TYPE_QUADRADIC) {
206 float bx = x[i+1] - 2 * c1x[i] + x[i];
207 float cx = 2 * c1x[i] - 2 * x[i];
209 float by = y[i+1] - 2 * c1y[i] + y[i];
210 float cy = 2 * c1y[i] - 2 * y[i];
213 for(float t=0; t<1; t += 1 / (float)NUMSTEPS) {
214 float rx = bx * t * t + cx * t + dx;
215 float ry = by * t * t + cy * t + dy;
216 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
217 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
218 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
225 if (ret.numedges > 0) ret.sort(0, ret.numedges - 1, false);
229 protected void parseSingleCommandAndArguments(Tokenizer t, char command, boolean relative) {
230 if (numvertices == 0 && command != 'm') throw new RuntimeException("first command MUST be an 'm'");
231 if (numvertices > x.length - 2) {
232 float[] new_x = new float[x.length * 2]; System.arraycopy(x, 0, new_x, 0, x.length); x = new_x;
233 float[] new_y = new float[y.length * 2]; System.arraycopy(y, 0, new_y, 0, y.length); y = new_y;
238 type[numvertices-1] = TYPE_LINETO;
239 for(where = numvertices - 1; where > 0; where--)
240 if (type[where - 1] == TYPE_MOVETO) break;
241 x[numvertices] = x[where];
242 y[numvertices] = y[where];
249 if (numvertices > 0) type[numvertices-1] = TYPE_MOVETO;
250 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
251 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
256 case 'l': case 'h': case 'v': {
257 type[numvertices-1] = TYPE_LINETO;
258 float first = t.parseFloat(), second;
259 if (command == 'h') {
260 second = relative ? 0 : y[numvertices - 1];
261 } else if (command == 'v') {
262 second = first; first = relative ? 0 : x[numvertices - 1];
264 second = t.parseFloat();
266 x[numvertices] = first + (relative ? x[numvertices - 1] : 0);
267 y[numvertices] = second + (relative ? y[numvertices - 1] : 0);
273 type[numvertices-1] = TYPE_ARCTO;
274 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
275 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
276 c2x[numvertices-1] = (t.parseFloat() / 360) * 2 * PI;
277 c2y[numvertices-1] = (((int)t.parseFloat()) << 1) | (int)t.parseFloat();
278 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
279 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
284 case 's': case 'c': {
285 type[numvertices-1] = TYPE_CUBIC;
286 if (command == 'c') {
287 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
288 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
289 } else if (numvertices > 1 && type[numvertices-2] == TYPE_CUBIC) {
290 c1x[numvertices-1] = 2 * x[numvertices - 1] - c2x[numvertices-2];
291 c1y[numvertices-1] = 2 * y[numvertices - 1] - c2y[numvertices-2];
293 c1x[numvertices-1] = x[numvertices-1];
294 c1y[numvertices-1] = y[numvertices-1];
296 c2x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
297 c2y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
298 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
299 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
304 case 't': case 'q': {
305 type[numvertices-1] = TYPE_QUADRADIC;
306 if (command == 'q') {
307 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
308 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
309 } else if (numvertices > 1 && type[numvertices-2] == TYPE_QUADRADIC) {
310 c1x[numvertices-1] = 2 * x[numvertices - 1] - c1x[numvertices-2];
311 c1y[numvertices-1] = 2 * y[numvertices - 1] - c1y[numvertices-2];
313 c1x[numvertices-1] = x[numvertices-1];
314 c1y[numvertices-1] = y[numvertices-1];
316 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
317 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
327 // invariant: after this loop, no two lines intersect other than at a vertex
329 int index = numvertices - 2;
330 for(int i=0; i<Math.min(numvertices - 3, index); i++) {
331 for(int j = index; j < numvertices - 1; j++) {
333 // I'm not sure how to deal with vertical lines...
334 if (x[i+1] == x[i] || x[j+1] == x[j]) continue;
336 float islope = (y[i+1] - y[i]) / (x[i+1] - x[i]);
337 float jslope = (y[j+1] - y[j]) / (x[j+1] - x[j]);
338 if (islope == jslope) continue; // parallel lines can't intersect
340 float _x = (islope * x[i] - jslope * x[j] + y[j] - y[i]) / (islope - jslope);
341 float _y = islope * (_x - x[i]) + y[i];
343 if (_x > Math.min(x[i+1], x[i]) && _x < Math.max(x[i+1], x[i]) &&
344 _x > Math.min(x[j+1], x[j]) && _x < Math.max(x[j+1], x[j])) {
345 // FIXME: something's not right in here. See if we can do without fracturing line 'i'.
346 for(int k = ++numvertices; k>i; k--) { x[k] = x[k - 1]; y[k] = y[k - 1]; }
349 x[numvertices] = x[numvertices - 1]; x[numvertices - 1] = _x;
350 y[numvertices] = y[numvertices - 1]; y[numvertices - 1] = _y;
351 edges[numedges++] = numvertices - 1; numvertices++;
353 break; // actually 'continue' the outermost loop
362 // Rasterized Vector Path //////////////////////////////////////////////////////////////////////////////
365 public static class Raster {
367 // the vertices of this path
368 int[] x = new int[DEFAULT_PATHLEN];
369 int[] y = new int[DEFAULT_PATHLEN];
373 * A list of the vertices on this path which *start* an *edge* (rather than a moveto), sorted by increasing y.
374 * example: x[edges[1]],y[edges[1]] - x[edges[i]+1],y[edges[i]+1] is the second-topmost edge
375 * note that if x[i],y[i] - x[i+1],y[i+1] is a MOVETO, then no element in edges will be equal to i
377 int[] edges = new int[DEFAULT_PATHLEN];
380 /** translate a rasterized path */
381 public void translate(int dx, int dy) { for(int i=0; i<numvertices; i++) { x[i] += dx; y[i] += dy; } }
383 /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
384 int sort(int left, int right, boolean partition) {
387 middle = (left + right) / 2;
388 int s = edges[right]; edges[right] = edges[middle]; edges[middle] = s;
389 for (i = left - 1, j = right; ; ) {
390 while (y[edges[++i]] < y[edges[right]]);
391 while (j > left && y[edges[--j]] > y[edges[right]]);
393 s = edges[i]; edges[i] = edges[j]; edges[j] = s;
395 s = edges[right]; edges[right] = edges[i]; edges[i] = s;
398 if (left >= right) return 0;
399 int p = sort(left, right, true);
400 sort(left, p - 1, false);
401 sort(p + 1, right, false);
406 /** finds the x value at which the line intercepts the line y=_y */
407 private int intercept(int i, float _y, boolean includeTop, boolean includeBottom) {
408 if (includeTop ? (_y < Math.min(y[i], y[i+1])) : (_y <= Math.min(y[i], y[i+1])))
409 return Integer.MIN_VALUE;
410 if (includeBottom ? (_y > Math.max(y[i], y[i+1])) : (_y >= Math.max(y[i], y[i+1])))
411 return Integer.MIN_VALUE;
412 return (int)Math.round((((float)(x[i + 1] - x[i])) /
413 ((float)(y[i + 1] - y[i])) ) * ((float)(_y - y[i])) + x[i]);
416 /** fill the interior of the path */
417 public void fill(PixelBuffer buf, Paint paint) {
418 if (numedges == 0) return;
419 int y0 = y[edges[0]], y1 = y0;
420 boolean useEvenOdd = false;
422 // we iterate over all endpoints in increasing y-coordinate order
423 for(int index = 1; index<numedges; index++) {
426 // we now examine the horizontal band between y=y0 and y=y1
428 y1 = y[edges[index]];
429 if (y0 == y1) continue;
431 // within this band, we iterate over all edges
432 int x0 = Integer.MIN_VALUE;
433 int leftSegment = -1;
435 int x1 = Integer.MAX_VALUE;
436 int rightSegment = Integer.MAX_VALUE;
437 for(int i=0; i<numedges; i++) {
438 if (y[edges[i]] == y[edges[i]+1]) continue; // ignore horizontal lines; they are irrelevant.
439 // we order the segments by the x-coordinate of their midpoint;
440 // since segments cannot intersect, this is a well-ordering
441 int i0 = intercept(edges[i], y0, true, false);
442 int i1 = intercept(edges[i], y1, false, true);
443 if (i0 == Integer.MIN_VALUE || i1 == Integer.MIN_VALUE) continue;
444 int midpoint = i0 + i1;
445 if (midpoint < x0) continue;
446 if (midpoint == x0 && i <= leftSegment) continue;
447 if (midpoint > x1) continue;
448 if (midpoint == x1 && i >= rightSegment) continue;
452 if (leftSegment == rightSegment || rightSegment == Integer.MAX_VALUE) break;
453 if (leftSegment != -1)
454 if ((useEvenOdd && count % 2 != 0) || (!useEvenOdd && count != 0))
455 paint.fillTrapezoid(intercept(edges[leftSegment], y0, true, true),
456 intercept(edges[rightSegment], y0, true, true), y0,
457 intercept(edges[leftSegment], y1, true, true),
458 intercept(edges[rightSegment], y1, true, true), y1,
460 if (useEvenOdd) count++;
461 else count += (y[edges[rightSegment]] < y[edges[rightSegment]+1]) ? -1 : 1;
462 leftSegment = rightSegment; x0 = x1;
467 /** stroke the outline of the path */
468 public void stroke(PixelBuffer buf, int width, int color) { stroke(buf, width, color, null, 0, 0); }
469 public void stroke(PixelBuffer buf, int width, int color, String dashArray, int dashOffset, float segLength) {
471 if (dashArray == null) {
472 for(int i=0; i<numedges; i++)
473 buf.drawLine((int)x[edges[i]],
474 (int)y[edges[i]], (int)x[edges[i]+1], (int)y[edges[i]+1], width, color, false);
480 float actualLength = 0;
481 for(int i=0; i<numvertices; i++) {
482 // skip over MOVETOs -- they do not contribute to path length
483 if (x[i] == x[i+1] && y[i] == y[i+1]) continue;
484 if (x[i+1] == x[i+2] && y[i+1] == y[i+2]) continue;
489 actualLength += java.lang.Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
491 ratio = actualLength / segLength;
493 Tokenizer pt = new Tokenizer(dashArray);
494 Vector v = new Vector();
495 while (pt.hasMoreTokens()) v.addElement(new Float(pt.parseFloat()));
496 float[] dashes = new float[v.size() % 2 == 0 ? v.size() : 2 * v.size()];
497 for(int i=0; i<dashes.length; i++) dashes[i] = ((Float)v.elementAt(i % v.size())).floatValue();
498 int dashpos = dashOffset;
499 boolean on = dashpos % 2 == 0;
500 for(int i=0; i<numvertices; i++) {
501 // skip over MOVETOs -- they do not contribute to path length
502 if (x[i] == x[i+1] && y[i] == y[i+1]) continue;
503 if (x[i+1] == x[i+2] && y[i+1] == y[i+2]) continue;
505 int x2 = (int)x[i + 1];
507 int y2 = (int)y[i + 1];
508 float segmentLength = (float)java.lang.Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
509 int _x1 = x1, _y1 = y1;
512 pos = Math.min(segmentLength, pos + dashes[dashpos] * ratio);
513 if (pos != segmentLength) dashpos = (dashpos + 1) % dashes.length;
514 int _x2 = (int)((x2 * pos + x1 * (segmentLength - pos)) / segmentLength);
515 int _y2 = (int)((y2 * pos + y1 * (segmentLength - pos)) / segmentLength);
516 if (on) buf.drawLine(_x1, _y1, _x2, _y2, width, color, false);
518 _x1 = _x2; _y1 = _y2;
519 } while(pos < segmentLength);
523 // FEATURE: make this faster and cache it; also deal with negative coordinates
524 public int boundingBoxWidth() {
526 for(int i=0; i<numvertices; i++) ret = Math.max(ret, x[i]);
530 // FEATURE: make this faster and cache it; also deal with negative coordinates
531 public int boundingBoxHeight() {
533 for(int i=0; i<numvertices; i++) ret = Math.max(ret, y[i]);