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 Path parse(String s) { return Tokenizer.parse(s); }
40 public static class Tokenizer {
41 // FIXME: check array bounds exception for improperly terminated string
44 char lastCommand = 'M';
45 public Tokenizer(String s) { this.s = s; }
47 public static Path parse(String s) {
48 if (s == null) return null;
49 Tokenizer t = new Tokenizer(s);
50 Path ret = new Path();
51 char last_command = 'M';
53 while(t.hasMoreTokens()) {
54 char command = t.parseCommand();
55 if (first && command != 'M') throw new RuntimeException("the first command of a path must be 'M'");
57 boolean relative = Character.toLowerCase(command) == command;
58 command = Character.toLowerCase(command);
59 ret.parseSingleCommandAndArguments(t, command, relative);
60 last_command = command;
65 private void consumeWhitespace() {
66 while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
67 if (i < s.length() && s.charAt(i) == ',') i++;
68 while(i < s.length() && (Character.isWhitespace(s.charAt(i)))) i++;
70 public boolean hasMoreTokens() { consumeWhitespace(); return i < s.length(); }
71 public char parseCommand() {
74 if (!Character.isLetter(c)) return lastCommand;
76 return lastCommand = c;
78 public float parseFloat() {
82 for(; i < s.length(); i++) {
84 if (Character.isWhitespace(c) || c == ',' || (c == '-' && i != start)) break;
85 if (!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '-')) {
86 if (c == '%') { // FIXME
87 } else if (s.regionMatches(i, "pt", 0, i+2)) { // FIXME
88 } else if (s.regionMatches(i, "em", 0, i+2)) { // FIXME
89 } else if (s.regionMatches(i, "pc", 0, i+2)) { // FIXME
90 } else if (s.regionMatches(i, "ex", 0, i+2)) { // FIXME
91 } else if (s.regionMatches(i, "mm", 0, i+2)) { i += 2; multiplier = INCHES_PER_MM * PX_PER_INCH; break;
92 } else if (s.regionMatches(i, "cm", 0, i+2)) { i += 2; multiplier = INCHES_PER_CM * PX_PER_INCH; break;
93 } else if (s.regionMatches(i, "in", 0, i+2)) { i += 2; multiplier = PX_PER_INCH; break;
94 } else if (s.regionMatches(i, "px", 0, i+2)) { i += 2; break;
95 } else if (Character.isLetter(c)) break;
96 throw new RuntimeException("didn't expect character \"" + c + "\" in a numeric constant");
99 if (start == i) throw new RuntimeException("FIXME");
100 return Float.parseFloat(s.substring(start, i)) * multiplier;
104 /** Creates a concrete vector path transformed through the given matrix. */
105 public Raster realize(Affine a) {
107 Raster ret = new Raster();
108 int NUMSTEPS = 5; // FIXME
110 ret.x[0] = (int)Math.round(a.multiply_px(x[0], y[0]));
111 ret.y[0] = (int)Math.round(a.multiply_py(x[0], y[0]));
113 for(int i=1; i<numvertices; i++) {
114 if (type[i] == TYPE_LINETO) {
117 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
118 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
119 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
121 } else if (type[i] == TYPE_MOVETO) {
124 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
125 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
128 } else if (type[i] == TYPE_ARCTO) {
132 float fa = ((int)c2y[i]) >> 1;
133 float fs = ((int)c2y[i]) & 1;
139 // F.6.5: given x1,y1,x2,y2,fa,fs, compute cx,cy,theta1,dtheta
140 float x1_ = (float)Math.cos(phi) * (x1 - x2) / 2 + (float)Math.sin(phi) * (y1 - y2) / 2;
141 float y1_ = -1 * (float)Math.sin(phi) * (x1 - x2) / 2 + (float)Math.cos(phi) * (y1 - y2) / 2;
142 float tmp = (float)Math.sqrt((rx * rx * ry * ry - rx * rx * y1_ * y1_ - ry * ry * x1_ * x1_) /
143 (rx * rx * y1_ * y1_ + ry * ry * x1_ * x1_));
144 float cx_ = (fa == fs ? -1 : 1) * tmp * (rx * y1_ / ry);
145 float cy_ = (fa == fs ? -1 : 1) * -1 * tmp * (ry * x1_ / rx);
146 float cx = (float)Math.cos(phi) * cx_ - (float)Math.sin(phi) * cy_ + (x1 + x2) / 2;
147 float cy = (float)Math.sin(phi) * cx_ + (float)Math.cos(phi) * cy_ + (y1 + y2) / 2;
149 // F.6.4 Conversion from center to endpoint parameterization
150 float ux = 1, uy = 0, vx = (x1_ - cx_) / rx, vy = (y1_ - cy_) / ry;
151 float det = ux * vy - uy * vx;
152 float theta1 = (det < 0 ? -1 : 1) *
153 (float)Math.acos((ux * vx + uy * vy) /
154 ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
155 ux = (x1_ - cx_) / rx; uy = (y1_ - cy_) / ry;
156 vx = (-1 * x1_ - cx_) / rx; vy = (-1 * y1_ - cy_) / ry;
157 det = ux * vy - uy * vx;
158 float dtheta = (det < 0 ? -1 : 1) *
159 (float)Math.acos((ux * vx + uy * vy) /
160 ((float)Math.sqrt(ux * ux + uy * uy) * (float)Math.sqrt(vx * vx + vy * vy)));
161 dtheta = dtheta % (float)(2 * Math.PI);
163 if (fs == 0 && dtheta > 0) theta1 -= 2 * PI;
164 if (fs == 1 && dtheta < 0) theta1 += 2 * PI;
166 if (fa == 1 && dtheta < 0) dtheta = 2 * PI + dtheta;
167 else if (fa == 1 && dtheta > 0) dtheta = -1 * (2 * PI - dtheta);
169 // FIXME: integrate F.6.6
170 // FIXME: isn't quite ending where it should...
172 // F.6.3: Parameterization alternatives
173 float theta = theta1;
174 for(int j=0; j<NUMSTEPS; j++) {
175 float rasterx = rx * (float)Math.cos(theta) * (float)Math.cos(phi) -
176 ry * (float)Math.sin(theta) * (float)Math.sin(phi) + cx;
177 float rastery = rx * (float)Math.cos(theta) * (float)Math.sin(phi) +
178 ry * (float)Math.cos(phi) * (float)Math.sin(theta) + cy;
179 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rasterx, rastery));
180 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rasterx, rastery));
181 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
182 theta += dtheta / NUMSTEPS;
185 } else if (type[i] == TYPE_CUBIC) {
187 float ax = x[i+1] - 3 * c2x[i] + 3 * c1x[i] - x[i];
188 float bx = 3 * c2x[i] - 6 * c1x[i] + 3 * x[i];
189 float cx = 3 * c1x[i] - 3 * x[i];
191 float ay = y[i+1] - 3 * c2y[i] + 3 * c1y[i] - y[i];
192 float by = 3 * c2y[i] - 6 * c1y[i] + 3 * y[i];
193 float cy = 3 * c1y[i] - 3 * y[i];
196 for(float t=0; t<1; t += 1 / (float)NUMSTEPS) {
197 float rx = ax * t * t * t + bx * t * t + cx * t + dx;
198 float ry = ay * t * t * t + by * t * t + cy * t + dy;
199 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
200 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
201 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
205 } else if (type[i] == TYPE_QUADRADIC) {
207 float bx = x[i+1] - 2 * c1x[i] + x[i];
208 float cx = 2 * c1x[i] - 2 * x[i];
210 float by = y[i+1] - 2 * c1y[i] + y[i];
211 float cy = 2 * c1y[i] - 2 * y[i];
214 for(float t=0; t<1; t += 1 / (float)NUMSTEPS) {
215 float rx = bx * t * t + cx * t + dx;
216 float ry = by * t * t + cy * t + dy;
217 ret.x[ret.numvertices] = (int)Math.round(a.multiply_px(rx, ry));
218 ret.y[ret.numvertices] = (int)Math.round(a.multiply_py(rx, ry));
219 ret.edges[ret.numedges++] = ret.numvertices - 1; ret.numvertices++;
226 if (ret.numedges > 0) ret.sort(0, ret.numedges - 1, false);
230 protected void parseSingleCommandAndArguments(Tokenizer t, char command, boolean relative) {
231 if (numvertices == 0 && command != 'm') throw new RuntimeException("first command MUST be an 'm'");
232 if (numvertices > x.length - 2) {
233 float[] new_x = new float[x.length * 2]; System.arraycopy(x, 0, new_x, 0, x.length); x = new_x;
234 float[] new_y = new float[y.length * 2]; System.arraycopy(y, 0, new_y, 0, y.length); y = new_y;
239 type[numvertices-1] = TYPE_LINETO;
240 for(where = numvertices - 1; where > 0; where--)
241 if (type[where - 1] == TYPE_MOVETO) break;
242 x[numvertices] = x[where];
243 y[numvertices] = y[where];
250 if (numvertices > 0) type[numvertices-1] = TYPE_MOVETO;
251 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
252 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
257 case 'l': case 'h': case 'v': {
258 type[numvertices-1] = TYPE_LINETO;
259 float first = t.parseFloat(), second;
260 if (command == 'h') {
261 second = relative ? 0 : y[numvertices - 1];
262 } else if (command == 'v') {
263 second = first; first = relative ? 0 : x[numvertices - 1];
265 second = t.parseFloat();
267 x[numvertices] = first + (relative ? x[numvertices - 1] : 0);
268 y[numvertices] = second + (relative ? y[numvertices - 1] : 0);
274 type[numvertices-1] = TYPE_ARCTO;
275 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
276 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
277 c2x[numvertices-1] = (t.parseFloat() / 360) * 2 * PI;
278 c2y[numvertices-1] = (((int)t.parseFloat()) << 1) | (int)t.parseFloat();
279 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
280 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
285 case 's': case 'c': {
286 type[numvertices-1] = TYPE_CUBIC;
287 if (command == 'c') {
288 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
289 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
290 } else if (numvertices > 1 && type[numvertices-2] == TYPE_CUBIC) {
291 c1x[numvertices-1] = 2 * x[numvertices - 1] - c2x[numvertices-2];
292 c1y[numvertices-1] = 2 * y[numvertices - 1] - c2y[numvertices-2];
294 c1x[numvertices-1] = x[numvertices-1];
295 c1y[numvertices-1] = y[numvertices-1];
297 c2x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
298 c2y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
299 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
300 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
305 case 't': case 'q': {
306 type[numvertices-1] = TYPE_QUADRADIC;
307 if (command == 'q') {
308 c1x[numvertices-1] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
309 c1y[numvertices-1] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
310 } else if (numvertices > 1 && type[numvertices-2] == TYPE_QUADRADIC) {
311 c1x[numvertices-1] = 2 * x[numvertices - 1] - c1x[numvertices-2];
312 c1y[numvertices-1] = 2 * y[numvertices - 1] - c1y[numvertices-2];
314 c1x[numvertices-1] = x[numvertices-1];
315 c1y[numvertices-1] = y[numvertices-1];
317 x[numvertices] = t.parseFloat() + (relative ? x[numvertices - 1] : 0);
318 y[numvertices] = t.parseFloat() + (relative ? y[numvertices - 1] : 0);
328 // invariant: after this loop, no two lines intersect other than at a vertex
330 int index = numvertices - 2;
331 for(int i=0; i<Math.min(numvertices - 3, index); i++) {
332 for(int j = index; j < numvertices - 1; j++) {
334 // I'm not sure how to deal with vertical lines...
335 if (x[i+1] == x[i] || x[j+1] == x[j]) continue;
337 float islope = (y[i+1] - y[i]) / (x[i+1] - x[i]);
338 float jslope = (y[j+1] - y[j]) / (x[j+1] - x[j]);
339 if (islope == jslope) continue; // parallel lines can't intersect
341 float _x = (islope * x[i] - jslope * x[j] + y[j] - y[i]) / (islope - jslope);
342 float _y = islope * (_x - x[i]) + y[i];
344 if (_x > Math.min(x[i+1], x[i]) && _x < Math.max(x[i+1], x[i]) &&
345 _x > Math.min(x[j+1], x[j]) && _x < Math.max(x[j+1], x[j])) {
346 // FIXME: something's not right in here. See if we can do without fracturing line 'i'.
347 for(int k = ++numvertices; k>i; k--) { x[k] = x[k - 1]; y[k] = y[k - 1]; }
350 x[numvertices] = x[numvertices - 1]; x[numvertices - 1] = _x;
351 y[numvertices] = y[numvertices - 1]; y[numvertices - 1] = _y;
352 edges[numedges++] = numvertices - 1; numvertices++;
354 break; // actually 'continue' the outermost loop
363 // Rasterized Vector Path //////////////////////////////////////////////////////////////////////////////
366 public static class Raster {
368 // the vertices of this path
369 int[] x = new int[DEFAULT_PATHLEN];
370 int[] y = new int[DEFAULT_PATHLEN];
374 * A list of the vertices on this path which *start* an *edge* (rather than a moveto), sorted by increasing y.
375 * example: x[edges[1]],y[edges[1]] - x[edges[i]+1],y[edges[i]+1] is the second-topmost edge
376 * 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
378 int[] edges = new int[DEFAULT_PATHLEN];
381 /** translate a rasterized path */
382 public void translate(int dx, int dy) { for(int i=0; i<numvertices; i++) { x[i] += dx; y[i] += dy; } }
384 /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */
385 int sort(int left, int right, boolean partition) {
388 middle = (left + right) / 2;
389 int s = edges[right]; edges[right] = edges[middle]; edges[middle] = s;
390 for (i = left - 1, j = right; ; ) {
391 while (y[edges[++i]] < y[edges[right]]);
392 while (j > left && y[edges[--j]] > y[edges[right]]);
394 s = edges[i]; edges[i] = edges[j]; edges[j] = s;
396 s = edges[right]; edges[right] = edges[i]; edges[i] = s;
399 if (left >= right) return 0;
400 int p = sort(left, right, true);
401 sort(left, p - 1, false);
402 sort(p + 1, right, false);
407 /** finds the x value at which the line intercepts the line y=_y */
408 private int intercept(int i, float _y, boolean includeTop, boolean includeBottom) {
409 if (includeTop ? (_y < Math.min(y[i], y[i+1])) : (_y <= Math.min(y[i], y[i+1])))
410 return Integer.MIN_VALUE;
411 if (includeBottom ? (_y > Math.max(y[i], y[i+1])) : (_y >= Math.max(y[i], y[i+1])))
412 return Integer.MIN_VALUE;
413 return (int)Math.round((((float)(x[i + 1] - x[i])) /
414 ((float)(y[i + 1] - y[i])) ) * ((float)(_y - y[i])) + x[i]);
417 /** fill the interior of the path */
418 public void fill(PixelBuffer buf, Paint paint) {
419 if (numedges == 0) return;
420 int y0 = y[edges[0]], y1 = y0;
421 boolean useEvenOdd = false;
423 // we iterate over all endpoints in increasing y-coordinate order
424 for(int index = 1; index<numedges; index++) {
427 // we now examine the horizontal band between y=y0 and y=y1
429 y1 = y[edges[index]];
430 if (y0 == y1) continue;
432 // within this band, we iterate over all edges
433 int x0 = Integer.MIN_VALUE;
434 int leftSegment = -1;
436 int x1 = Integer.MAX_VALUE;
437 int rightSegment = Integer.MAX_VALUE;
438 for(int i=0; i<numedges; i++) {
439 if (y[edges[i]] == y[edges[i]+1]) continue; // ignore horizontal lines; they are irrelevant.
440 // we order the segments by the x-coordinate of their midpoint;
441 // since segments cannot intersect, this is a well-ordering
442 int i0 = intercept(edges[i], y0, true, false);
443 int i1 = intercept(edges[i], y1, false, true);
444 if (i0 == Integer.MIN_VALUE || i1 == Integer.MIN_VALUE) continue;
445 int midpoint = i0 + i1;
446 if (midpoint < x0) continue;
447 if (midpoint == x0 && i <= leftSegment) continue;
448 if (midpoint > x1) continue;
449 if (midpoint == x1 && i >= rightSegment) continue;
453 if (leftSegment == rightSegment || rightSegment == Integer.MAX_VALUE) break;
454 if (leftSegment != -1)
455 if ((useEvenOdd && count % 2 != 0) || (!useEvenOdd && count != 0))
456 paint.fillTrapezoid(intercept(edges[leftSegment], y0, true, true),
457 intercept(edges[rightSegment], y0, true, true), y0,
458 intercept(edges[leftSegment], y1, true, true),
459 intercept(edges[rightSegment], y1, true, true), y1,
461 if (useEvenOdd) count++;
462 else count += (y[edges[rightSegment]] < y[edges[rightSegment]+1]) ? -1 : 1;
463 leftSegment = rightSegment; x0 = x1;
468 /** stroke the outline of the path */
469 public void stroke(PixelBuffer buf, int width, int color) { stroke(buf, width, color, null, 0, 0); }
470 public void stroke(PixelBuffer buf, int width, int color, String dashArray, int dashOffset, float segLength) {
472 if (dashArray == null) {
473 for(int i=0; i<numedges; i++)
474 buf.drawLine((int)x[edges[i]],
475 (int)y[edges[i]], (int)x[edges[i]+1], (int)y[edges[i]+1], width, color, false);
481 float actualLength = 0;
482 for(int i=0; i<numvertices; i++) {
483 // skip over MOVETOs -- they do not contribute to path length
484 if (x[i] == x[i+1] && y[i] == y[i+1]) continue;
485 if (x[i+1] == x[i+2] && y[i+1] == y[i+2]) continue;
490 actualLength += java.lang.Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
492 ratio = actualLength / segLength;
494 Tokenizer pt = new Tokenizer(dashArray);
495 Vector v = new Vector();
496 while (pt.hasMoreTokens()) v.addElement(new Float(pt.parseFloat()));
497 float[] dashes = new float[v.size() % 2 == 0 ? v.size() : 2 * v.size()];
498 for(int i=0; i<dashes.length; i++) dashes[i] = ((Float)v.elementAt(i % v.size())).floatValue();
499 int dashpos = dashOffset;
500 boolean on = dashpos % 2 == 0;
501 for(int i=0; i<numvertices; i++) {
502 // skip over MOVETOs -- they do not contribute to path length
503 if (x[i] == x[i+1] && y[i] == y[i+1]) continue;
504 if (x[i+1] == x[i+2] && y[i+1] == y[i+2]) continue;
506 int x2 = (int)x[i + 1];
508 int y2 = (int)y[i + 1];
509 float segmentLength = (float)java.lang.Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
510 int _x1 = x1, _y1 = y1;
513 pos = Math.min(segmentLength, pos + dashes[dashpos] * ratio);
514 if (pos != segmentLength) dashpos = (dashpos + 1) % dashes.length;
515 int _x2 = (int)((x2 * pos + x1 * (segmentLength - pos)) / segmentLength);
516 int _y2 = (int)((y2 * pos + y1 * (segmentLength - pos)) / segmentLength);
517 if (on) buf.drawLine(_x1, _y1, _x2, _y2, width, color, false);
519 _x1 = _x2; _y1 = _y2;
520 } while(pos < segmentLength);
524 // FEATURE: make this faster and cache it; also deal with negative coordinates
525 public int boundingBoxWidth() {
527 for(int i=0; i<numvertices; i++) ret = Math.max(ret, x[i]);
531 // FEATURE: make this faster and cache it; also deal with negative coordinates
532 public int boundingBoxHeight() {
534 for(int i=0; i<numvertices; i++) ret = Math.max(ret, y[i]);