summaryrefslogtreecommitdiff
path: root/java/awt/geom/FlatteningPathIterator.java
blob: b06e6cc47b82f8ff0d2bdea372ae2b7c151c5c66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/* FlatteningPathIterator.java -- Approximates curves by straight lines
   Copyright (C) 2003 Free Software Foundation

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.awt.geom;

import java.util.NoSuchElementException;


/**
 * A PathIterator for approximating curved path segments by sequences
 * of straight lines. Instances of this class will only return
 * segments of type {@link PathIterator#SEG_MOVETO}, {@link
 * PathIterator#SEG_LINETO}, and {@link PathIterator#SEG_CLOSE}.
 *
 * <p>The accuracy of the approximation is determined by two
 * parameters:
 *
 * <ul><li>The <i>flatness</i> is a threshold value for deciding when
 * a curved segment is consided flat enough for being approximated by
 * a single straight line. Flatness is defined as the maximal distance
 * of a curve control point to the straight line that connects the
 * curve start and end. A lower flatness threshold means a closer
 * approximation.  See {@link QuadCurve2D#getFlatness()} and {@link
 * CubicCurve2D#getFlatness()} for drawings which illustrate the
 * meaning of flatness.</li>
 *
 * <li>The <i>recursion limit</i> imposes an upper bound for how often
 * a curved segment gets subdivided. A limit of <i>n</i> means that
 * for each individual quadratic and cubic B&#xe9;zier spline
 * segment, at most 2<sup><small><i>n</i></small></sup> {@link
 * PathIterator#SEG_LINETO} segments will be created.</li></ul>
 *
 * <p><b>Memory Efficiency:</b> The memory consumption grows linearly
 * with the recursion limit. Neither the <i>flatness</i> parameter nor
 * the number of segments in the flattened path will affect the memory
 * consumption.
 *
 * <p><b>Thread Safety:</b> Multiple threads can safely work on
 * separate instances of this class. However, multiple threads should
 * not concurrently access the same instance, as no synchronization is
 * performed.
 *
 * @see <a href="doc-files/FlatteningPathIterator-1.html"
 * >Implementation Note</a>
 *
 * @author Sascha Brawer (brawer@dandelis.ch)
 *
 * @since 1.2
 */
public class FlatteningPathIterator
  implements PathIterator
{
  /**
   * The PathIterator whose curved segments are being approximated.
   */
  private final PathIterator srcIter;


  /**
   * The square of the flatness threshold value, which determines when
   * a curve segment is considered flat enough that no further
   * subdivision is needed.
   *
   * <p>Calculating flatness actually produces the squared flatness
   * value. To avoid the relatively expensive calculation of a square
   * root for each curve segment, we perform all flatness comparisons
   * on squared values.
   *
   * @see QuadCurve2D#getFlatnessSq()
   * @see CubicCurve2D#getFlatnessSq()
   */
  private final double flatnessSq;


  /**
   * The maximal number of subdivions that are performed to
   * approximate a quadratic or cubic curve segment.
   */
  private final int recursionLimit;


  /**
   * A stack for holding the coordinates of subdivided segments.
   *
   * @see <a href="doc-files/FlatteningPathIterator-1.html"
   * >Implementation Note</a>
   */
  private double[] stack;


  /**
   * The current stack size.
   *
   * @see <a href="doc-files/FlatteningPathIterator-1.html"
   * >Implementation Note</a>
   */
  private int stackSize;


  /**
   * The number of recursions that were performed to arrive at
   * a segment on the stack.
   *
   * @see <a href="doc-files/FlatteningPathIterator-1.html"
   * >Implementation Note</a>
   */
  private int[] recLevel;

  
  
  private final double[] scratch = new double[6];


  /**
   * The segment type of the last segment that was returned by
   * the source iterator.
   */
  private int srcSegType;


  /**
   * The current <i>x</i> position of the source iterator.
   */
  private double srcPosX;


  /**
   * The current <i>y</i> position of the source iterator.
   */
  private double srcPosY;


  /**
   * A flag that indicates when this path iterator has finished its
   * iteration over path segments.
   */
  private boolean done;


  /**
   * Constructs a new PathIterator for approximating an input
   * PathIterator with straight lines. The approximation works by
   * recursive subdivisons, until the specified flatness threshold is
   * not exceeded.
   *
   * <p>There will not be more than 10 nested recursion steps, which
   * means that a single <code>SEG_QUADTO</code> or
   * <code>SEG_CUBICTO</code> segment is approximated by at most
   * 2<sup><small>10</small></sup> = 1024 straight lines.
   */
  public FlatteningPathIterator(PathIterator src, double flatness)
  {
    this(src, flatness, 10);
  }


  /**
   * Constructs a new PathIterator for approximating an input
   * PathIterator with straight lines. The approximation works by
   * recursive subdivisons, until the specified flatness threshold is
   * not exceeded.  Additionally, the number of recursions is also
   * bound by the specified recursion limit.
   */
  public FlatteningPathIterator(PathIterator src, double flatness,
                                int limit)
  {
    if (flatness < 0 || limit < 0)
      throw new IllegalArgumentException();

    srcIter = src;
    flatnessSq = flatness * flatness;
    recursionLimit = limit;
    fetchSegment();
  }


  /**
   * Returns the maximally acceptable flatness.
   *
   * @see QuadCurve2D#getFlatness()
   * @see CubicCurve2D#getFlatness()
   */
  public double getFlatness()
  {
    return Math.sqrt(flatnessSq);
  }


  /**
   * Returns the maximum number of recursive curve subdivisions.
   */
  public int getRecursionLimit()
  {
    return recursionLimit;
  }


  // Documentation will be copied from PathIterator.
  public int getWindingRule()
  {
    return srcIter.getWindingRule();
  }


  // Documentation will be copied from PathIterator.
  public boolean isDone()
  {
    return done;
  }


  // Documentation will be copied from PathIterator.
  public void next()
  {
    if (stackSize > 0)
    {
      --stackSize;
      if (stackSize > 0)
      {
        switch (srcSegType)
        {
        case PathIterator.SEG_QUADTO:
          subdivideQuadratic();
          return;

        case PathIterator.SEG_CUBICTO:
          subdivideCubic();
          return;

        default:
          throw new IllegalStateException();
        }
      }
    }

    srcIter.next();
    fetchSegment();
  }


  // Documentation will be copied from PathIterator.
  public int currentSegment(double[] coords)
  {
    if (done)
      throw new NoSuchElementException();

    switch (srcSegType)
    {
    case PathIterator.SEG_CLOSE:
      return srcSegType;

    case PathIterator.SEG_MOVETO:
    case PathIterator.SEG_LINETO:
      coords[0] = srcPosX;
      coords[1] = srcPosY;
      return srcSegType;

    case PathIterator.SEG_QUADTO:
      if (stackSize == 0)
      {
        coords[0] = srcPosX;
        coords[1] = srcPosY;
      }
      else
      {
        int sp = stack.length - 4 * stackSize;
        coords[0] = stack[sp + 2];
        coords[1] = stack[sp + 3];
      }
      return PathIterator.SEG_LINETO;

    case PathIterator.SEG_CUBICTO:
      if (stackSize == 0)
      {
        coords[0] = srcPosX;
        coords[1] = srcPosY;
      }
      else
      {
        int sp = stack.length - 6 * stackSize;
        coords[0] = stack[sp + 4];
        coords[1] = stack[sp + 5];
      }
      return PathIterator.SEG_LINETO;
    }

    throw new IllegalStateException();
  }


  // Documentation will be copied from PathIterator.
  public int currentSegment(float[] coords)
  {
    if (done)
      throw new NoSuchElementException();

    switch (srcSegType)
    {
    case PathIterator.SEG_CLOSE:
      return srcSegType;

    case PathIterator.SEG_MOVETO:
    case PathIterator.SEG_LINETO:
      coords[0] = (float) srcPosX;
      coords[1] = (float) srcPosY;
      return srcSegType;

    case PathIterator.SEG_QUADTO:
      if (stackSize == 0)
      {
        coords[0] = (float) srcPosX;
        coords[1] = (float) srcPosY;
      }
      else
      {
        int sp = stack.length - 4 * stackSize;
        coords[0] = (float) stack[sp + 2];
        coords[1] = (float) stack[sp + 3];
      }
      return PathIterator.SEG_LINETO;

    case PathIterator.SEG_CUBICTO:
      if (stackSize == 0)
      {
        coords[0] = (float) srcPosX;
        coords[1] = (float) srcPosY;
      }
      else
      {
        int sp = stack.length - 6 * stackSize;
        coords[0] = (float) stack[sp + 4];
        coords[1] = (float) stack[sp + 5];
      }
      return PathIterator.SEG_LINETO;
    }

    throw new IllegalStateException();
  }


  /**
   * Fetches the next segment from the source iterator.
   */
  private void fetchSegment()
  {
    int sp;

    if (srcIter.isDone())
    {
      done = true;
      return;
    }

    srcSegType = srcIter.currentSegment(scratch);
    
    switch (srcSegType)
    {
    case PathIterator.SEG_CLOSE:
      return;

    case PathIterator.SEG_MOVETO:
    case PathIterator.SEG_LINETO:
      srcPosX = scratch[0];
      srcPosY = scratch[1];
      return;

    case PathIterator.SEG_QUADTO:
      if (recursionLimit == 0)
      {
        srcPosX = scratch[2];
        srcPosY = scratch[3];
        stackSize = 0;
        return;
      }
      sp = 4 * recursionLimit;
      stackSize = 1;
      if (stack == null)
      {
        stack = new double[sp + /* 4 + 2 */ 6];
        recLevel = new int[recursionLimit + 1];
      }
      recLevel[0] = 0;
      stack[sp] = srcPosX;                  // P1.x
      stack[sp + 1] = srcPosY;              // P1.y
      stack[sp + 2] = scratch[0];           // C.x
      stack[sp + 3] = scratch[1];           // C.y
      srcPosX = stack[sp + 4] = scratch[2]; // P2.x
      srcPosY = stack[sp + 5] = scratch[3]; // P2.y
      subdivideQuadratic();
      break;

    case PathIterator.SEG_CUBICTO:
      if (recursionLimit == 0)
      {
        srcPosX = scratch[4];
        srcPosY = scratch[5];
        stackSize = 0;
        return;
      }
      sp = 6 * recursionLimit;
      stackSize = 1;
      if ((stack == null) || (stack.length < sp + 8))
      {
        stack = new double[sp + /* 6 + 2 */ 8];
        recLevel = new int[recursionLimit + 1];
      }
      recLevel[0] = 0;
      stack[sp] = srcPosX;                  // P1.x
      stack[sp + 1] = srcPosY;              // P1.y
      stack[sp + 2] = scratch[0];           // C1.x
      stack[sp + 3] = scratch[1];           // C1.y
      stack[sp + 4] = scratch[2];           // C2.x
      stack[sp + 5] = scratch[3];           // C2.y
      srcPosX = stack[sp + 6] = scratch[4]; // P2.x
      srcPosY = stack[sp + 7] = scratch[5]; // P2.y
      subdivideCubic();
      return;
    }
  }


  /**
   * Repeatedly subdivides the quadratic curve segment that is on top
   * of the stack. The iteration terminates when the recursion limit
   * has been reached, or when the resulting segment is flat enough.
   */
  private void subdivideQuadratic()
  {
    int sp;
    int level;

    sp = stack.length - 4 * stackSize - 2;
    level = recLevel[stackSize - 1];
    while ((level < recursionLimit)
           && (QuadCurve2D.getFlatnessSq(stack, sp) >= flatnessSq))
    {
      recLevel[stackSize] = recLevel[stackSize - 1] = ++level;
      QuadCurve2D.subdivide(stack, sp, stack, sp - 4, stack, sp);
      ++stackSize;
      sp -= 4;
    }
  }


  /**
   * Repeatedly subdivides the cubic curve segment that is on top
   * of the stack. The iteration terminates when the recursion limit
   * has been reached, or when the resulting segment is flat enough.
   */
  private void subdivideCubic()
  {
    int sp;
    int level;

    sp = stack.length - 6 * stackSize - 2;
    level = recLevel[stackSize - 1];
    while ((level < recursionLimit)
           && (CubicCurve2D.getFlatnessSq(stack, sp) >= flatnessSq))
    {
      recLevel[stackSize] = recLevel[stackSize - 1] = ++level;
      
      CubicCurve2D.subdivide(stack, sp, stack, sp - 6, stack, sp);
      ++stackSize;
      sp -= 6;
    }
  }


  /* These routines were useful for debugging. Since they would
   * just bloat the implementation, they are commented out.
   *
   *

  private static String segToString(int segType, double[] d, int offset)
  {
    String s;

    switch (segType)
    {
    case PathIterator.SEG_CLOSE:
      return "SEG_CLOSE";

    case PathIterator.SEG_MOVETO:
      return "SEG_MOVETO (" + d[offset] + ", " + d[offset + 1] + ")";

    case PathIterator.SEG_LINETO:
      return "SEG_LINETO (" + d[offset] + ", " + d[offset + 1] + ")";

    case PathIterator.SEG_QUADTO:
      return "SEG_QUADTO (" + d[offset] + ", " + d[offset + 1]
        + ") (" + d[offset + 2] + ", " + d[offset + 3] + ")";

    case PathIterator.SEG_CUBICTO:
      return "SEG_CUBICTO (" + d[offset] + ", " + d[offset + 1]
        + ") (" + d[offset + 2] + ", " + d[offset + 3]
        + ") (" + d[offset + 4] + ", " + d[offset + 5] + ")";
    }

    throw new IllegalStateException();
  }


  private void dumpQuadraticStack(String msg)
  {
    int sp = stack.length - 4 * stackSize - 2;
    int i = 0;
    System.err.print("    " + msg + ":");
    while (sp < stack.length)
    {
      System.err.print(" (" + stack[sp] + ", " + stack[sp+1] + ")");
      if (i < recLevel.length)
        System.out.print("/" + recLevel[i++]);
      if (sp + 3 < stack.length)
        System.err.print(" [" + stack[sp+2] + ", " + stack[sp+3] + "]");
      sp += 4;
    }
    System.err.println();
  }


  private void dumpCubicStack(String msg)
  {
    int sp = stack.length - 6 * stackSize - 2;
    int i = 0;
    System.err.print("    " + msg + ":");
    while (sp < stack.length)
    {
      System.err.print(" (" + stack[sp] + ", " + stack[sp+1] + ")");
      if (i < recLevel.length)
        System.out.print("/" + recLevel[i++]);
      if (sp + 3 < stack.length)
      {
        System.err.print(" [" + stack[sp+2] + ", " + stack[sp+3] + "]");
        System.err.print(" [" + stack[sp+4] + ", " + stack[sp+5] + "]");
      }
      sp += 6;
    }
    System.err.println();
  }

  *
  *
  */
}