new PixelBuffer API (mainly tons of renames)
[org.ibex.core.git] / src / org / ibex / graphics / Polygon.java
1 package org.ibex.graphics;\r
2 import java.util.*;\r
3 import org.ibex.util.*;\r
4 \r
5 //\r
6 // This is a very heavily modified (nearly complete rewrite) version\r
7 // of GPCJ, which is itself a Java port of the Generalized Polygon\r
8 // Clipping Library\r
9 // \r
10 //   http://www.cs.man.ac.uk/aig/staff/alan/software/gpc.html\r
11 //\r
12 // Modifications by Adam Megacz\r
13 //\r
14 \r
15 // Possible remaining optimizations:\r
16 //   -- recycle EdgeNode instances\r
17 //   -- evolve PolygonNode into the Polygon class?\r
18 \r
19 //\r
20 // !! WARNING !!  !! WARNING !!  !! WARNING !!\r
21 //\r
22 // Unlike GPCJ, this code is NOT reentrant or thread-safe; static\r
23 // arrays are used to avoid allocation penalties.  Also, the union(),\r
24 // intersection(), and xor() methods destructively update the 'this'\r
25 // object.\r
26 //\r
27 \r
28 /*\r
29  * The SEI Software Open Source License, Version 1.0\r
30  *\r
31  * Copyright (c) 2004, Solution Engineering, Inc.\r
32  * All rights reserved.\r
33  *\r
34  * Redistribution and use in source and binary forms, with or without\r
35  * modification, are permitted provided that the following conditions\r
36  * are met:\r
37  *\r
38  * 1. Redistributions of source code must retain the above copyright\r
39  *    notice, this list of conditions and the following disclaimer. \r
40  *\r
41  * 2. The end-user documentation included with the redistribution,\r
42  *    if any, must include the following acknowledgment:\r
43  *       "This product includes software developed by the\r
44  *        Solution Engineering, Inc. (http://www.seisw.com/)."\r
45  *    Alternately, this acknowledgment may appear in the software itself,\r
46  *    if and wherever such third-party acknowledgments normally appear.\r
47  *\r
48  * 3. The name "Solution Engineering" must not be used to endorse or\r
49  *    promote products derived from this software without prior\r
50  *    written permission. For written permission, please contact\r
51  *    admin@seisw.com.\r
52  *\r
53  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\r
54  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r
55  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
56  * DISCLAIMED.  IN NO EVENT SHALL SOLUTION ENGINEERING, INC. OR\r
57  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
58  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
59  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\r
60  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r
61  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r
62  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\r
63  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r
64  * SUCH DAMAGE.\r
65  * ====================================================================\r
66  */\r
67 \r
68 \r
69 public final class Polygon {\r
70 \r
71     private static final int DEFAULT_PATHLEN  =  10;\r
72     private static final int DEFAULT_CONTOURS =   4;\r
73 \r
74     private static final int BIGNUM = 65535;\r
75 \r
76     public boolean[] hole             = new boolean[DEFAULT_CONTOURS];\r
77     public boolean[] contributing     = new boolean[DEFAULT_CONTOURS];\r
78     public float[]   x                = new float[DEFAULT_PATHLEN];\r
79     public float[]   y                = new float[DEFAULT_PATHLEN];\r
80     public int       numvertices      = 0;\r
81     public int[]     edges            = null;\r
82     public int       numedges         = 0;\r
83     public int[]     contours         = new int[DEFAULT_CONTOURS];\r
84     public int       numcontours      = 0;\r
85     public float[]   minx_            = new float[DEFAULT_CONTOURS];\r
86     public float[]   miny_            = new float[DEFAULT_CONTOURS];\r
87     public float[]   maxx_            = new float[DEFAULT_CONTOURS];\r
88     public float[]   maxy_            = new float[DEFAULT_CONTOURS];\r
89     public float     minx             = Float.MAX_VALUE;\r
90     public float     miny             = Float.MAX_VALUE;\r
91     public float     maxx             = Float.MIN_VALUE;\r
92     public float     maxy             = Float.MIN_VALUE;\r
93     public boolean   sealed           = false;\r
94 \r
95     public Polygon() { }\r
96     public Polygon(Path p, Affine a) { p.addTo(this, a); }\r
97     public void intersection(Polygon p2) { clip(GPC_INT, this, p2); }\r
98     public void intersect(Polygon p2) { clip(GPC_INT, this, p2); }\r
99     public void union(Polygon p2) { clip(GPC_UNION, this, p2); }\r
100     public void xor(Polygon p2) { clip(GPC_XOR, this, p2); }\r
101     public void subtract(Polygon p2) { clip(GPC_DIFF, this, p2); }\r
102     private static Polygon rectclipper = new Polygon();\r
103     public void addrect(float x1, float y1, float x2, float y2, Affine a) {\r
104         add(a.multiply_px(x1, y1), a.multiply_py(x1, y1));\r
105         add(a.multiply_px(x2, y1), a.multiply_py(x2, y1));\r
106         add(a.multiply_px(x2, y2), a.multiply_py(x2, y2));\r
107         add(a.multiply_px(x1, y2), a.multiply_py(x1, y2));\r
108         closepath();\r
109     }\r
110     public void clipto(float x1, float y1, float x2, float y2, Affine a) {\r
111         rectclipper.clear();\r
112         rectclipper.addrect(x1, y1, x2, y2, a);\r
113         intersection(rectclipper);\r
114     }\r
115     public void closepath() {\r
116         if (numcontours > 0 && numvertices == 0) return;\r
117         if (numcontours > 0 && (x[contours[numcontours-1]] != x[numvertices-1] || y[contours[numcontours-1]] != y[numvertices-1]))\r
118             add(x[contours[numcontours-1]], y[contours[numcontours-1]]);\r
119     }\r
120     public void newcontour() {\r
121         if (numcontours > 0 && numvertices == contours[numcontours-1]) return;\r
122         closepath();\r
123         maxx_[numcontours] = maxy_[numcontours] = Float.MIN_VALUE;\r
124         minx_[numcontours] = miny_[numcontours] = Float.MAX_VALUE;\r
125         contours[numcontours++] = numvertices;\r
126         if (numcontours >= contours.length - 2) {\r
127             int[] z = new int[contours.length * 4]; System.arraycopy(contours, 0, z, 0, contours.length); contours = z;\r
128             boolean[] s = new boolean[hole.length * 4]; System.arraycopy(hole, 0, s, 0, hole.length); hole = s;\r
129             s = new boolean[contributing.length * 4];System.arraycopy(contributing,0,s,0,contributing.length);contributing = s;\r
130             float[] f = new float[minx_.length * 4]; System.arraycopy(minx_, 0, f, 0, minx_.length); minx_ = f;\r
131             f = new float[maxx_.length * 4]; System.arraycopy(maxx_, 0, f, 0, maxx_.length); maxx_ = f;\r
132             f = new float[miny_.length * 4]; System.arraycopy(miny_, 0, f, 0, miny_.length); miny_ = f;\r
133             f = new float[maxy_.length * 4]; System.arraycopy(maxy_, 0, f, 0, maxy_.length); maxy_ = f;\r
134             Log.debug(this, "growing contour list to " + contours.length);\r
135         } \r
136     }\r
137     public void add(float x, float y) {\r
138         if (sealed) { Log.error(this, "tried to add a vertex to a sealed polygon!"); return; }\r
139         if (numcontours == 0) newcontour();\r
140         this.x[numvertices] = x;\r
141         this.y[numvertices] = y;\r
142         numvertices++;\r
143         if (x > maxx_[numcontours-1]) maxx_[numcontours-1] = x;\r
144         if (x < minx_[numcontours-1]) minx_[numcontours-1] = x;\r
145         if (y > maxy_[numcontours-1]) maxy_[numcontours-1] = y;\r
146         if (y < miny_[numcontours-1]) miny_[numcontours-1] = y;\r
147         if (x > maxx) maxx = x;\r
148         if (x < minx) minx = x;\r
149         if (y > maxy) maxy = y;\r
150         if (y < miny) miny = y;\r
151         if (numvertices >= this.x.length) {\r
152             float[] new_x = new float[this.x.length * 4]; System.arraycopy(this.x, 0, new_x, 0, this.x.length); this.x = new_x;\r
153             float[] new_y = new float[this.y.length * 4]; System.arraycopy(this.y, 0, new_y, 0, this.y.length); this.y = new_y;\r
154             Log.debug(this, "growing vertex list to " + this.x.length);\r
155         } \r
156     }\r
157     public void clear() {\r
158         numvertices = 0; numedges = 0; numcontours = 0; sealed = false;\r
159         maxx = Float.MIN_VALUE; maxy = Float.MIN_VALUE; minx = Float.MAX_VALUE; miny = Float.MIN_VALUE;\r
160     }\r
161     public boolean isEmpty() { return numvertices == 0; }\r
162     public void add(Polygon p) { add(p, Affine.identity()); }\r
163     public void add(Polygon p, Affine a) { for(int i=0; i<p.numcontours; i++) add(p, i, a); }\r
164     public void add(Polygon p, int idx) { add(p, idx, Affine.identity()); }\r
165     public void add(Polygon p, int idx, Affine a) {\r
166         newcontour();\r
167         for(int i=p.contours[idx]; i<p.contours[idx+1]; i++) {\r
168             float x = p.x[p.contours[idx]+i];\r
169             float y = p.y[p.contours[idx]+i];\r
170             add(a.multiply_px(x, y), a.multiply_py(x, y));\r
171         }\r
172     }\r
173     public void transform(Affine a) {\r
174         maxx = Float.MIN_VALUE; maxy = Float.MIN_VALUE; minx = Float.MAX_VALUE; miny = Float.MIN_VALUE;\r
175         int s = 0;\r
176         for(int i=0; i<numvertices; i++) {\r
177             while (i >= contours[s+1]) s++;\r
178             float x = a.multiply_px(this.x[i], this.y[i]);\r
179             float y = a.multiply_py(this.x[i], this.y[i]);\r
180             this.x[i] = x; \r
181             this.y[i] = y; \r
182             if (x > maxx_[s]) maxx_[s] = x;\r
183             if (x < minx_[s]) minx_[s] = x;\r
184             if (y > maxy_[s]) maxy_[s] = y;\r
185             if (y < miny_[s]) miny_[s] = y;\r
186             if (x > maxx) maxx = x;\r
187             if (x < minx) minx = x;\r
188             if (y > maxy) maxy = y;\r
189             if (y < miny) miny = y;\r
190         }\r
191     }\r
192 \r
193     public void stroke(PixelBuffer buf, int color) {\r
194         Polygon p = this;\r
195         if (!p.sealed) p.sort();\r
196         for(int i=0; i<p.numedges; i++) {\r
197             float x1 = p.x[p.edges[i]];\r
198             float y1 = p.y[p.edges[i]];\r
199             float x2 = p.x[p.edges[i]+1];\r
200             float y2 = p.y[p.edges[i]+1];\r
201             buf.drawLine((int)Math.floor(x1), (int)Math.floor(y1), (int)Math.ceil(x2), (int)Math.ceil(y2), color);\r
202         }\r
203     }\r
204 \r
205     /** finds the x value at which the line intercepts the line y=_y */\r
206     private int intercept(int i, float _y, boolean includeTop, boolean includeBottom) {\r
207         Polygon p = this;\r
208         if (includeTop ? (_y < Math.min(p.y[i], p.y[i+1])) : (_y <= Math.min(p.y[i], p.y[i+1])))\r
209             return Integer.MIN_VALUE;\r
210         if (includeBottom ? (_y > Math.max(p.y[i], p.y[i+1])) : (_y >= Math.max(p.y[i], p.y[i+1])))\r
211             return Integer.MIN_VALUE;\r
212         float f = (((float)(p.x[i + 1] - p.x[i])) / ((float)(p.y[i + 1] - p.y[i])) ) * ((float)(_y - p.y[i])) + p.x[i];\r
213         return (int)Math.floor(f);\r
214     }\r
215 \r
216     /** fill the interior of the path */\r
217     public void fill(PixelBuffer buf, Paint paint) {\r
218         Polygon p = this;\r
219         if (!p.sealed) p.sort();\r
220         if (p.numedges == 0) return;\r
221         float y0 = p.y[p.edges[0]], y1 = y0;\r
222         boolean useEvenOdd = false;\r
223 \r
224         // we iterate over all endpoints in increasing y-coordinate order\r
225         OUTER: for(int index = 1; index<p.numedges; index++) {\r
226             int count = 0;\r
227 \r
228             // we now examine the horizontal band between y=y0 and y=y1\r
229             y0 = y1;\r
230             y1 = p.y[p.edges[index]];\r
231             if (y0 == y1) continue;\r
232 \r
233             // within this band, we iterate over all p.edges\r
234             int x0 = Integer.MIN_VALUE;\r
235             int leftSegment = -1;\r
236             while(true) {\r
237                 int x1 = Integer.MAX_VALUE;\r
238                 int rightSegment = Integer.MAX_VALUE;\r
239                 for(int i=0; i<p.numedges; i++) {\r
240                     if (p.y[p.edges[i]] == p.y[p.edges[i]+1]) continue; // ignore horizontal lines; they are irrelevant.\r
241                     // we order the segments by the x-coordinate of their midpoint;\r
242                     // since segments cannot intersect, this is a well-ordering\r
243                     int i0 = intercept(p.edges[i], y0, true, false);\r
244                     int i1 = intercept(p.edges[i], y1, false, true);\r
245                     if (i0 == Integer.MIN_VALUE || i1 == Integer.MIN_VALUE) continue;\r
246                     int midpoint = i0 + i1;\r
247                     if (midpoint < x0) continue;\r
248                     if (midpoint == x0 && i <= leftSegment) continue;\r
249                     if (midpoint > x1) continue;\r
250                     if (midpoint == x1 && i >= rightSegment) continue;\r
251                     rightSegment = i;\r
252                     x1 = midpoint;\r
253                 }\r
254                 if (leftSegment == rightSegment || rightSegment == Integer.MAX_VALUE) break;\r
255                 if (leftSegment != -1)\r
256                     if ((useEvenOdd && count % 2 != 0) || (!useEvenOdd && count != 0)) {\r
257                         int tx1a = intercept(p.edges[leftSegment], y0, true, true);\r
258                         int tx1b = intercept(p.edges[rightSegment], y0, true, true);\r
259                         int tx2a = intercept(p.edges[leftSegment], y1, true, true);\r
260                         int tx2b = intercept(p.edges[rightSegment], y1, true, true);\r
261                         buf.fillTrapezoid(tx1a, tx1b, (int)y0, tx2a, tx2b, (int)y1, ((Paint.SingleColorPaint)paint).color);\r
262                     }\r
263                 if (useEvenOdd) count++;\r
264                 else count += (p.y[p.edges[rightSegment]] < p.y[p.edges[rightSegment]+1]) ? -1 : 1;\r
265                 leftSegment = rightSegment; x0 = x1;\r
266             }\r
267         }\r
268     }\r
269 \r
270     //////////////////////////////////////////////////////////////////////////////\r
271 \r
272     public Polygon sort() {\r
273         closepath();\r
274         contours[numcontours] = numvertices;\r
275         sealed = true;\r
276         numedges = 0;\r
277         edges = new int[numvertices];\r
278         for(int i=0; i<numcontours; i++)\r
279             for(int j=contours[i]; j<contours[i+1]-1; j++)\r
280                 edges[numedges++] = j;\r
281         sort(0, numedges - 1, false);\r
282         return this;\r
283     }\r
284 \r
285     /** simple quicksort, from http://sourceforge.net/snippet/detail.php?type=snippet&id=100240 */\r
286     int sort(int left, int right, boolean partition) {\r
287         if (partition) {\r
288             int i, j, middle;\r
289             middle = (left + right) / 2;\r
290             int s = edges[right]; edges[right] = edges[middle]; edges[middle] = s;\r
291             for (i = left - 1, j = right; ; ) {\r
292                 while (y[edges[++i]] < y[edges[right]]);\r
293                 while (j > left && y[edges[--j]] > y[edges[right]]);\r
294                 if (i >= j) break;\r
295                 s = edges[i]; edges[i] = edges[j]; edges[j] = s;\r
296             }\r
297             s = edges[right]; edges[right] = edges[i]; edges[i] = s;\r
298             return i;\r
299         } else {\r
300             if (left >= right) return 0;\r
301             int p = sort(left, right, true);\r
302             sort(left, p - 1, false);\r
303             sort(p + 1, right, false);\r
304             return 0;\r
305         }\r
306     }\r
307 \r
308     // Rendering //////////////////////////////////////////////////////////////////////////////\r
309 \r
310        \r
311     private static int bound(int min, int mid, int max) { return mid < min ? min : mid > max ? max : mid; }\r
312 \r
313     public String toString(int i) {\r
314         String ret = "    ";\r
315         for(int j=contours[i]; j<contours[i+1]; j++) ret += x[j]+","+y[j];\r
316         return ret + "\n";\r
317     }\r
318     public String toString() {\r
319         String ret = "Polygon\n";\r
320         for(int i=0; i<numcontours; i++) ret += toString(i);\r
321         return ret;\r
322     }\r
323 \r
324 \r
325     // GPC //////////////////////////////////////////////////////////////////////////////\r
326 \r
327     //private static final float GPC_EPSILON = 2.2204460492503131e-016 ;\r
328     private static final float GPC_EPSILON = (float)1e-8;\r
329     private static final String GPC_VERSION = "2.31" ;\r
330     private static final int LEFT  = 0 ;\r
331     private static final int RIGHT = 1 ;\r
332     private static final int ABOVE = 0 ;\r
333     private static final int BELOW = 1 ;\r
334     private static final int CLIP = 0 ;\r
335     private static final int SUBJ = 1 ;\r
336     \r
337     // evilbadnonthreadsafestuff\r
338     private static ScanBeamList sbte       = new ScanBeamList();\r
339     private static EdgeTable s_heap        = new EdgeTable();\r
340     private static EdgeTable c_heap        = new EdgeTable();\r
341     private static LmtTable lmt_table      = new LmtTable();\r
342     private static TopPolygonNode out_poly = new TopPolygonNode();\r
343     private static AetTree aet             = new AetTree();\r
344     private static ItNodeTable it_table    = new ItNodeTable();\r
345 \r
346     private static Polygon clip(byte op, Polygon subj, Polygon clip) {\r
347         try {\r
348             return clip_(op, subj, clip);\r
349         } catch (Exception npe) {\r
350             npe.printStackTrace();\r
351             return null;\r
352         }\r
353     }\r
354     private static Polygon clip_(byte op, Polygon subj, Polygon clip) {\r
355       int parity_CLIP = LEFT;\r
356       int parity_SUBJ = LEFT;\r
357       float[] sbt = null;\r
358       int local_min = 0;\r
359       int scanbeam = 0;\r
360 \r
361       numFreeEdgeNodes = numEdgeNodes;\r
362 \r
363         subj.closepath(); subj.contours[subj.numcontours] = subj.numvertices;\r
364         clip.closepath(); clip.contours[clip.numcontours] = clip.numvertices;\r
365         PolygonNode.clear();\r
366 \r
367       // Test for trivial NULL result cases \r
368       if ((subj.isEmpty() && clip.isEmpty()) || (subj.isEmpty() && ((op == GPC_INT) || (op == GPC_DIFF))) ||\r
369           (clip.isEmpty() &&  (op == GPC_INT)))\r
370           { subj.clear(); return subj; }\r
371       \r
372       // Identify potentialy contributing contours \r
373       if (((op == GPC_INT) || (op == GPC_DIFF)) && !subj.isEmpty() && !clip.isEmpty())\r
374          minimax_test(subj, clip, op);\r
375       \r
376       // Build LMT \r
377       lmt_table.clear();\r
378       sbte.clear();\r
379       s_heap.clear();\r
380       c_heap.clear();\r
381       if (!subj.isEmpty()) build_lmt(s_heap, lmt_table, sbte, subj, SUBJ, op);\r
382       if (!clip.isEmpty()) build_lmt(c_heap, lmt_table, sbte, clip, CLIP, op);\r
383       if (lmt_table.isEmpty()) { subj.clear(); return subj; }    // Return a NULL result if no contours contribute\r
384 \r
385       // Build scanbeam table from scanbeam tree \r
386             sbt = sbte.sort();\r
387       // Invert clip polygon for difference operation \r
388       if (op == GPC_DIFF) parity_CLIP = RIGHT;\r
389       out_poly.clear();\r
390       aet.clear();\r
391       \r
392       // Process each scanbeam \r
393       while(scanbeam < sbte.entries) {\r
394          // Set yb and yt to the bottom and top of the scanbeam \r
395          float yb = sbt[scanbeam++];\r
396          float yt = (float)0.0;\r
397          float dy = (float)0.0;\r
398          if (scanbeam < sbte.entries) { yt = sbt[scanbeam]; dy = yt - yb; }\r
399   \r
400          // === SCANBEAM BOUNDARY PROCESSING ================================ \r
401          // If LMT node corresponding to yb exists \r
402          if (local_min < lmt_table.numentries && lmt_table.y[local_min] == yb) {\r
403              // Add edges starting at this local minimum to the AET \r
404              for(EdgeNode edge = lmt_table.first_bound[local_min]; (edge != null); edge= edge.next_bound)\r
405                  add_edge_to_aet(aet, edge);\r
406              local_min++;\r
407          }\r
408          \r
409          float px = -Float.MAX_VALUE;    // Set dummy previous x value\r
410          EdgeNode e0 = aet.top_node;       // Create bundles within AET\r
411          EdgeNode e1 = aet.top_node;\r
412          \r
413          // Set up bundle fields of first edge \r
414          if (aet.top_node.type == CLIP) aet.top_node.bundle_ABOVE_CLIP = (aet.top_node.top_y != yb) ? 1 : 0;\r
415          else aet.top_node.bundle_ABOVE_SUBJ = (aet.top_node.top_y != yb) ? 1 : 0;\r
416 \r
417          if (((aet.top_node.type==0) ? 1 : 0) == CLIP) aet.top_node.bundle_ABOVE_CLIP = 0;\r
418          else aet.top_node.bundle_ABOVE_SUBJ = 0;\r
419          aet.top_node.bstate_ABOVE = UNBUNDLED;\r
420 \r
421          for (EdgeNode next_edge = aet.top_node.next; next_edge != null; next_edge = next_edge.next) {\r
422             int ne_type = next_edge.type;\r
423             int ne_type_opp = ((next_edge.type==0) ? 1 : 0);  // next edge type opposite\r
424             \r
425             // Set up bundle fields of next edge \r
426             if (ne_type     == CLIP) next_edge.bundle_ABOVE_CLIP = (next_edge.top_y != yb) ? 1 : 0;\r
427             else next_edge.bundle_ABOVE_SUBJ = (next_edge.top_y != yb) ? 1 : 0;                \r
428             if (ne_type_opp == CLIP) next_edge.bundle_ABOVE_CLIP  = 0;\r
429             else next_edge.bundle_ABOVE_SUBJ  = 0;                \r
430             next_edge.bstate_ABOVE = UNBUNDLED;\r
431             \r
432             // Bundle edges above the scanbeam boundary if they coincide \r
433             if ((ne_type == CLIP ? next_edge.bundle_ABOVE_CLIP : next_edge.bundle_ABOVE_SUBJ) == 1) {\r
434                if (EQ(e0.xb, next_edge.xb) && EQ(e0.dx, next_edge.dx) && (e0.top_y != yb)) {\r
435                    if (ne_type == CLIP)\r
436                        next_edge.bundle_ABOVE_CLIP ^= ne_type == CLIP ? e0.bundle_ABOVE_CLIP : e0.bundle_ABOVE_SUBJ;\r
437                    else next_edge.bundle_ABOVE_SUBJ  ^= ne_type == CLIP ? e0.bundle_ABOVE_CLIP : e0.bundle_ABOVE_SUBJ;\r
438                    if (ne_type_opp == CLIP)\r
439                        next_edge.bundle_ABOVE_CLIP = ne_type_opp == CLIP ? e0.bundle_ABOVE_CLIP : e0.bundle_ABOVE_SUBJ;\r
440                    else next_edge.bundle_ABOVE_SUBJ = ne_type_opp == CLIP ? e0.bundle_ABOVE_CLIP : e0.bundle_ABOVE_SUBJ;\r
441                   next_edge.bstate_ABOVE = BUNDLE_HEAD;\r
442                   e0.bundle_ABOVE_CLIP = 0;\r
443                   e0.bundle_ABOVE_SUBJ = 0;\r
444                   e0.bstate_ABOVE = BUNDLE_TAIL;\r
445                }\r
446                e0 = next_edge;\r
447             }\r
448          }\r
449          \r
450          int horiz_CLIP = HState.NH;\r
451          int horiz_SUBJ = HState.NH;\r
452          int exists_CLIP = 0;\r
453          int exists_SUBJ = 0;\r
454          PolygonNode cf = null;\r
455          \r
456          // Process each edge at this scanbeam boundary \r
457          for (EdgeNode edge = aet.top_node; (edge != null); edge = edge.next) {\r
458              exists_CLIP = edge.bundle_ABOVE_CLIP + (edge.bundle_BELOW_CLIP << 1);\r
459              exists_SUBJ = edge.bundle_ABOVE_SUBJ + (edge.bundle_BELOW_SUBJ << 1);\r
460          \r
461             if ((exists_CLIP != 0) || (exists_SUBJ != 0)) {   // Set bundle side \r
462                edge.bside_CLIP = parity_CLIP;\r
463                edge.bside_SUBJ = parity_SUBJ;\r
464                boolean contributing = false;\r
465                int br=0, bl=0, tr=0, tl=0;\r
466                // Determine contributing status and quadrant occupancies \r
467                switch(op) {\r
468                    case GPC_DIFF:\r
469                    case GPC_INT:\r
470                        contributing= ((exists_CLIP!=0) && ((parity_SUBJ!=0) || (horiz_SUBJ!=0))) ||\r
471                            ((exists_SUBJ!=0) && ((parity_CLIP!=0) || (horiz_CLIP!=0))) ||\r
472                            ((exists_CLIP!=0) && (exists_SUBJ!=0) && (parity_CLIP == parity_SUBJ));\r
473                        br = ((parity_CLIP!=0) && (parity_SUBJ!=0)) ? 1 : 0;\r
474                        bl = (((parity_CLIP ^ edge.bundle_ABOVE_CLIP)!=0) &&\r
475                              ((parity_SUBJ ^ edge.bundle_ABOVE_SUBJ)!=0)) ? 1 : 0;\r
476                        tr = (((parity_CLIP ^ ((horiz_CLIP!=HState.NH)?1:0)) !=0) && \r
477                              ((parity_SUBJ ^ ((horiz_SUBJ!=HState.NH)?1:0)) !=0)) ? 1 : 0;\r
478                        tl = (((parity_CLIP ^ ((horiz_CLIP!=HState.NH)?1:0) ^ edge.bundle_BELOW_CLIP)!=0) &&\r
479                              ((parity_SUBJ ^ ((horiz_SUBJ!=HState.NH)?1:0) ^ edge.bundle_BELOW_SUBJ)!=0))?1:0;\r
480                        break;\r
481 \r
482                    case GPC_XOR:\r
483                        contributing= (exists_CLIP!=0) || (exists_SUBJ!=0);\r
484                        br= (parity_CLIP) ^ (parity_SUBJ);\r
485                        bl= (parity_CLIP ^ edge.bundle_ABOVE_CLIP) ^ (parity_SUBJ ^ edge.bundle_ABOVE_SUBJ);\r
486                        tr= (parity_CLIP ^ ((horiz_CLIP!=HState.NH)?1:0)) ^ (parity_SUBJ ^ ((horiz_SUBJ!=HState.NH)?1:0));\r
487                        tl= (parity_CLIP ^ ((horiz_CLIP!=HState.NH)?1:0) ^ edge.bundle_BELOW_CLIP)\r
488                            ^ (parity_SUBJ ^ ((horiz_SUBJ!=HState.NH)?1:0) ^ edge.bundle_BELOW_SUBJ);\r
489                        break;\r
490 \r
491                    case GPC_UNION:\r
492                        contributing= ((exists_CLIP!=0) && (!(parity_SUBJ!=0) || (horiz_SUBJ!=0))) ||\r
493                            ((exists_SUBJ!=0) && (!(parity_CLIP!=0) || (horiz_CLIP!=0))) ||\r
494                            ((exists_CLIP!=0) && (exists_SUBJ!=0) && (parity_CLIP == parity_SUBJ));\r
495                        br= ((parity_CLIP!=0) || (parity_SUBJ!=0))?1:0;\r
496                        bl= (((parity_CLIP ^ edge.bundle_ABOVE_CLIP)!=0) || ((parity_SUBJ ^ edge.bundle_ABOVE_SUBJ)!=0))?1:0;\r
497                        tr= (((parity_CLIP ^ ((horiz_CLIP!=HState.NH)?1:0))!=0) || \r
498                             ((parity_SUBJ ^ ((horiz_SUBJ!=HState.NH)?1:0))!=0)) ?1:0;\r
499                        tl= (((parity_CLIP ^ ((horiz_CLIP!=HState.NH)?1:0) ^ edge.bundle_BELOW_CLIP)!=0) ||\r
500                             ((parity_SUBJ ^ ((horiz_SUBJ!=HState.NH)?1:0) ^ edge.bundle_BELOW_SUBJ)!=0)) ? 1:0;\r
501                        break;\r
502                    default: throw new IllegalStateException("Unknown op");\r
503                }\r
504                \r
505                // Update parity \r
506                parity_CLIP ^= edge.bundle_ABOVE_CLIP;\r
507                parity_SUBJ ^= edge.bundle_ABOVE_SUBJ;\r
508                \r
509                // Update horizontal state \r
510                if (exists_CLIP!=0) horiz_CLIP = HState.next_h_state[horiz_CLIP][((exists_CLIP - 1) << 1) + parity_CLIP];\r
511                if (exists_SUBJ!=0) horiz_SUBJ = HState.next_h_state[horiz_SUBJ][((exists_SUBJ - 1) << 1) + parity_SUBJ];\r
512                \r
513                if (contributing) {\r
514                    float xb = edge.xb;\r
515                    int vclass = VertexType.getType(tr, tl, br, bl);\r
516                    switch (vclass) {\r
517                      case VertexType.EMN:\r
518                      case VertexType.IMN:\r
519                         edge.outp_ABOVE = out_poly.add_local_min(xb, yb);\r
520                         px = xb;\r
521                         cf = edge.outp_ABOVE;\r
522                         break;\r
523                      case VertexType.ERI:\r
524                         if (xb != px) { cf.add_right(xb, yb); px= xb; }\r
525                         edge.outp_ABOVE= cf;\r
526                         cf= null;\r
527                         break;\r
528                      case VertexType.ELI:\r
529                         edge.outp_BELOW.add_left(xb, yb);\r
530                         px= xb;\r
531                         cf= edge.outp_BELOW;\r
532                         break;\r
533                      case VertexType.EMX:\r
534                         if (xb != px) { cf.add_left(xb, yb); px= xb; }\r
535                         out_poly.merge_right(cf, edge.outp_BELOW);\r
536                         cf= null;\r
537                         break;\r
538                      case VertexType.ILI:\r
539                         if (xb != px) { cf.add_left(xb, yb); px= xb; }\r
540                         edge.outp_ABOVE= cf;\r
541                         cf= null;\r
542                         break;\r
543                      case VertexType.IRI:\r
544                         edge.outp_BELOW.add_right(xb, yb);\r
545                         px= xb;\r
546                         cf= edge.outp_BELOW;\r
547                         edge.outp_BELOW= null;\r
548                         break;\r
549                      case VertexType.IMX:\r
550                         if (xb != px) { cf.add_right(xb, yb); px= xb; }\r
551                         out_poly.merge_left(cf, edge.outp_BELOW);\r
552                         cf= null;\r
553                         edge.outp_BELOW= null;\r
554                         break;\r
555                      case VertexType.IMM:\r
556                         if (xb != px) { cf.add_right(xb, yb); px= xb; }\r
557                         out_poly.merge_left(cf, edge.outp_BELOW);\r
558                         edge.outp_BELOW= null;\r
559                         edge.outp_ABOVE = out_poly.add_local_min(xb, yb);\r
560                         cf= edge.outp_ABOVE;\r
561                         break;\r
562                      case VertexType.EMM:\r
563                         if (xb != px) { cf.add_left(xb, yb); px= xb; }\r
564                         out_poly.merge_right(cf, edge.outp_BELOW);\r
565                         edge.outp_BELOW= null;\r
566                         edge.outp_ABOVE = out_poly.add_local_min(xb, yb);\r
567                         cf= edge.outp_ABOVE;\r
568                         break;\r
569                      case VertexType.LED:\r
570                         if (edge.bot_y == yb) edge.outp_BELOW.add_left(xb, yb);\r
571                         edge.outp_ABOVE= edge.outp_BELOW;\r
572                         px= xb;\r
573                         break;\r
574                      case VertexType.RED:\r
575                         if (edge.bot_y == yb) edge.outp_BELOW.add_right(xb, yb);\r
576                         edge.outp_ABOVE= edge.outp_BELOW;\r
577                         px= xb;\r
578                         break;\r
579                      default:\r
580                         break;\r
581                   } // End of switch \r
582                } // End of contributing conditional \r
583             } // End of edge exists conditional \r
584          } // End of AET loop \r
585          \r
586          // Delete terminating edges from the AET, otherwise compute xt \r
587          for (EdgeNode edge = aet.top_node; (edge != null); edge = edge.next) {\r
588             if (edge.top_y == yb) {\r
589                 EdgeNode prev_edge = edge.prev;\r
590                 EdgeNode next_edge= edge.next;\r
591                \r
592                if (prev_edge != null) prev_edge.next = next_edge;\r
593                else aet.top_node = next_edge;\r
594                if (next_edge != null) next_edge.prev = prev_edge;\r
595                \r
596                // Copy bundle head state to the adjacent tail edge if required \r
597                if ((edge.bstate_BELOW == BUNDLE_HEAD) && (prev_edge!=null)) {\r
598                   if (prev_edge.bstate_BELOW == BUNDLE_TAIL) {\r
599                      prev_edge.outp_BELOW= edge.outp_BELOW;\r
600                      prev_edge.bstate_BELOW= UNBUNDLED;\r
601                      if (prev_edge.prev != null) {\r
602                         if (prev_edge.prev.bstate_BELOW == BUNDLE_TAIL)\r
603                            prev_edge.bstate_BELOW = BUNDLE_HEAD;\r
604                      }\r
605                   }\r
606                }\r
607             } else {\r
608                if (edge.top_y == yt) edge.xt = edge.top_x;\r
609                else edge.xt= edge.bot_x + edge.dx * (yt - edge.bot_y);\r
610             }\r
611          }\r
612                   \r
613          if (scanbeam < sbte.entries) {\r
614             // === SCANBEAM INTERIOR PROCESSING ============================== \r
615             // Build intersection table for the current scanbeam \r
616              it_table.clear();\r
617              it_table.build_intersection_table(aet, dy);\r
618          \r
619             // Process each node in the intersection table \r
620             for (int intersect = 0; intersect < it_table.num; intersect++) {\r
621                e0 = it_table.ie_0[intersect];\r
622                e1 = it_table.ie_1[intersect];\r
623                \r
624                // Only generate output for contributing intersections \r
625                if (((e0.bundle_ABOVE_CLIP!=0) || (e0.bundle_ABOVE_SUBJ!=0)) &&\r
626                    ((e1.bundle_ABOVE_CLIP!=0) || (e1.bundle_ABOVE_SUBJ!=0))) {\r
627 \r
628                   PolygonNode p = e0.outp_ABOVE;\r
629                   PolygonNode q = e1.outp_ABOVE;\r
630                   float ix = it_table.x[intersect];\r
631                   float iy = it_table.y[intersect] + yb;\r
632                \r
633                   int in_clip = (((e0.bundle_ABOVE_CLIP!=0) && !(e0.bside_CLIP!=0)) ||\r
634                                   ((e1.bundle_ABOVE_CLIP!=0) &&  (e1.bside_CLIP!=0)) ||\r
635                                   (!(e0.bundle_ABOVE_CLIP!=0) && !(e1.bundle_ABOVE_CLIP!=0) &&\r
636                                     (e0.bside_CLIP!=0) && (e1.bside_CLIP!=0))) ? 1 : 0;\r
637                   \r
638                   int in_subj = (((e0.bundle_ABOVE_SUBJ!=0) && !(e0.bside_SUBJ!=0)) ||\r
639                                   ((e1.bundle_ABOVE_SUBJ!=0) &&  (e1.bside_SUBJ!=0)) ||\r
640                                   (!(e0.bundle_ABOVE_SUBJ!=0) && !(e1.bundle_ABOVE_SUBJ!=0) &&\r
641                                     (e0.bside_SUBJ!=0) && (e1.bside_SUBJ!=0))) ? 1 : 0;\r
642         \r
643                   int tr=0, tl=0, br=0, bl=0;\r
644                   // Determine quadrant occupancies \r
645                   switch(op) {\r
646                       case GPC_DIFF:\r
647                       case GPC_INT:\r
648                           tr= ((in_clip!=0) && (in_subj!=0)) ? 1 : 0;\r
649                           tl= (((in_clip ^ e1.bundle_ABOVE_CLIP)!=0) && ((in_subj ^ e1.bundle_ABOVE_SUBJ)!=0))?1:0;\r
650                           br= (((in_clip ^ e0.bundle_ABOVE_CLIP)!=0) && ((in_subj ^ e0.bundle_ABOVE_SUBJ)!=0))?1:0;\r
651                           bl= (((in_clip ^ e1.bundle_ABOVE_CLIP ^ e0.bundle_ABOVE_CLIP)!=0) &&\r
652                                ((in_subj ^ e1.bundle_ABOVE_SUBJ ^ e0.bundle_ABOVE_SUBJ)!=0)) ? 1:0;\r
653                           break;\r
654                       case GPC_XOR:\r
655                           tr= (in_clip)^ (in_subj);\r
656                           tl= (in_clip ^ e1.bundle_ABOVE_CLIP) ^ (in_subj ^ e1.bundle_ABOVE_SUBJ);\r
657                           br= (in_clip ^ e0.bundle_ABOVE_CLIP) ^ (in_subj ^ e0.bundle_ABOVE_SUBJ);\r
658                           bl= (in_clip ^ e1.bundle_ABOVE_CLIP ^ e0.bundle_ABOVE_CLIP)\r
659                               ^ (in_subj ^ e1.bundle_ABOVE_SUBJ ^ e0.bundle_ABOVE_SUBJ);\r
660                           break;\r
661                       case GPC_UNION:\r
662                           tr= ((in_clip!=0) || (in_subj!=0)) ? 1 : 0;\r
663                           tl= (((in_clip ^ e1.bundle_ABOVE_CLIP)!=0) || ((in_subj ^ e1.bundle_ABOVE_SUBJ)!=0)) ? 1 : 0;\r
664                           br= (((in_clip ^ e0.bundle_ABOVE_CLIP)!=0) || ((in_subj ^ e0.bundle_ABOVE_SUBJ)!=0)) ? 1 : 0;\r
665                           bl= (((in_clip ^ e1.bundle_ABOVE_CLIP ^ e0.bundle_ABOVE_CLIP)!=0) ||\r
666                                ((in_subj ^ e1.bundle_ABOVE_SUBJ ^ e0.bundle_ABOVE_SUBJ)!=0)) ? 1 : 0;\r
667                           break;\r
668                       default: throw new IllegalStateException("Unknown op type, "+op);\r
669                   }\r
670                   \r
671                   int vclass = VertexType.getType(tr, tl, br, bl);\r
672                   switch (vclass) {\r
673                      case VertexType.EMN:\r
674                         e0.outp_ABOVE = out_poly.add_local_min(ix, iy);\r
675                         e1.outp_ABOVE = e0.outp_ABOVE;\r
676                         break;\r
677                      case VertexType.ERI:\r
678                         if (p != null) { p.add_right(ix, iy); e1.outp_ABOVE= p; e0.outp_ABOVE= null; }\r
679                         break;\r
680                      case VertexType.ELI:\r
681                         if (q != null) { q.add_left(ix, iy); e0.outp_ABOVE= q; e1.outp_ABOVE= null; }\r
682                         break;\r
683                      case VertexType.EMX:\r
684                         if ((p!=null) && (q!=null)) {\r
685                             p.add_left(ix, iy);\r
686                             out_poly.merge_right(p, q);\r
687                             e0.outp_ABOVE= null;\r
688                            e1.outp_ABOVE= null;\r
689                         }\r
690                         break;\r
691                      case VertexType.IMN:\r
692                         e0.outp_ABOVE = out_poly.add_local_min(ix, iy);\r
693                         e1.outp_ABOVE = e0.outp_ABOVE;\r
694                         break;\r
695                      case VertexType.ILI:\r
696                         if (p != null) {\r
697                            p.add_left(ix, iy);\r
698                            e1.outp_ABOVE= p;\r
699                            e0.outp_ABOVE= null;\r
700                         }\r
701                         break;\r
702                      case VertexType.IRI:\r
703                         if (q!=null) {\r
704                            q.add_right(ix, iy);\r
705                            e0.outp_ABOVE= q;\r
706                            e1.outp_ABOVE= null;\r
707                         }\r
708                         break;\r
709                      case VertexType.IMX:\r
710                         if ((p!=null) && (q!=null)) {\r
711                             p.add_right(ix, iy);\r
712                             out_poly.merge_left(p, q);\r
713                             e0.outp_ABOVE= null;\r
714                             e1.outp_ABOVE= null;\r
715                         }\r
716                         break;\r
717                      case VertexType.IMM:\r
718                         if ((p!=null) && (q!=null)) {\r
719                             p.add_right(ix, iy);\r
720                             out_poly.merge_left(p, q);\r
721                             e0.outp_ABOVE = out_poly.add_local_min(ix, iy);\r
722                             e1.outp_ABOVE= e0.outp_ABOVE;\r
723                         }\r
724                         break;\r
725                      case VertexType.EMM:\r
726                         if ((p!=null) && (q!=null)) {\r
727                             p.add_left(ix, iy);\r
728                             out_poly.merge_right(p, q);\r
729                             e0.outp_ABOVE = out_poly.add_local_min(ix, iy);\r
730                             e1.outp_ABOVE = e0.outp_ABOVE;\r
731                         }\r
732                         break;\r
733                      default: break;\r
734                   } // End of switch \r
735                } // End of contributing intersection conditional \r
736                   \r
737                // Swap bundle sides in response to edge crossing \r
738                if (e0.bundle_ABOVE_CLIP!=0) e1.bside_CLIP = (e1.bside_CLIP==0)?1:0;\r
739                if (e1.bundle_ABOVE_CLIP!=0) e0.bside_CLIP= (e0.bside_CLIP==0)?1:0;\r
740                if (e0.bundle_ABOVE_SUBJ!=0) e1.bside_SUBJ= (e1.bside_SUBJ==0)?1:0;\r
741                if (e1.bundle_ABOVE_SUBJ!=0) e0.bside_SUBJ= (e0.bside_SUBJ==0)?1:0;\r
742 \r
743                // Swap e0 and e1 bundles in the AET \r
744                EdgeNode prev_edge = e0.prev;\r
745                EdgeNode next_edge = e1.next;\r
746                if (next_edge != null) next_edge.prev = e0;\r
747    \r
748                if (e0.bstate_ABOVE == BUNDLE_HEAD) {\r
749                   boolean search = true;\r
750                   while (search) {\r
751                       prev_edge= prev_edge.prev;\r
752                       if (prev_edge != null) {\r
753                           if (prev_edge.bstate_ABOVE != BUNDLE_TAIL)\r
754                               search= false;\r
755                       } else {\r
756                           search= false;\r
757                       }\r
758                   }\r
759                }\r
760                if (prev_edge == null) {\r
761                   aet.top_node.prev = e1;\r
762                   e1.next           = aet.top_node;\r
763                   aet.top_node      = e0.next;\r
764                } else {\r
765                    prev_edge.next.prev = e1;\r
766                    e1.next             = prev_edge.next;\r
767                    prev_edge.next      = e0.next;\r
768                }\r
769                e0.next.prev = prev_edge;\r
770                e1.next.prev = e1;\r
771                e0.next      = next_edge;\r
772             } // End of IT loop\r
773                \r
774             // Prepare for next scanbeam \r
775             for (EdgeNode edge = aet.top_node; (edge != null); edge = edge.next) {\r
776                EdgeNode next_edge = edge.next;\r
777                EdgeNode succ_edge = edge.succ;\r
778                if ((edge.top_y == yt) && (succ_edge!=null)) {\r
779                   // Replace AET edge by its successor \r
780                   succ_edge.outp_BELOW= edge.outp_ABOVE;\r
781                   succ_edge.bstate_BELOW= edge.bstate_ABOVE;\r
782                   succ_edge.bundle_BELOW_CLIP= edge.bundle_ABOVE_CLIP;\r
783                   succ_edge.bundle_BELOW_SUBJ= edge.bundle_ABOVE_SUBJ;\r
784                   EdgeNode prev_edge = edge.prev;\r
785                   if (prev_edge != null) prev_edge.next = succ_edge;\r
786                   else aet.top_node = succ_edge;\r
787                   if (next_edge != null) next_edge.prev= succ_edge;\r
788                   succ_edge.prev = prev_edge;\r
789                   succ_edge.next = next_edge;\r
790                } else {\r
791                    // Update this edge \r
792                    edge.outp_BELOW= edge.outp_ABOVE;\r
793                    edge.bstate_BELOW= edge.bstate_ABOVE;\r
794                    edge.bundle_BELOW_CLIP= edge.bundle_ABOVE_CLIP;\r
795                    edge.bundle_BELOW_SUBJ= edge.bundle_ABOVE_SUBJ;\r
796                    edge.xb= edge.xt;\r
797                }\r
798                edge.outp_ABOVE= null;\r
799             }\r
800          }\r
801       } // === END OF SCANBEAM PROCESSING ================================== \r
802 \r
803       // Generate result polygon from out_poly \r
804       subj.clear();\r
805       return out_poly.getResult(subj);\r
806    }\r
807    \r
808     private static boolean EQ(float a, float b) { return (Math.abs(a - b) <= GPC_EPSILON); }\r
809     private static int PREV_INDEX(int i, int n) { return ((i - 1 + n) % n); }\r
810     private static int NEXT_INDEX(int i, int n) { return ((i + 1   ) % n); }\r
811     private static boolean OPTIMAL(Polygon p, int index, int i) {\r
812         return (p.y[p.contours[index] + PREV_INDEX(i, p.contours[index+1]-p.contours[index])] != p.y[p.contours[index] + i]) ||\r
813             (p.y[p.contours[index] + NEXT_INDEX(i, p.contours[index+1]-p.contours[index])] != p.y[p.contours[index] + i]);\r
814     }\r
815    \r
816    private static void minimax_test(Polygon subj, Polygon clip, byte op) {\r
817       // For each clip contour, search for any subject contour overlaps \r
818       for(int c=0; c < clip.numcontours; c++) {\r
819          boolean overlap = false;\r
820          for(int s = 0; !overlap && (s < subj.numcontours); s++)\r
821              overlap = (!((subj.maxx_[s] < clip.minx_[c]) || (subj.minx_[s] > clip.maxx_[c]))) &&\r
822                  (!((subj.maxy_[s] < clip.miny_[c]) || (subj.miny_[s] > clip.maxy_[c])));\r
823          clip.contributing[c] = overlap;\r
824       }  \r
825       if (op != GPC_INT) return;\r
826       // For each subject contour, search for any clip contour overlaps \r
827       for (int s=0; s < subj.numcontours; s++) {\r
828           boolean overlap = false;\r
829           for (int c=0; !overlap && (c < clip.numcontours); c++)\r
830               overlap = (!((subj.maxx_[s] < clip.minx_[c]) || (subj.minx_[s] > clip.maxx_[c]))) &&\r
831                   (!((subj.maxy_[s] < clip.miny_[c]) || (subj.miny_[s] > clip.maxy_[c])));\r
832           subj.contributing[s] = overlap;\r
833       }\r
834    }\r
835 \r
836    private static void insert_bound(LmtTable lmt_table, float y, EdgeNode e) {\r
837       int index = lmt_table.add(y, null);\r
838       // Link node e to the tail of the list \r
839       if (lmt_table.first_bound[index] == null) { lmt_table.first_bound[index] = e; return; }\r
840       EdgeNode prev_bound = null;\r
841       EdgeNode current_bound = lmt_table.first_bound[index];\r
842       while(true)\r
843           // Do primary sort on the x field \r
844           if (e.bot_x <  current_bound.bot_x) {\r
845               // Insert a new node mid-list \r
846               if (prev_bound == null) lmt_table.first_bound[index] = e;\r
847               else prev_bound.next_bound = e;\r
848               e.next_bound = current_bound;\r
849               break;\r
850           } else if (e.bot_x == current_bound.bot_x) {\r
851               // Do secondary sort on the dx field \r
852               if (e.dx < current_bound.dx) {\r
853                   // Insert a new node mid-list \r
854                   if (prev_bound == null) lmt_table.first_bound[index] = e;\r
855                   else prev_bound.next_bound = e;\r
856                   e.next_bound = current_bound;\r
857                   break;\r
858               }\r
859               // Head further down the list \r
860               if (current_bound.next_bound == null) { current_bound.next_bound = e; break; }\r
861               prev_bound = current_bound;\r
862               current_bound = current_bound.next_bound;\r
863           } else {\r
864               // Head further down the list \r
865               if (current_bound.next_bound == null) { current_bound.next_bound = e; break; }\r
866               prev_bound = current_bound;\r
867               current_bound = current_bound.next_bound;\r
868           }\r
869    }\r
870    \r
871    private static void add_edge_to_aet(AetTree aet, EdgeNode edge) {\r
872       if (aet.top_node == null) {\r
873          // Append edge onto the tail end of the AET \r
874          aet.top_node = edge;\r
875          edge.prev = null;\r
876          edge.next= null;\r
877          return;\r
878       }\r
879       EdgeNode current_edge = aet.top_node;\r
880       EdgeNode prev = null;\r
881       while(true)\r
882           // Do primary sort on the xb field \r
883           if (edge.xb < current_edge.xb) {\r
884               // Insert edge here (before the AET edge) \r
885               edge.prev= prev;\r
886               edge.next= current_edge;\r
887               current_edge.prev = edge;\r
888               if (prev == null) aet.top_node = edge;\r
889               else prev.next = edge;\r
890               break;\r
891           } else if (edge.xb == current_edge.xb) {\r
892               // Do secondary sort on the dx field \r
893               if (edge.dx < current_edge.dx) {\r
894                   // Insert edge here (before the AET edge) \r
895                   edge.prev= prev;\r
896                   edge.next= current_edge;\r
897                   current_edge.prev = edge;\r
898                   if (prev == null) aet.top_node = edge;\r
899                   else prev.next = edge;\r
900                   break;\r
901                }\r
902               // Head further into the AET \r
903               prev = current_edge;\r
904               if (current_edge.next == null) {\r
905                   current_edge.next = edge;\r
906                   edge.prev = current_edge;\r
907                   edge.next = null;\r
908                   break;\r
909               }\r
910               current_edge = current_edge.next;\r
911           } else {\r
912               // Head further into the AET \r
913               prev = current_edge;\r
914               if (current_edge.next == null) {\r
915                   current_edge.next = edge;\r
916                   edge.prev = current_edge;\r
917                   edge.next = null;\r
918                   break;\r
919                }\r
920               current_edge = current_edge.next;\r
921           }\r
922    }\r
923 \r
924    private static void build_lmt(EdgeTable edge_table, LmtTable lmt_table, ScanBeamList sbte, Polygon p, int type, byte op) {\r
925       for (int c=0; c < p.numcontours; c++) {\r
926           if (!p.contributing[c]) { p.contributing[c] = true; continue; }\r
927           // Perform contour optimisation \r
928           int num_vertices= 0;\r
929           int e_index = 0;\r
930           edge_table.clear();\r
931           for (int i= 0; i < p.contours[c+1] - p.contours[c]; i++)\r
932               if (OPTIMAL(p, c, i)) {\r
933                  edge_table.addNode(p.x[p.contours[c]+i], p.y[p.contours[c]+i]);\r
934                  sbte.add(p.y[p.contours[c]+i]);  // Record vertex in the scanbeam table \r
935                  num_vertices++;\r
936               }\r
937            \r
938          // Do the contour forward pass \r
939          for (int min= 0; min < num_vertices; min++) {\r
940              // If a forward local minimum... \r
941              if (edge_table.FWD_MIN(min)) {\r
942                  // Search for the next local maximum... \r
943                  int num_edges = 1;\r
944                  int max = NEXT_INDEX(min, num_vertices);\r
945                  while(edge_table.NOT_FMAX(max)) { num_edges++; max = NEXT_INDEX(max, num_vertices); }\r
946 \r
947                  // Build the next edge list \r
948                  int v = min;\r
949                  EdgeNode e = edge_table.getNode(e_index);\r
950                  e.bstate_BELOW = UNBUNDLED;\r
951                  e.bundle_BELOW_CLIP = 0;\r
952                  e.bundle_BELOW_SUBJ = 0;\r
953                   \r
954                  for (int i= 0; i < num_edges; i++) {\r
955                      EdgeNode ei = edge_table.getNode(e_index+i);\r
956                      EdgeNode ev = edge_table.getNode(v);\r
957                      ei.xb    = ev.vertex_x;\r
958                      ei.bot_x = ev.vertex_x;\r
959                      ei.bot_y = ev.vertex_y;\r
960                      v = NEXT_INDEX(v, num_vertices);\r
961                      ev = edge_table.getNode(v);\r
962                      ei.top_x= ev.vertex_x;\r
963                      ei.top_y= ev.vertex_y;\r
964                      ei.dx= (ev.vertex_x - ei.bot_x) / (ei.top_y - ei.bot_y);\r
965                      ei.type = type;\r
966                      ei.outp_ABOVE = null;\r
967                      ei.outp_BELOW = null;\r
968                      ei.next = null;\r
969                      ei.prev = null;\r
970                      ei.succ = ((num_edges > 1) && (i < (num_edges - 1))) ? edge_table.getNode(e_index+i+1) : null;\r
971                      ei.pred = ((num_edges > 1) && (i > 0)) ? edge_table.getNode(e_index+i-1) : null;\r
972                      ei.next_bound = null;\r
973                      ei.bside_CLIP = (op == GPC_DIFF) ? RIGHT : LEFT;\r
974                      ei.bside_SUBJ = LEFT;\r
975                  }\r
976                  insert_bound(lmt_table, edge_table.getNode(min).vertex_y, e);\r
977                  e_index += num_edges;\r
978              }\r
979          }\r
980 \r
981          // Do the contour reverse pass \r
982          for (int min= 0; min < num_vertices; min++) {\r
983              // If a reverse local minimum... \r
984              if (edge_table.REV_MIN(min)) {\r
985                  // Search for the previous local maximum... \r
986                  int num_edges= 1;\r
987                  int max = PREV_INDEX(min, num_vertices);\r
988                  while(edge_table.NOT_RMAX(max)) { num_edges++; max = PREV_INDEX(max, num_vertices); }\r
989                  // Build the previous edge list \r
990                  int v = min;\r
991                  EdgeNode e = edge_table.getNode(e_index);\r
992                  e.bstate_BELOW = UNBUNDLED;\r
993                  e.bundle_BELOW_CLIP = 0;\r
994                  e.bundle_BELOW_SUBJ = 0;\r
995                  for (int i= 0; i < num_edges; i++) {\r
996                      EdgeNode ei = edge_table.getNode(e_index+i);\r
997                      EdgeNode ev = edge_table.getNode(v);\r
998                      ei.xb    = ev.vertex_x;\r
999                      ei.bot_x = ev.vertex_x;\r
1000                      ei.bot_y = ev.vertex_y;\r
1001                      v= PREV_INDEX(v, num_vertices);\r
1002                      ev = edge_table.getNode(v);\r
1003                      ei.top_x = ev.vertex_x;\r
1004                      ei.top_y = ev.vertex_y;\r
1005                      ei.dx = (ev.vertex_x - ei.bot_x) / (ei.top_y - ei.bot_y);\r
1006                      ei.type = type;\r
1007                      ei.outp_ABOVE = null;\r
1008                      ei.outp_BELOW = null;\r
1009                      ei.next = null;\r
1010                      ei.prev = null;\r
1011                      ei.succ = ((num_edges > 1) && (i < (num_edges - 1))) ? edge_table.getNode(e_index+i+1) : null;\r
1012                      ei.pred = ((num_edges > 1) && (i > 0)) ? edge_table.getNode(e_index+i-1) : null;\r
1013                      ei.next_bound = null;\r
1014                      ei.bside_CLIP = (op == GPC_DIFF) ? RIGHT : LEFT;\r
1015                      ei.bside_SUBJ = LEFT;\r
1016                  }\r
1017                  insert_bound(lmt_table, edge_table.getNode(min).vertex_y, e);\r
1018                  e_index+= num_edges;\r
1019              }\r
1020          }\r
1021       }\r
1022    }\r
1023 \r
1024     public static final byte GPC_DIFF  = 0;\r
1025     public static final byte GPC_INT   = 1;\r
1026     public static final byte GPC_XOR   = 2;\r
1027     public static final byte GPC_UNION = 3;\r
1028 \r
1029     // Edge intersection classes\r
1030    private static class VertexType {\r
1031       public static final int NUL =  0; // Empty non-intersection            \r
1032       public static final int EMX =  1; // External maximum                  \r
1033       public static final int ELI =  2; // External left intermediate        \r
1034       public static final int TED =  3; // Top edge                          \r
1035       public static final int ERI =  4; // External right intermediate       \r
1036       public static final int RED =  5; // Right edge                        \r
1037       public static final int IMM =  6; // Internal maximum and minimum      \r
1038       public static final int IMN =  7; // Internal minimum                  \r
1039       public static final int EMN =  8; // External minimum                  \r
1040       public static final int EMM =  9; // External maximum and minimum      \r
1041       public static final int LED = 10; // Left edge                         \r
1042       public static final int ILI = 11; // Internal left intermediate        \r
1043       public static final int BED = 12; // Bottom edge                       \r
1044       public static final int IRI = 13; // Internal right intermediate       \r
1045       public static final int IMX = 14; // Internal maximum                  \r
1046       public static final int FUL = 15; // Full non-intersection             \r
1047       public static int getType(int tr, int tl, int br, int bl) { return tr + (tl << 1) + (br << 2) + (bl << 3); }\r
1048    }\r
1049    \r
1050    private static class HState {\r
1051       public static final int NH = 0; // No horizontal edge                \r
1052       public static final int BH = 1; // Bottom horizontal edge            \r
1053       public static final int TH = 2; // Top horizontal edge               \r
1054       // Horizontal edge state transitions within scanbeam boundary \r
1055       public static final int[][] next_h_state =\r
1056       {\r
1057       //        ABOVE     BELOW     CROSS \r
1058       //        L   R     L   R     L   R \r
1059       /* NH */ {BH, TH,   TH, BH,   NH, NH},\r
1060       /* BH */ {NH, NH,   NH, NH,   TH, TH},\r
1061       /* TH */ {NH, NH,   NH, NH,   BH, BH}\r
1062       };\r
1063    }\r
1064    \r
1065     public static final byte UNBUNDLED   = 0; // Isolated edge not within a bundle\r
1066     public static final byte BUNDLE_HEAD = 1; // Bundle head node\r
1067     public static final byte BUNDLE_TAIL = 2; // Passive bundle tail node\r
1068 \r
1069     private static class PolygonNode {\r
1070         public static void clear() { numvertices = 1; }\r
1071         private static final float[] x  = new float[BIGNUM];\r
1072         private static final float[] y  = new float[BIGNUM];\r
1073         private static final int[] nxt  = new int[BIGNUM];\r
1074         private static int numvertices = 1;\r
1075 \r
1076         int          active = 1;             // Active flag / vertex count        \r
1077         boolean      hole;                   // Hole / external contour flag      \r
1078         int          v_LEFT;                 // Left and right vertex list ptrs   \r
1079         int          v_RIGHT;                // Left and right vertex list ptrs   \r
1080         PolygonNode  next;                   // Pointer to next polygon contour   \r
1081         PolygonNode  proxy;                  // Pointer to actual structure used  \r
1082        \r
1083        public PolygonNode(PolygonNode next, float x0, float y0) {\r
1084            // Make v_LEFT and v_RIGHT point to new vertex \r
1085            x[numvertices] = x0; y[numvertices] = y0; nxt[numvertices] = 0;\r
1086            this.v_LEFT = numvertices;\r
1087            this.v_RIGHT = numvertices;\r
1088            numvertices++;\r
1089            this.proxy = this; // Initialise proxy to point to p itself \r
1090            this.next = next;\r
1091        }\r
1092        public void merge(PolygonNode q) { nxt[proxy.v_RIGHT] = q.proxy.v_LEFT; q.proxy.v_LEFT = proxy.v_LEFT; }\r
1093        public void mergeRight(PolygonNode p) { nxt[proxy.v_RIGHT] = p.proxy.v_LEFT; proxy.v_RIGHT = p.proxy.v_RIGHT; }\r
1094        public void addSelfTo(Polygon poly) {\r
1095            for (int vtx = v_LEFT; vtx != 0; vtx = nxt[vtx]) poly.add(x[vtx], y[vtx]);\r
1096            poly.newcontour();\r
1097        }\r
1098        public int count() { int ret = 0; for (int vtx = v_LEFT; vtx != 0; vtx = nxt[vtx]) ret++; return ret; }\r
1099        public void add_right(float x0, float y0) {\r
1100            x[numvertices] = x0; y[numvertices] = y0; nxt[numvertices] = 0;\r
1101            nxt[proxy.v_RIGHT] = numvertices;\r
1102            proxy.v_RIGHT = numvertices;\r
1103            numvertices++;\r
1104        }\r
1105        public void add_left(float x0, float y0) {\r
1106            x[numvertices] = x0; y[numvertices] = y0; nxt[numvertices] = 0;\r
1107            nxt[numvertices] = proxy.v_LEFT;\r
1108            proxy.v_LEFT = numvertices;\r
1109            numvertices++;\r
1110        }\r
1111    }\r
1112 \r
1113    private static class TopPolygonNode {\r
1114        PolygonNode top_node = null;\r
1115        public void clear() { top_node = null; }\r
1116        public PolygonNode add_local_min(float x, float y) {\r
1117            PolygonNode existing_min = top_node;\r
1118            top_node = new PolygonNode(existing_min, x, y);\r
1119            return top_node;\r
1120        }\r
1121        public void merge_left(PolygonNode p, PolygonNode q) {\r
1122          // Label contour as a hole \r
1123          q.proxy.hole = true;\r
1124          if (p.proxy == q.proxy) return;\r
1125          // Assign p's vertex list to the left end of q's list \r
1126          p.merge(q);\r
1127          // Redirect any p.proxy references to q.proxy \r
1128          PolygonNode target = p.proxy;\r
1129          for(PolygonNode node = top_node; (node != null); node = node.next)\r
1130              if (node.proxy == target) { node.active= 0; node.proxy= q.proxy; }\r
1131       }\r
1132 \r
1133       public void merge_right(PolygonNode p, PolygonNode q) {\r
1134          // Label contour as external \r
1135          q.proxy.hole = false;\r
1136          if (p.proxy == q.proxy) return;\r
1137          // Assign p's vertex list to the right end of q's list \r
1138          q.mergeRight(p);\r
1139          // Redirect any p->proxy references to q->proxy \r
1140          PolygonNode target = p.proxy;\r
1141          for (PolygonNode node = top_node; (node != null); node = node.next)\r
1142              if (node.proxy == target) { node.active = 0; node.proxy= q.proxy; }\r
1143       }\r
1144       \r
1145       public int count_contours() {\r
1146          int nc = 0;\r
1147          for (PolygonNode polygon = top_node; (polygon != null); polygon = polygon.next)\r
1148             if (polygon.active != 0) {\r
1149                // Count the vertices in the current contour \r
1150                int nv= polygon.proxy.count();\r
1151                // Record valid vertex counts in the active field \r
1152                if (nv > 2) { polygon.active = nv; nc++; }\r
1153                else polygon.active= 0;\r
1154             }\r
1155          return nc;\r
1156       }\r
1157       \r
1158       public Polygon getResult(Polygon result) {\r
1159          int num_contours = count_contours();\r
1160          if (num_contours <= 0) return result;\r
1161          int c= 0;\r
1162          PolygonNode npoly_node = null;\r
1163          for (PolygonNode poly_node = top_node; (poly_node != null); poly_node = npoly_node) {\r
1164              npoly_node = poly_node.next;\r
1165              if (poly_node.active == 0) continue;\r
1166              int prepoly = result.numcontours;\r
1167              // This algorithm puts the verticies into the poly in reverse order\r
1168              poly_node.proxy.addSelfTo(result);\r
1169              if (poly_node.proxy.hole) {\r
1170                  for(int i=prepoly; i<result.numcontours; i++)\r
1171                      result.hole[i] = poly_node.proxy.hole;\r
1172              }\r
1173              c++;\r
1174          }\r
1175          return result;\r
1176       }\r
1177    }\r
1178    \r
1179     private static EdgeNode[] allEdgeNodes = new EdgeNode[BIGNUM];\r
1180     private static int numEdgeNodes = 0;\r
1181     private static int numFreeEdgeNodes = 0;\r
1182     private static EdgeNode newEdgeNode(float x, float y) {\r
1183         if (numFreeEdgeNodes == 0) {\r
1184             return allEdgeNodes[numEdgeNodes++] = new EdgeNode(x, y);\r
1185         } else {\r
1186             EdgeNode ret = allEdgeNodes[--numFreeEdgeNodes];\r
1187             ret.vertex_x = x;\r
1188             ret.vertex_y = y;\r
1189             return ret;\r
1190         }\r
1191     }\r
1192    private static class EdgeNode {\r
1193        float vertex_x;\r
1194        float vertex_y;\r
1195        float top_x;\r
1196        float top_y;\r
1197        float bot_x;\r
1198        float bot_y;\r
1199        float         xb;           // Scanbeam bottom x coordinate      \r
1200        float         xt;           // Scanbeam top x coordinate         \r
1201        float         dx;           // Change in x for a unit y increase \r
1202        int           type;         // Clip / subject edge flag          \r
1203        int bundle_ABOVE_CLIP;\r
1204        int bundle_ABOVE_SUBJ;\r
1205        int bundle_BELOW_CLIP;\r
1206        int bundle_BELOW_SUBJ;\r
1207        int bside_CLIP;\r
1208        int bside_SUBJ;\r
1209        byte bstate_ABOVE;\r
1210        byte bstate_BELOW;\r
1211        PolygonNode  outp_ABOVE; // Output polygon / tristrip pointer \r
1212        PolygonNode  outp_BELOW; // Output polygon / tristrip pointer \r
1213        EdgeNode       prev;         // Previous edge in the AET          \r
1214        EdgeNode       next;         // Next edge in the AET              \r
1215        EdgeNode       pred;         // Edge connected at the lower end   \r
1216        EdgeNode       succ;         // Edge connected at the upper end   \r
1217        EdgeNode       next_bound;   // Pointer to next bound in LMT      \r
1218        public EdgeNode(float x, float y) { vertex_x = x; vertex_y = y; }\r
1219    }\r
1220    private static class AetTree { EdgeNode top_node; public void clear() { top_node = null; } }\r
1221 \r
1222    private static class EdgeTable {\r
1223        public EdgeNode[] edges = new EdgeNode[BIGNUM];\r
1224        public int entries;\r
1225        public void clear() { for(; entries >= 0; entries--) edges[entries] = null; entries = 0; }\r
1226        public void addNode(float x, float y) { edges[entries++] = newEdgeNode(x, y); }\r
1227        public EdgeNode getNode(int index) { return edges[index]; }\r
1228        public boolean NOT_RMAX(int i) { return (edges[PREV_INDEX(i, entries)].vertex_y > edges[i].vertex_y); }\r
1229        public boolean NOT_FMAX(int i) { return(edges[NEXT_INDEX(i, entries)].vertex_y > edges[i].vertex_y); }\r
1230        public boolean FWD_MIN(int i) {\r
1231            return ((edges[PREV_INDEX(i, entries)].vertex_y >= edges[i].vertex_y) &&\r
1232                    (edges[NEXT_INDEX(i, entries)].vertex_y >  edges[i].vertex_y));\r
1233        }\r
1234        public boolean REV_MIN(int i) {\r
1235            return ((edges[PREV_INDEX(i, entries)].vertex_y >  edges[i].vertex_y) &&\r
1236                    (edges[NEXT_INDEX(i, entries)].vertex_y >= edges[i].vertex_y));\r
1237        }\r
1238    }\r
1239 \r
1240    private static class LmtTable {\r
1241        float[] y = new float[BIGNUM];\r
1242        EdgeNode[] first_bound = new EdgeNode[BIGNUM];\r
1243        int numentries = 0;\r
1244        public void clear() { for(; numentries >= 0; numentries--) first_bound[numentries] = null; numentries = 0; }\r
1245        public int count() { return numentries; }\r
1246        public boolean isEmpty() { return numentries == 0; }\r
1247        public int add(float y0, EdgeNode e) {\r
1248            for(int i=0; i<numentries; i++)\r
1249                if (y[i] == y0) return i;\r
1250                else if (y[i] > y0) {\r
1251                    System.arraycopy(y, i, y, i+1, numentries-i);\r
1252                    System.arraycopy(first_bound, i, first_bound, i+1, numentries-i);\r
1253                    y[i] = y0;\r
1254                    first_bound[i] = e;\r
1255                    numentries++;\r
1256                    return i;\r
1257                }\r
1258            y[numentries] = y0;\r
1259            first_bound[numentries] = e;\r
1260            return numentries++;\r
1261        }\r
1262    }\r
1263 \r
1264    private static class ScanBeamList {\r
1265        public int entries = 0;\r
1266        public float[] floats = new float[BIGNUM];\r
1267        public void clear() { entries = 0; }\r
1268        public void add(float f) { floats[entries++] = f; }\r
1269        public float[] sort() {\r
1270            org.ibex.util.Vec.sortFloats(floats, 0, entries-1);\r
1271            int j = 0;\r
1272            for(int i=1; i<entries; i++) if (floats[j] != floats[i]) floats[++j] = floats[i];\r
1273            entries = j+1;\r
1274            return floats;\r
1275        }\r
1276    }\r
1277    \r
1278    private static class ItNodeTable {\r
1279        EdgeNode ie_0[] = new EdgeNode[BIGNUM];\r
1280        EdgeNode ie_1[] = new EdgeNode[BIGNUM];\r
1281        float x[] = new float[BIGNUM];\r
1282        float y[] = new float[BIGNUM];\r
1283        int num = 0;\r
1284        public void clear() { for(; num>=0; num--) { ie_0[num] = null; ie_1[num] = null; } num = 0; }\r
1285        public void build_intersection_table(AetTree aet, float dy) {\r
1286            int st = -1;\r
1287            // Process each AET edge \r
1288            for (EdgeNode edge = aet.top_node; (edge != null); edge = edge.next)\r
1289                if ((edge.bstate_ABOVE == BUNDLE_HEAD) ||\r
1290                    (edge.bundle_ABOVE_CLIP != 0) || (edge.bundle_ABOVE_SUBJ != 0))\r
1291                    st = add_st_edge(st, edge, dy);\r
1292            sort(0, num-1);\r
1293            for(;numst>=0; numst--) edge[numst] = null; numst = 0;\r
1294        }\r
1295        \r
1296        int numst = 0;\r
1297        EdgeNode edge[] = new EdgeNode[BIGNUM];    // Pointer to AET edge               \r
1298        float    xb[] = new float[BIGNUM];         // Scanbeam bottom x coordinate      \r
1299        float    xt[] = new float[BIGNUM];         // Scanbeam top x coordinate         \r
1300        float    dx[] = new float[BIGNUM];         // Change in x for a unit y increase \r
1301        int      prev[] = new int[BIGNUM];           // Previous edge in sorted list      \r
1302 \r
1303        private int add_st_edge(int st, EdgeNode e, float dy) {\r
1304            if (st == -1) { st = numst++; edge[st] = e; xb[st] = e.xb; xt[st] = e.xt; dx[st] = e.dx; prev[st] = -1; return st; }\r
1305            float den = (xt[st] - xb[st]) - (e.xt - e.xb);\r
1306 \r
1307            // If new edge and ST edge don't cross, No intersection - insert edge here (before the ST edge) \r
1308            if ((e.xt >= xt[st]) || (e.dx == dx[st]) || (Math.abs(den) <= GPC_EPSILON))\r
1309                { prev[numst] = st; st = numst++; edge[st] = e; xb[st] = e.xb; xt[st] = e.xt; dx[st] = e.dx; return st; }\r
1310 \r
1311            // Compute intersection between new edge and ST edge \r
1312            float r = (e.xb - xb[st]) / den;\r
1313            float x = xb[st] + r * (xt[st] - xb[st]);\r
1314            float y = r * dy;\r
1315            // Insert the edge pointers and the intersection point in the IT \r
1316            add_intersection(edge[st], e, x, y);\r
1317            prev[st] = add_st_edge(prev[st], e, dy);\r
1318            return st;\r
1319        }\r
1320        private void add_intersection(EdgeNode edge0, EdgeNode edge1, float x0, float y0) {\r
1321            ie_0[num] = edge0; ie_1[num] = edge1; x[num] = x0; y[num] = y0; num++; }\r
1322 \r
1323        public final void sort(int start, int end) {\r
1324            if(start >= end) return;\r
1325            if(end-start <= 6) {\r
1326                for(int i=start+1;i<=end;i++) {\r
1327                    float tmpa = y[i];\r
1328                    float tmpx = x[i];\r
1329                    EdgeNode tmpe0 = ie_0[i];\r
1330                    EdgeNode tmpe1 = ie_1[i];\r
1331                    int j;\r
1332                    for(j=i-1;j>=start;j--) {\r
1333                        if(y[j] <= tmpa) break;\r
1334                        y[j+1] = y[j];\r
1335                        x[j+1] = x[j];\r
1336                        ie_0[j+1] = ie_0[j];\r
1337                        ie_1[j+1] = ie_1[j];\r
1338                    }\r
1339                    y[j+1] = tmpa;\r
1340                    x[j+1] = tmpx;\r
1341                    ie_0[j+1] = tmpe0;\r
1342                    ie_1[j+1] = tmpe1;\r
1343                }\r
1344                return;\r
1345            }\r
1346            float pivot = y[end];\r
1347            int lo = start - 1;\r
1348            int hi = end;\r
1349            do {\r
1350                while(y[++lo] < pivot) { }\r
1351                while((hi > lo) && y[--hi] > pivot) { }\r
1352                swap(lo, hi);\r
1353            } while(lo < hi);\r
1354            swap(lo, end);\r
1355            sort(start, lo-1);\r
1356            sort(lo+1, end);\r
1357        }\r
1358        private final void swap(int a, int b) {\r
1359            if(a != b) {\r
1360                float tmp = x[a]; x[a] = x[b]; x[b] = tmp;\r
1361                tmp = y[a]; y[a] = y[b]; y[b] = tmp;\r
1362                EdgeNode tmpe = ie_0[a]; ie_0[a] = ie_0[b]; ie_0[b] = tmpe;\r
1363                tmpe = ie_1[a]; ie_1[a] = ie_1[b]; ie_1[b] = tmpe;\r
1364            }\r
1365        }\r
1366    }\r
1367 \r
1368 }\r