1 /*
2 ** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3 ** Copyright (C) [dates of first publication] Silicon Graphics, Inc.
4 ** All Rights Reserved.
5 **
6 ** Permission is hereby granted, free of charge, to any person obtaining a copy
7 ** of this software and associated documentation files (the "Software"), to deal
8 ** in the Software without restriction, including without limitation the rights
9 ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 ** of the Software, and to permit persons to whom the Software is furnished to do so,
11 ** subject to the following conditions:
12 **
13 ** The above copyright notice including the dates of first publication and either this
14 ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be
15 ** included in all copies or substantial portions of the Software.
16 **
17 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18 ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
19 ** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL SILICON GRAPHICS, INC.
20 ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
22 ** OR OTHER DEALINGS IN THE SOFTWARE.
23 **
24 ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not
25 ** be used in advertising or otherwise to promote the sale, use or other dealings in
26 ** this Software without prior written authorization from Silicon Graphics, Inc.
27 */
28 /*
29 ** Author: Eric Veach, July 1994.
30 */
31 
32 #include <assert.h>
33 #include <stddef.h>
34 #include <setjmp.h>		/* longjmp */
35 
36 #include "mesh.h"
37 #include "geom.h"
38 #include "tess.h"
39 #include "dict.h"
40 #include "priorityq.h"
41 #include "bucketalloc.h"
42 #include "sweep.h"
43 
44 #define TRUE 1
45 #define FALSE 0
46 
47 #ifdef FOR_TRITE_TEST_PROGRAM
48 extern void DebugEvent( TESStesselator *tess );
49 #else
50 #define DebugEvent( tess )
51 #endif
52 
53 /*
54 * Invariants for the Edge Dictionary.
55 * - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2)
56 *   at any valid location of the sweep event
57 * - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2
58 *   share a common endpoint
59 * - for each e, e->Dst has been processed, but not e->Org
60 * - each edge e satisfies VertLeq(e->Dst,event) && VertLeq(event,e->Org)
61 *   where "event" is the current sweep line event.
62 * - no edge e has zero length
63 *
64 * Invariants for the Mesh (the processed portion).
65 * - the portion of the mesh left of the sweep line is a planar graph,
66 *   ie. there is *some* way to embed it in the plane
67 * - no processed edge has zero length
68 * - no two processed vertices have identical coordinates
69 * - each "inside" region is monotone, ie. can be broken into two chains
70 *   of monotonically increasing vertices according to VertLeq(v1,v2)
71 *   - a non-invariant: these chains may intersect (very slightly)
72 *
73 * Invariants for the Sweep.
74 * - if none of the edges incident to the event vertex have an activeRegion
75 *   (ie. none of these edges are in the edge dictionary), then the vertex
76 *   has only right-going edges.
77 * - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced
78 *   by ConnectRightVertex), then it is the only right-going edge from
79 *   its associated vertex.  (This says that these edges exist only
80 *   when it is necessary.)
81 */
82 
83 #define MAX(x,y)	((x) >= (y) ? (x) : (y))
84 #define MIN(x,y)	((x) <= (y) ? (x) : (y))
85 
86 /* When we merge two edges into one, we need to compute the combined
87 * winding of the new edge.
88 */
89 #define AddWinding(eDst,eSrc)	(eDst->winding += eSrc->winding, \
90 	eDst->Sym->winding += eSrc->Sym->winding)
91 
92 static void SweepEvent( TESStesselator *tess, TESSvertex *vEvent );
93 static void WalkDirtyRegions( TESStesselator *tess, ActiveRegion *regUp );
94 static int CheckForRightSplice( TESStesselator *tess, ActiveRegion *regUp );
95 
EdgeLeq(TESStesselator * tess,ActiveRegion * reg1,ActiveRegion * reg2)96 static int EdgeLeq( TESStesselator *tess, ActiveRegion *reg1, ActiveRegion *reg2 )
97 /*
98 * Both edges must be directed from right to left (this is the canonical
99 * direction for the upper edge of each region).
100 *
101 * The strategy is to evaluate a "t" value for each edge at the
102 * current sweep line position, given by tess->event.  The calculations
103 * are designed to be very stable, but of course they are not perfect.
104 *
105 * Special case: if both edge destinations are at the sweep event,
106 * we sort the edges by slope (they would otherwise compare equally).
107 */
108 {
109 	TESSvertex *event = tess->event;
110 	TESShalfEdge *e1, *e2;
111 	TESSreal t1, t2;
112 
113 	e1 = reg1->eUp;
114 	e2 = reg2->eUp;
115 
116 	if( e1->Dst == event ) {
117 		if( e2->Dst == event ) {
118 			/* Two edges right of the sweep line which meet at the sweep event.
119 			* Sort them by slope.
120 			*/
121 			if( VertLeq( e1->Org, e2->Org )) {
122 				return EdgeSign( e2->Dst, e1->Org, e2->Org ) <= 0;
123 			}
124 			return EdgeSign( e1->Dst, e2->Org, e1->Org ) >= 0;
125 		}
126 		return EdgeSign( e2->Dst, event, e2->Org ) <= 0;
127 	}
128 	if( e2->Dst == event ) {
129 		return EdgeSign( e1->Dst, event, e1->Org ) >= 0;
130 	}
131 
132 	/* General case - compute signed distance *from* e1, e2 to event */
133 	t1 = EdgeEval( e1->Dst, event, e1->Org );
134 	t2 = EdgeEval( e2->Dst, event, e2->Org );
135 	return (t1 >= t2);
136 }
137 
138 
DeleteRegion(TESStesselator * tess,ActiveRegion * reg)139 static void DeleteRegion( TESStesselator *tess, ActiveRegion *reg )
140 {
141 	if( reg->fixUpperEdge ) {
142 		/* It was created with zero winding number, so it better be
143 		* deleted with zero winding number (ie. it better not get merged
144 		* with a real edge).
145 		*/
146 		assert( reg->eUp->winding == 0 );
147 	}
148 	reg->eUp->activeRegion = NULL;
149 	dictDelete( tess->dict, reg->nodeUp );
150 	bucketFree( tess->regionPool, reg );
151 }
152 
153 
FixUpperEdge(TESStesselator * tess,ActiveRegion * reg,TESShalfEdge * newEdge)154 static int FixUpperEdge( TESStesselator *tess, ActiveRegion *reg, TESShalfEdge *newEdge )
155 /*
156 * Replace an upper edge which needs fixing (see ConnectRightVertex).
157 */
158 {
159 	assert( reg->fixUpperEdge );
160 	if ( !tessMeshDelete( tess->mesh, reg->eUp ) ) return 0;
161 	reg->fixUpperEdge = FALSE;
162 	reg->eUp = newEdge;
163 	newEdge->activeRegion = reg;
164 
165 	return 1;
166 }
167 
TopLeftRegion(TESStesselator * tess,ActiveRegion * reg)168 static ActiveRegion *TopLeftRegion( TESStesselator *tess, ActiveRegion *reg )
169 {
170 	TESSvertex *org = reg->eUp->Org;
171 	TESShalfEdge *e;
172 
173 	/* Find the region above the uppermost edge with the same origin */
174 	do {
175 		reg = RegionAbove( reg );
176 	} while( reg->eUp->Org == org );
177 
178 	/* If the edge above was a temporary edge introduced by ConnectRightVertex,
179 	* now is the time to fix it.
180 	*/
181 	if( reg->fixUpperEdge ) {
182 		e = tessMeshConnect( tess->mesh, RegionBelow(reg)->eUp->Sym, reg->eUp->Lnext );
183 		if (e == NULL) return NULL;
184 		if ( !FixUpperEdge( tess, reg, e ) ) return NULL;
185 		reg = RegionAbove( reg );
186 	}
187 	return reg;
188 }
189 
TopRightRegion(ActiveRegion * reg)190 static ActiveRegion *TopRightRegion( ActiveRegion *reg )
191 {
192 	TESSvertex *dst = reg->eUp->Dst;
193 
194 	/* Find the region above the uppermost edge with the same destination */
195 	do {
196 		reg = RegionAbove( reg );
197 	} while( reg->eUp->Dst == dst );
198 	return reg;
199 }
200 
AddRegionBelow(TESStesselator * tess,ActiveRegion * regAbove,TESShalfEdge * eNewUp)201 static ActiveRegion *AddRegionBelow( TESStesselator *tess,
202 									ActiveRegion *regAbove,
203 									TESShalfEdge *eNewUp )
204 /*
205 * Add a new active region to the sweep line, *somewhere* below "regAbove"
206 * (according to where the new edge belongs in the sweep-line dictionary).
207 * The upper edge of the new region will be "eNewUp".
208 * Winding number and "inside" flag are not updated.
209 */
210 {
211 	ActiveRegion *regNew = (ActiveRegion *)bucketAlloc( tess->regionPool );
212 	if (regNew == NULL) longjmp(tess->env,1);
213 
214 	regNew->eUp = eNewUp;
215 	regNew->nodeUp = dictInsertBefore( tess->dict, regAbove->nodeUp, regNew );
216 	if (regNew->nodeUp == NULL) longjmp(tess->env,1);
217 	regNew->fixUpperEdge = FALSE;
218 	regNew->sentinel = FALSE;
219 	regNew->dirty = FALSE;
220 
221 	eNewUp->activeRegion = regNew;
222 	return regNew;
223 }
224 
IsWindingInside(TESStesselator * tess,int n)225 static int IsWindingInside( TESStesselator *tess, int n )
226 {
227 	switch( tess->windingRule ) {
228 		case TESS_WINDING_ODD:
229 			return (n & 1);
230 		case TESS_WINDING_NONZERO:
231 			return (n != 0);
232 		case TESS_WINDING_POSITIVE:
233 			return (n > 0);
234 		case TESS_WINDING_NEGATIVE:
235 			return (n < 0);
236 		case TESS_WINDING_ABS_GEQ_TWO:
237 			return (n >= 2) || (n <= -2);
238 	}
239 	/*LINTED*/
240 	assert( FALSE );
241 	/*NOTREACHED*/
242 
243 	return( FALSE );
244 }
245 
246 
ComputeWinding(TESStesselator * tess,ActiveRegion * reg)247 static void ComputeWinding( TESStesselator *tess, ActiveRegion *reg )
248 {
249 	reg->windingNumber = RegionAbove(reg)->windingNumber + reg->eUp->winding;
250 	reg->inside = IsWindingInside( tess, reg->windingNumber );
251 }
252 
253 
FinishRegion(TESStesselator * tess,ActiveRegion * reg)254 static void FinishRegion( TESStesselator *tess, ActiveRegion *reg )
255 /*
256 * Delete a region from the sweep line.  This happens when the upper
257 * and lower chains of a region meet (at a vertex on the sweep line).
258 * The "inside" flag is copied to the appropriate mesh face (we could
259 * not do this before -- since the structure of the mesh is always
260 * changing, this face may not have even existed until now).
261 */
262 {
263 	TESShalfEdge *e = reg->eUp;
264 	TESSface *f = e->Lface;
265 
266 	f->inside = reg->inside;
267 	f->anEdge = e;   /* optimization for tessMeshTessellateMonoRegion() */
268 	DeleteRegion( tess, reg );
269 }
270 
271 
FinishLeftRegions(TESStesselator * tess,ActiveRegion * regFirst,ActiveRegion * regLast)272 static TESShalfEdge *FinishLeftRegions( TESStesselator *tess,
273 									  ActiveRegion *regFirst, ActiveRegion *regLast )
274 /*
275 * We are given a vertex with one or more left-going edges.  All affected
276 * edges should be in the edge dictionary.  Starting at regFirst->eUp,
277 * we walk down deleting all regions where both edges have the same
278 * origin vOrg.  At the same time we copy the "inside" flag from the
279 * active region to the face, since at this point each face will belong
280 * to at most one region (this was not necessarily true until this point
281 * in the sweep).  The walk stops at the region above regLast; if regLast
282 * is NULL we walk as far as possible.  At the same time we relink the
283 * mesh if necessary, so that the ordering of edges around vOrg is the
284 * same as in the dictionary.
285 */
286 {
287 	ActiveRegion *reg, *regPrev;
288 	TESShalfEdge *e, *ePrev;
289 
290 	regPrev = regFirst;
291 	ePrev = regFirst->eUp;
292 	while( regPrev != regLast ) {
293 		regPrev->fixUpperEdge = FALSE;	/* placement was OK */
294 		reg = RegionBelow( regPrev );
295 		e = reg->eUp;
296 		if( e->Org != ePrev->Org ) {
297 			if( ! reg->fixUpperEdge ) {
298 				/* Remove the last left-going edge.  Even though there are no further
299 				* edges in the dictionary with this origin, there may be further
300 				* such edges in the mesh (if we are adding left edges to a vertex
301 				* that has already been processed).  Thus it is important to call
302 				* FinishRegion rather than just DeleteRegion.
303 				*/
304 				FinishRegion( tess, regPrev );
305 				break;
306 			}
307 			/* If the edge below was a temporary edge introduced by
308 			* ConnectRightVertex, now is the time to fix it.
309 			*/
310 			e = tessMeshConnect( tess->mesh, ePrev->Lprev, e->Sym );
311 			if (e == NULL) longjmp(tess->env,1);
312 			if ( !FixUpperEdge( tess, reg, e ) ) longjmp(tess->env,1);
313 		}
314 
315 		/* Relink edges so that ePrev->Onext == e */
316 		if( ePrev->Onext != e ) {
317 			if ( !tessMeshSplice( tess->mesh, e->Oprev, e ) ) longjmp(tess->env,1);
318 			if ( !tessMeshSplice( tess->mesh, ePrev, e ) ) longjmp(tess->env,1);
319 		}
320 		FinishRegion( tess, regPrev );	/* may change reg->eUp */
321 		ePrev = reg->eUp;
322 		regPrev = reg;
323 	}
324 	return ePrev;
325 }
326 
327 
AddRightEdges(TESStesselator * tess,ActiveRegion * regUp,TESShalfEdge * eFirst,TESShalfEdge * eLast,TESShalfEdge * eTopLeft,int cleanUp)328 static void AddRightEdges( TESStesselator *tess, ActiveRegion *regUp,
329 						  TESShalfEdge *eFirst, TESShalfEdge *eLast, TESShalfEdge *eTopLeft,
330 						  int cleanUp )
331 /*
332 * Purpose: insert right-going edges into the edge dictionary, and update
333 * winding numbers and mesh connectivity appropriately.  All right-going
334 * edges share a common origin vOrg.  Edges are inserted CCW starting at
335 * eFirst; the last edge inserted is eLast->Oprev.  If vOrg has any
336 * left-going edges already processed, then eTopLeft must be the edge
337 * such that an imaginary upward vertical segment from vOrg would be
338 * contained between eTopLeft->Oprev and eTopLeft; otherwise eTopLeft
339 * should be NULL.
340 */
341 {
342 	ActiveRegion *reg, *regPrev;
343 	TESShalfEdge *e, *ePrev;
344 	int firstTime = TRUE;
345 
346 	/* Insert the new right-going edges in the dictionary */
347 	e = eFirst;
348 	do {
349 		assert( VertLeq( e->Org, e->Dst ));
350 		AddRegionBelow( tess, regUp, e->Sym );
351 		e = e->Onext;
352 	} while ( e != eLast );
353 
354 	/* Walk *all* right-going edges from e->Org, in the dictionary order,
355 	* updating the winding numbers of each region, and re-linking the mesh
356 	* edges to match the dictionary ordering (if necessary).
357 	*/
358 	if( eTopLeft == NULL ) {
359 		eTopLeft = RegionBelow( regUp )->eUp->Rprev;
360 	}
361 	regPrev = regUp;
362 	ePrev = eTopLeft;
363 	for( ;; ) {
364 		reg = RegionBelow( regPrev );
365 		e = reg->eUp->Sym;
366 		if( e->Org != ePrev->Org ) break;
367 
368 		if( e->Onext != ePrev ) {
369 			/* Unlink e from its current position, and relink below ePrev */
370 			if ( !tessMeshSplice( tess->mesh, e->Oprev, e ) ) longjmp(tess->env,1);
371 			if ( !tessMeshSplice( tess->mesh, ePrev->Oprev, e ) ) longjmp(tess->env,1);
372 		}
373 		/* Compute the winding number and "inside" flag for the new regions */
374 		reg->windingNumber = regPrev->windingNumber - e->winding;
375 		reg->inside = IsWindingInside( tess, reg->windingNumber );
376 
377 		/* Check for two outgoing edges with same slope -- process these
378 		* before any intersection tests (see example in tessComputeInterior).
379 		*/
380 		regPrev->dirty = TRUE;
381 		if( ! firstTime && CheckForRightSplice( tess, regPrev )) {
382 			AddWinding( e, ePrev );
383 			DeleteRegion( tess, regPrev );
384 			if ( !tessMeshDelete( tess->mesh, ePrev ) ) longjmp(tess->env,1);
385 		}
386 		firstTime = FALSE;
387 		regPrev = reg;
388 		ePrev = e;
389 	}
390 	regPrev->dirty = TRUE;
391 	assert( regPrev->windingNumber - e->winding == reg->windingNumber );
392 
393 	if( cleanUp ) {
394 		/* Check for intersections between newly adjacent edges. */
395 		WalkDirtyRegions( tess, regPrev );
396 	}
397 }
398 
399 
SpliceMergeVertices(TESStesselator * tess,TESShalfEdge * e1,TESShalfEdge * e2)400 static void SpliceMergeVertices( TESStesselator *tess, TESShalfEdge *e1,
401 								TESShalfEdge *e2 )
402 /*
403 * Two vertices with idential coordinates are combined into one.
404 * e1->Org is kept, while e2->Org is discarded.
405 */
406 {
407 	if ( !tessMeshSplice( tess->mesh, e1, e2 ) ) longjmp(tess->env,1);
408 }
409 
VertexWeights(TESSvertex * isect,TESSvertex * org,TESSvertex * dst,TESSreal * weights)410 static void VertexWeights( TESSvertex *isect, TESSvertex *org, TESSvertex *dst,
411 						  TESSreal *weights )
412 /*
413 * Find some weights which describe how the intersection vertex is
414 * a linear combination of "org" and "dest".  Each of the two edges
415 * which generated "isect" is allocated 50% of the weight; each edge
416 * splits the weight between its org and dst according to the
417 * relative distance to "isect".
418 */
419 {
420 	TESSreal t1 = VertL1dist( org, isect );
421 	TESSreal t2 = VertL1dist( dst, isect );
422 
423 	weights[0] = (TESSreal)0.5 * t2 / (t1 + t2);
424 	weights[1] = (TESSreal)0.5 * t1 / (t1 + t2);
425 	isect->coords[0] += weights[0]*org->coords[0] + weights[1]*dst->coords[0];
426 	isect->coords[1] += weights[0]*org->coords[1] + weights[1]*dst->coords[1];
427 	isect->coords[2] += weights[0]*org->coords[2] + weights[1]*dst->coords[2];
428 }
429 
430 
GetIntersectData(TESStesselator * tess,TESSvertex * isect,TESSvertex * orgUp,TESSvertex * dstUp,TESSvertex * orgLo,TESSvertex * dstLo)431 static void GetIntersectData( TESStesselator *tess, TESSvertex *isect,
432 							 TESSvertex *orgUp, TESSvertex *dstUp,
433 							 TESSvertex *orgLo, TESSvertex *dstLo )
434  /*
435  * We've computed a new intersection point, now we need a "data" pointer
436  * from the user so that we can refer to this new vertex in the
437  * rendering callbacks.
438  */
439 {
440 	TESSreal weights[4];
441 	TESS_NOTUSED( tess );
442 
443 	isect->coords[0] = isect->coords[1] = isect->coords[2] = 0;
444 	isect->idx = TESS_UNDEF;
445 	VertexWeights( isect, orgUp, dstUp, &weights[0] );
446 	VertexWeights( isect, orgLo, dstLo, &weights[2] );
447 }
448 
CheckForRightSplice(TESStesselator * tess,ActiveRegion * regUp)449 static int CheckForRightSplice( TESStesselator *tess, ActiveRegion *regUp )
450 /*
451 * Check the upper and lower edge of "regUp", to make sure that the
452 * eUp->Org is above eLo, or eLo->Org is below eUp (depending on which
453 * origin is leftmost).
454 *
455 * The main purpose is to splice right-going edges with the same
456 * dest vertex and nearly identical slopes (ie. we can't distinguish
457 * the slopes numerically).  However the splicing can also help us
458 * to recover from numerical errors.  For example, suppose at one
459 * point we checked eUp and eLo, and decided that eUp->Org is barely
460 * above eLo.  Then later, we split eLo into two edges (eg. from
461 * a splice operation like this one).  This can change the result of
462 * our test so that now eUp->Org is incident to eLo, or barely below it.
463 * We must correct this condition to maintain the dictionary invariants.
464 *
465 * One possibility is to check these edges for intersection again
466 * (ie. CheckForIntersect).  This is what we do if possible.  However
467 * CheckForIntersect requires that tess->event lies between eUp and eLo,
468 * so that it has something to fall back on when the intersection
469 * calculation gives us an unusable answer.  So, for those cases where
470 * we can't check for intersection, this routine fixes the problem
471 * by just splicing the offending vertex into the other edge.
472 * This is a guaranteed solution, no matter how degenerate things get.
473 * Basically this is a combinatorial solution to a numerical problem.
474 */
475 {
476 	ActiveRegion *regLo = RegionBelow(regUp);
477 	TESShalfEdge *eUp = regUp->eUp;
478 	TESShalfEdge *eLo = regLo->eUp;
479 
480 	if( VertLeq( eUp->Org, eLo->Org )) {
481 		if( EdgeSign( eLo->Dst, eUp->Org, eLo->Org ) > 0 ) return FALSE;
482 
483 		/* eUp->Org appears to be below eLo */
484 		if( ! VertEq( eUp->Org, eLo->Org )) {
485 			/* Splice eUp->Org into eLo */
486 			if ( tessMeshSplitEdge( tess->mesh, eLo->Sym ) == NULL) longjmp(tess->env,1);
487 			if ( !tessMeshSplice( tess->mesh, eUp, eLo->Oprev ) ) longjmp(tess->env,1);
488 			regUp->dirty = regLo->dirty = TRUE;
489 
490 		} else if( eUp->Org != eLo->Org ) {
491 			/* merge the two vertices, discarding eUp->Org */
492 			pqDelete( tess->pq, eUp->Org->pqHandle );
493 			SpliceMergeVertices( tess, eLo->Oprev, eUp );
494 		}
495 	} else {
496 		if( EdgeSign( eUp->Dst, eLo->Org, eUp->Org ) < 0 ) return FALSE;
497 
498 		/* eLo->Org appears to be above eUp, so splice eLo->Org into eUp */
499 		RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
500 		if (tessMeshSplitEdge( tess->mesh, eUp->Sym ) == NULL) longjmp(tess->env,1);
501 		if ( !tessMeshSplice( tess->mesh, eLo->Oprev, eUp ) ) longjmp(tess->env,1);
502 	}
503 	return TRUE;
504 }
505 
CheckForLeftSplice(TESStesselator * tess,ActiveRegion * regUp)506 static int CheckForLeftSplice( TESStesselator *tess, ActiveRegion *regUp )
507 /*
508 * Check the upper and lower edge of "regUp", to make sure that the
509 * eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which
510 * destination is rightmost).
511 *
512 * Theoretically, this should always be true.  However, splitting an edge
513 * into two pieces can change the results of previous tests.  For example,
514 * suppose at one point we checked eUp and eLo, and decided that eUp->Dst
515 * is barely above eLo.  Then later, we split eLo into two edges (eg. from
516 * a splice operation like this one).  This can change the result of
517 * the test so that now eUp->Dst is incident to eLo, or barely below it.
518 * We must correct this condition to maintain the dictionary invariants
519 * (otherwise new edges might get inserted in the wrong place in the
520 * dictionary, and bad stuff will happen).
521 *
522 * We fix the problem by just splicing the offending vertex into the
523 * other edge.
524 */
525 {
526 	ActiveRegion *regLo = RegionBelow(regUp);
527 	TESShalfEdge *eUp = regUp->eUp;
528 	TESShalfEdge *eLo = regLo->eUp;
529 	TESShalfEdge *e;
530 
531 	assert( ! VertEq( eUp->Dst, eLo->Dst ));
532 
533 	if( VertLeq( eUp->Dst, eLo->Dst )) {
534 		if( EdgeSign( eUp->Dst, eLo->Dst, eUp->Org ) < 0 ) return FALSE;
535 
536 		/* eLo->Dst is above eUp, so splice eLo->Dst into eUp */
537 		RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
538 		e = tessMeshSplitEdge( tess->mesh, eUp );
539 		if (e == NULL) longjmp(tess->env,1);
540 		if ( !tessMeshSplice( tess->mesh, eLo->Sym, e ) ) longjmp(tess->env,1);
541 		e->Lface->inside = regUp->inside;
542 	} else {
543 		if( EdgeSign( eLo->Dst, eUp->Dst, eLo->Org ) > 0 ) return FALSE;
544 
545 		/* eUp->Dst is below eLo, so splice eUp->Dst into eLo */
546 		regUp->dirty = regLo->dirty = TRUE;
547 		e = tessMeshSplitEdge( tess->mesh, eLo );
548 		if (e == NULL) longjmp(tess->env,1);
549 		if ( !tessMeshSplice( tess->mesh, eUp->Lnext, eLo->Sym ) ) longjmp(tess->env,1);
550 		e->Rface->inside = regUp->inside;
551 	}
552 	return TRUE;
553 }
554 
555 
CheckForIntersect(TESStesselator * tess,ActiveRegion * regUp)556 static int CheckForIntersect( TESStesselator *tess, ActiveRegion *regUp )
557 /*
558 * Check the upper and lower edges of the given region to see if
559 * they intersect.  If so, create the intersection and add it
560 * to the data structures.
561 *
562 * Returns TRUE if adding the new intersection resulted in a recursive
563 * call to AddRightEdges(); in this case all "dirty" regions have been
564 * checked for intersections, and possibly regUp has been deleted.
565 */
566 {
567 	ActiveRegion *regLo = RegionBelow(regUp);
568 	TESShalfEdge *eUp = regUp->eUp;
569 	TESShalfEdge *eLo = regLo->eUp;
570 	TESSvertex *orgUp = eUp->Org;
571 	TESSvertex *orgLo = eLo->Org;
572 	TESSvertex *dstUp = eUp->Dst;
573 	TESSvertex *dstLo = eLo->Dst;
574 	TESSreal tMinUp, tMaxLo;
575 	TESSvertex isect, *orgMin;
576 	TESShalfEdge *e;
577 
578 	assert( ! VertEq( dstLo, dstUp ));
579 	assert( EdgeSign( dstUp, tess->event, orgUp ) <= 0 );
580 	assert( EdgeSign( dstLo, tess->event, orgLo ) >= 0 );
581 	assert( orgUp != tess->event && orgLo != tess->event );
582 	assert( ! regUp->fixUpperEdge && ! regLo->fixUpperEdge );
583 
584 	if( orgUp == orgLo ) return FALSE;	/* right endpoints are the same */
585 
586 	tMinUp = MIN( orgUp->t, dstUp->t );
587 	tMaxLo = MAX( orgLo->t, dstLo->t );
588 	if( tMinUp > tMaxLo ) return FALSE;	/* t ranges do not overlap */
589 
590 	if( VertLeq( orgUp, orgLo )) {
591 		if( EdgeSign( dstLo, orgUp, orgLo ) > 0 ) return FALSE;
592 	} else {
593 		if( EdgeSign( dstUp, orgLo, orgUp ) < 0 ) return FALSE;
594 	}
595 
596 	/* At this point the edges intersect, at least marginally */
597 	DebugEvent( tess );
598 
599 	tesedgeIntersect( dstUp, orgUp, dstLo, orgLo, &isect );
600 	/* The following properties are guaranteed: */
601 	assert( MIN( orgUp->t, dstUp->t ) <= isect.t );
602 	assert( isect.t <= MAX( orgLo->t, dstLo->t ));
603 	assert( MIN( dstLo->s, dstUp->s ) <= isect.s );
604 	assert( isect.s <= MAX( orgLo->s, orgUp->s ));
605 
606 	if( VertLeq( &isect, tess->event )) {
607 		/* The intersection point lies slightly to the left of the sweep line,
608 		* so move it until it''s slightly to the right of the sweep line.
609 		* (If we had perfect numerical precision, this would never happen
610 		* in the first place).  The easiest and safest thing to do is
611 		* replace the intersection by tess->event.
612 		*/
613 		isect.s = tess->event->s;
614 		isect.t = tess->event->t;
615 	}
616 	/* Similarly, if the computed intersection lies to the right of the
617 	* rightmost origin (which should rarely happen), it can cause
618 	* unbelievable inefficiency on sufficiently degenerate inputs.
619 	* (If you have the test program, try running test54.d with the
620 	* "X zoom" option turned on).
621 	*/
622 	orgMin = VertLeq( orgUp, orgLo ) ? orgUp : orgLo;
623 	if( VertLeq( orgMin, &isect )) {
624 		isect.s = orgMin->s;
625 		isect.t = orgMin->t;
626 	}
627 
628 	if( VertEq( &isect, orgUp ) || VertEq( &isect, orgLo )) {
629 		/* Easy case -- intersection at one of the right endpoints */
630 		(void) CheckForRightSplice( tess, regUp );
631 		return FALSE;
632 	}
633 
634 	if(    (! VertEq( dstUp, tess->event )
635 		&& EdgeSign( dstUp, tess->event, &isect ) >= 0)
636 		|| (! VertEq( dstLo, tess->event )
637 		&& EdgeSign( dstLo, tess->event, &isect ) <= 0 ))
638 	{
639 		/* Very unusual -- the new upper or lower edge would pass on the
640 		* wrong side of the sweep event, or through it.  This can happen
641 		* due to very small numerical errors in the intersection calculation.
642 		*/
643 		if( dstLo == tess->event ) {
644 			/* Splice dstLo into eUp, and process the new region(s) */
645 			if (tessMeshSplitEdge( tess->mesh, eUp->Sym ) == NULL) longjmp(tess->env,1);
646 			if ( !tessMeshSplice( tess->mesh, eLo->Sym, eUp ) ) longjmp(tess->env,1);
647 			regUp = TopLeftRegion( tess, regUp );
648 			if (regUp == NULL) longjmp(tess->env,1);
649 			eUp = RegionBelow(regUp)->eUp;
650 			FinishLeftRegions( tess, RegionBelow(regUp), regLo );
651 			AddRightEdges( tess, regUp, eUp->Oprev, eUp, eUp, TRUE );
652 			return TRUE;
653 		}
654 		if( dstUp == tess->event ) {
655 			/* Splice dstUp into eLo, and process the new region(s) */
656 			if (tessMeshSplitEdge( tess->mesh, eLo->Sym ) == NULL) longjmp(tess->env,1);
657 			if ( !tessMeshSplice( tess->mesh, eUp->Lnext, eLo->Oprev ) ) longjmp(tess->env,1);
658 			regLo = regUp;
659 			regUp = TopRightRegion( regUp );
660 			e = RegionBelow(regUp)->eUp->Rprev;
661 			regLo->eUp = eLo->Oprev;
662 			eLo = FinishLeftRegions( tess, regLo, NULL );
663 			AddRightEdges( tess, regUp, eLo->Onext, eUp->Rprev, e, TRUE );
664 			return TRUE;
665 		}
666 		/* Special case: called from ConnectRightVertex.  If either
667 		* edge passes on the wrong side of tess->event, split it
668 		* (and wait for ConnectRightVertex to splice it appropriately).
669 		*/
670 		if( EdgeSign( dstUp, tess->event, &isect ) >= 0 ) {
671 			RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
672 			if (tessMeshSplitEdge( tess->mesh, eUp->Sym ) == NULL) longjmp(tess->env,1);
673 			eUp->Org->s = tess->event->s;
674 			eUp->Org->t = tess->event->t;
675 		}
676 		if( EdgeSign( dstLo, tess->event, &isect ) <= 0 ) {
677 			regUp->dirty = regLo->dirty = TRUE;
678 			if (tessMeshSplitEdge( tess->mesh, eLo->Sym ) == NULL) longjmp(tess->env,1);
679 			eLo->Org->s = tess->event->s;
680 			eLo->Org->t = tess->event->t;
681 		}
682 		/* leave the rest for ConnectRightVertex */
683 		return FALSE;
684 	}
685 
686 	/* General case -- split both edges, splice into new vertex.
687 	* When we do the splice operation, the order of the arguments is
688 	* arbitrary as far as correctness goes.  However, when the operation
689 	* creates a new face, the work done is proportional to the size of
690 	* the new face.  We expect the faces in the processed part of
691 	* the mesh (ie. eUp->Lface) to be smaller than the faces in the
692 	* unprocessed original contours (which will be eLo->Oprev->Lface).
693 	*/
694 	if (tessMeshSplitEdge( tess->mesh, eUp->Sym ) == NULL) longjmp(tess->env,1);
695 	if (tessMeshSplitEdge( tess->mesh, eLo->Sym ) == NULL) longjmp(tess->env,1);
696 	if ( !tessMeshSplice( tess->mesh, eLo->Oprev, eUp ) ) longjmp(tess->env,1);
697 	eUp->Org->s = isect.s;
698 	eUp->Org->t = isect.t;
699 	eUp->Org->pqHandle = pqInsert( &tess->alloc, tess->pq, eUp->Org );
700 	if (eUp->Org->pqHandle == INV_HANDLE) {
701 		pqDeletePriorityQ( &tess->alloc, tess->pq );
702 		tess->pq = NULL;
703 		longjmp(tess->env,1);
704 	}
705 	GetIntersectData( tess, eUp->Org, orgUp, dstUp, orgLo, dstLo );
706 	RegionAbove(regUp)->dirty = regUp->dirty = regLo->dirty = TRUE;
707 	return FALSE;
708 }
709 
WalkDirtyRegions(TESStesselator * tess,ActiveRegion * regUp)710 static void WalkDirtyRegions( TESStesselator *tess, ActiveRegion *regUp )
711 /*
712 * When the upper or lower edge of any region changes, the region is
713 * marked "dirty".  This routine walks through all the dirty regions
714 * and makes sure that the dictionary invariants are satisfied
715 * (see the comments at the beginning of this file).  Of course
716 * new dirty regions can be created as we make changes to restore
717 * the invariants.
718 */
719 {
720 	ActiveRegion *regLo = RegionBelow(regUp);
721 	TESShalfEdge *eUp, *eLo;
722 
723 	for( ;; ) {
724 		/* Find the lowest dirty region (we walk from the bottom up). */
725 		while( regLo->dirty ) {
726 			regUp = regLo;
727 			regLo = RegionBelow(regLo);
728 		}
729 		if( ! regUp->dirty ) {
730 			regLo = regUp;
731 			regUp = RegionAbove( regUp );
732 			if( regUp == NULL || ! regUp->dirty ) {
733 				/* We've walked all the dirty regions */
734 				return;
735 			}
736 		}
737 		regUp->dirty = FALSE;
738 		eUp = regUp->eUp;
739 		eLo = regLo->eUp;
740 
741 		if( eUp->Dst != eLo->Dst ) {
742 			/* Check that the edge ordering is obeyed at the Dst vertices. */
743 			if( CheckForLeftSplice( tess, regUp )) {
744 
745 				/* If the upper or lower edge was marked fixUpperEdge, then
746 				* we no longer need it (since these edges are needed only for
747 				* vertices which otherwise have no right-going edges).
748 				*/
749 				if( regLo->fixUpperEdge ) {
750 					DeleteRegion( tess, regLo );
751 					if ( !tessMeshDelete( tess->mesh, eLo ) ) longjmp(tess->env,1);
752 					regLo = RegionBelow( regUp );
753 					eLo = regLo->eUp;
754 				} else if( regUp->fixUpperEdge ) {
755 					DeleteRegion( tess, regUp );
756 					if ( !tessMeshDelete( tess->mesh, eUp ) ) longjmp(tess->env,1);
757 					regUp = RegionAbove( regLo );
758 					eUp = regUp->eUp;
759 				}
760 			}
761 		}
762 		if( eUp->Org != eLo->Org ) {
763 			if(    eUp->Dst != eLo->Dst
764 				&& ! regUp->fixUpperEdge && ! regLo->fixUpperEdge
765 				&& (eUp->Dst == tess->event || eLo->Dst == tess->event) )
766 			{
767 				/* When all else fails in CheckForIntersect(), it uses tess->event
768 				* as the intersection location.  To make this possible, it requires
769 				* that tess->event lie between the upper and lower edges, and also
770 				* that neither of these is marked fixUpperEdge (since in the worst
771 				* case it might splice one of these edges into tess->event, and
772 				* violate the invariant that fixable edges are the only right-going
773 				* edge from their associated vertex).
774 				*/
775 				if( CheckForIntersect( tess, regUp )) {
776 					/* WalkDirtyRegions() was called recursively; we're done */
777 					return;
778 				}
779 			} else {
780 				/* Even though we can't use CheckForIntersect(), the Org vertices
781 				* may violate the dictionary edge ordering.  Check and correct this.
782 				*/
783 				(void) CheckForRightSplice( tess, regUp );
784 			}
785 		}
786 		if( eUp->Org == eLo->Org && eUp->Dst == eLo->Dst ) {
787 			/* A degenerate loop consisting of only two edges -- delete it. */
788 			AddWinding( eLo, eUp );
789 			DeleteRegion( tess, regUp );
790 			if ( !tessMeshDelete( tess->mesh, eUp ) ) longjmp(tess->env,1);
791 			regUp = RegionAbove( regLo );
792 		}
793 	}
794 }
795 
796 
ConnectRightVertex(TESStesselator * tess,ActiveRegion * regUp,TESShalfEdge * eBottomLeft)797 static void ConnectRightVertex( TESStesselator *tess, ActiveRegion *regUp,
798 							   TESShalfEdge *eBottomLeft )
799 /*
800 * Purpose: connect a "right" vertex vEvent (one where all edges go left)
801 * to the unprocessed portion of the mesh.  Since there are no right-going
802 * edges, two regions (one above vEvent and one below) are being merged
803 * into one.  "regUp" is the upper of these two regions.
804 *
805 * There are two reasons for doing this (adding a right-going edge):
806 *  - if the two regions being merged are "inside", we must add an edge
807 *    to keep them separated (the combined region would not be monotone).
808 *  - in any case, we must leave some record of vEvent in the dictionary,
809 *    so that we can merge vEvent with features that we have not seen yet.
810 *    For example, maybe there is a vertical edge which passes just to
811 *    the right of vEvent; we would like to splice vEvent into this edge.
812 *
813 * However, we don't want to connect vEvent to just any vertex.  We don''t
814 * want the new edge to cross any other edges; otherwise we will create
815 * intersection vertices even when the input data had no self-intersections.
816 * (This is a bad thing; if the user's input data has no intersections,
817 * we don't want to generate any false intersections ourselves.)
818 *
819 * Our eventual goal is to connect vEvent to the leftmost unprocessed
820 * vertex of the combined region (the union of regUp and regLo).
821 * But because of unseen vertices with all right-going edges, and also
822 * new vertices which may be created by edge intersections, we don''t
823 * know where that leftmost unprocessed vertex is.  In the meantime, we
824 * connect vEvent to the closest vertex of either chain, and mark the region
825 * as "fixUpperEdge".  This flag says to delete and reconnect this edge
826 * to the next processed vertex on the boundary of the combined region.
827 * Quite possibly the vertex we connected to will turn out to be the
828 * closest one, in which case we won''t need to make any changes.
829 */
830 {
831 	TESShalfEdge *eNew;
832 	TESShalfEdge *eTopLeft = eBottomLeft->Onext;
833 	ActiveRegion *regLo = RegionBelow(regUp);
834 	TESShalfEdge *eUp = regUp->eUp;
835 	TESShalfEdge *eLo = regLo->eUp;
836 	int degenerate = FALSE;
837 
838 	if( eUp->Dst != eLo->Dst ) {
839 		(void) CheckForIntersect( tess, regUp );
840 	}
841 
842 	/* Possible new degeneracies: upper or lower edge of regUp may pass
843 	* through vEvent, or may coincide with new intersection vertex
844 	*/
845 	if( VertEq( eUp->Org, tess->event )) {
846 		if ( !tessMeshSplice( tess->mesh, eTopLeft->Oprev, eUp ) ) longjmp(tess->env,1);
847 		regUp = TopLeftRegion( tess, regUp );
848 		if (regUp == NULL) longjmp(tess->env,1);
849 		eTopLeft = RegionBelow( regUp )->eUp;
850 		FinishLeftRegions( tess, RegionBelow(regUp), regLo );
851 		degenerate = TRUE;
852 	}
853 	if( VertEq( eLo->Org, tess->event )) {
854 		if ( !tessMeshSplice( tess->mesh, eBottomLeft, eLo->Oprev ) ) longjmp(tess->env,1);
855 		eBottomLeft = FinishLeftRegions( tess, regLo, NULL );
856 		degenerate = TRUE;
857 	}
858 	if( degenerate ) {
859 		AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TRUE );
860 		return;
861 	}
862 
863 	/* Non-degenerate situation -- need to add a temporary, fixable edge.
864 	* Connect to the closer of eLo->Org, eUp->Org.
865 	*/
866 	if( VertLeq( eLo->Org, eUp->Org )) {
867 		eNew = eLo->Oprev;
868 	} else {
869 		eNew = eUp;
870 	}
871 	eNew = tessMeshConnect( tess->mesh, eBottomLeft->Lprev, eNew );
872 	if (eNew == NULL) longjmp(tess->env,1);
873 
874 	/* Prevent cleanup, otherwise eNew might disappear before we've even
875 	* had a chance to mark it as a temporary edge.
876 	*/
877 	AddRightEdges( tess, regUp, eNew, eNew->Onext, eNew->Onext, FALSE );
878 	eNew->Sym->activeRegion->fixUpperEdge = TRUE;
879 	WalkDirtyRegions( tess, regUp );
880 }
881 
882 /* Because vertices at exactly the same location are merged together
883 * before we process the sweep event, some degenerate cases can't occur.
884 * However if someone eventually makes the modifications required to
885 * merge features which are close together, the cases below marked
886 * TOLERANCE_NONZERO will be useful.  They were debugged before the
887 * code to merge identical vertices in the main loop was added.
888 */
889 #define TOLERANCE_NONZERO	FALSE
890 
ConnectLeftDegenerate(TESStesselator * tess,ActiveRegion * regUp,TESSvertex * vEvent)891 static void ConnectLeftDegenerate( TESStesselator *tess,
892 								  ActiveRegion *regUp, TESSvertex *vEvent )
893 /*
894 * The event vertex lies exacty on an already-processed edge or vertex.
895 * Adding the new vertex involves splicing it into the already-processed
896 * part of the mesh.
897 */
898 {
899 	TESShalfEdge *e, *eTopLeft, *eTopRight, *eLast;
900 	ActiveRegion *reg;
901 
902 	e = regUp->eUp;
903 	if( VertEq( e->Org, vEvent )) {
904 		/* e->Org is an unprocessed vertex - just combine them, and wait
905 		* for e->Org to be pulled from the queue
906 		*/
907 		assert( TOLERANCE_NONZERO );
908 		SpliceMergeVertices( tess, e, vEvent->anEdge );
909 		return;
910 	}
911 
912 	if( ! VertEq( e->Dst, vEvent )) {
913 		/* General case -- splice vEvent into edge e which passes through it */
914 		if (tessMeshSplitEdge( tess->mesh, e->Sym ) == NULL) longjmp(tess->env,1);
915 		if( regUp->fixUpperEdge ) {
916 			/* This edge was fixable -- delete unused portion of original edge */
917 			if ( !tessMeshDelete( tess->mesh, e->Onext ) ) longjmp(tess->env,1);
918 			regUp->fixUpperEdge = FALSE;
919 		}
920 		if ( !tessMeshSplice( tess->mesh, vEvent->anEdge, e ) ) longjmp(tess->env,1);
921 		SweepEvent( tess, vEvent );	/* recurse */
922 		return;
923 	}
924 
925 	/* vEvent coincides with e->Dst, which has already been processed.
926 	* Splice in the additional right-going edges.
927 	*/
928 	assert( TOLERANCE_NONZERO );
929 	regUp = TopRightRegion( regUp );
930 	reg = RegionBelow( regUp );
931 	eTopRight = reg->eUp->Sym;
932 	eTopLeft = eLast = eTopRight->Onext;
933 	if( reg->fixUpperEdge ) {
934 		/* Here e->Dst has only a single fixable edge going right.
935 		* We can delete it since now we have some real right-going edges.
936 		*/
937 		assert( eTopLeft != eTopRight );   /* there are some left edges too */
938 		DeleteRegion( tess, reg );
939 		if ( !tessMeshDelete( tess->mesh, eTopRight ) ) longjmp(tess->env,1);
940 		eTopRight = eTopLeft->Oprev;
941 	}
942 	if ( !tessMeshSplice( tess->mesh, vEvent->anEdge, eTopRight ) ) longjmp(tess->env,1);
943 	if( ! EdgeGoesLeft( eTopLeft )) {
944 		/* e->Dst had no left-going edges -- indicate this to AddRightEdges() */
945 		eTopLeft = NULL;
946 	}
947 	AddRightEdges( tess, regUp, eTopRight->Onext, eLast, eTopLeft, TRUE );
948 }
949 
950 
ConnectLeftVertex(TESStesselator * tess,TESSvertex * vEvent)951 static void ConnectLeftVertex( TESStesselator *tess, TESSvertex *vEvent )
952 /*
953 * Purpose: connect a "left" vertex (one where both edges go right)
954 * to the processed portion of the mesh.  Let R be the active region
955 * containing vEvent, and let U and L be the upper and lower edge
956 * chains of R.  There are two possibilities:
957 *
958 * - the normal case: split R into two regions, by connecting vEvent to
959 *   the rightmost vertex of U or L lying to the left of the sweep line
960 *
961 * - the degenerate case: if vEvent is close enough to U or L, we
962 *   merge vEvent into that edge chain.  The subcases are:
963 *	- merging with the rightmost vertex of U or L
964 *	- merging with the active edge of U or L
965 *	- merging with an already-processed portion of U or L
966 */
967 {
968 	ActiveRegion *regUp, *regLo, *reg;
969 	TESShalfEdge *eUp, *eLo, *eNew;
970 	ActiveRegion tmp;
971 
972 	/* assert( vEvent->anEdge->Onext->Onext == vEvent->anEdge ); */
973 
974 	/* Get a pointer to the active region containing vEvent */
975 	tmp.eUp = vEvent->anEdge->Sym;
976 	/* __GL_DICTLISTKEY */ /* tessDictListSearch */
977 	regUp = (ActiveRegion *)dictKey( dictSearch( tess->dict, &tmp ));
978 	regLo = RegionBelow( regUp );
979 	if( !regLo ) {
980 		// This may happen if the input polygon is coplanar.
981 		return;
982 	}
983 	eUp = regUp->eUp;
984 	eLo = regLo->eUp;
985 
986 	/* Try merging with U or L first */
987 	if( EdgeSign( eUp->Dst, vEvent, eUp->Org ) == 0 ) {
988 		ConnectLeftDegenerate( tess, regUp, vEvent );
989 		return;
990 	}
991 
992 	/* Connect vEvent to rightmost processed vertex of either chain.
993 	* e->Dst is the vertex that we will connect to vEvent.
994 	*/
995 	reg = VertLeq( eLo->Dst, eUp->Dst ) ? regUp : regLo;
996 
997 	if( regUp->inside || reg->fixUpperEdge) {
998 		if( reg == regUp ) {
999 			eNew = tessMeshConnect( tess->mesh, vEvent->anEdge->Sym, eUp->Lnext );
1000 			if (eNew == NULL) longjmp(tess->env,1);
1001 		} else {
1002 			TESShalfEdge *tempHalfEdge= tessMeshConnect( tess->mesh, eLo->Dnext, vEvent->anEdge);
1003 			if (tempHalfEdge == NULL) longjmp(tess->env,1);
1004 
1005 			eNew = tempHalfEdge->Sym;
1006 		}
1007 		if( reg->fixUpperEdge ) {
1008 			if ( !FixUpperEdge( tess, reg, eNew ) ) longjmp(tess->env,1);
1009 		} else {
1010 			ComputeWinding( tess, AddRegionBelow( tess, regUp, eNew ));
1011 		}
1012 		SweepEvent( tess, vEvent );
1013 	} else {
1014 		/* The new vertex is in a region which does not belong to the polygon.
1015 		* We don''t need to connect this vertex to the rest of the mesh.
1016 		*/
1017 		AddRightEdges( tess, regUp, vEvent->anEdge, vEvent->anEdge, NULL, TRUE );
1018 	}
1019 }
1020 
1021 
SweepEvent(TESStesselator * tess,TESSvertex * vEvent)1022 static void SweepEvent( TESStesselator *tess, TESSvertex *vEvent )
1023 /*
1024 * Does everything necessary when the sweep line crosses a vertex.
1025 * Updates the mesh and the edge dictionary.
1026 */
1027 {
1028 	ActiveRegion *regUp, *reg;
1029 	TESShalfEdge *e, *eTopLeft, *eBottomLeft;
1030 
1031 	tess->event = vEvent;		/* for access in EdgeLeq() */
1032 	DebugEvent( tess );
1033 
1034 	/* Check if this vertex is the right endpoint of an edge that is
1035 	* already in the dictionary.  In this case we don't need to waste
1036 	* time searching for the location to insert new edges.
1037 	*/
1038 	e = vEvent->anEdge;
1039 	while( e->activeRegion == NULL ) {
1040 		e = e->Onext;
1041 		if( e == vEvent->anEdge ) {
1042 			/* All edges go right -- not incident to any processed edges */
1043 			ConnectLeftVertex( tess, vEvent );
1044 			return;
1045 		}
1046 	}
1047 
1048 	/* Processing consists of two phases: first we "finish" all the
1049 	* active regions where both the upper and lower edges terminate
1050 	* at vEvent (ie. vEvent is closing off these regions).
1051 	* We mark these faces "inside" or "outside" the polygon according
1052 	* to their winding number, and delete the edges from the dictionary.
1053 	* This takes care of all the left-going edges from vEvent.
1054 	*/
1055 	regUp = TopLeftRegion( tess, e->activeRegion );
1056 	if (regUp == NULL) longjmp(tess->env,1);
1057 	reg = RegionBelow( regUp );
1058 	eTopLeft = reg->eUp;
1059 	eBottomLeft = FinishLeftRegions( tess, reg, NULL );
1060 
1061 	/* Next we process all the right-going edges from vEvent.  This
1062 	* involves adding the edges to the dictionary, and creating the
1063 	* associated "active regions" which record information about the
1064 	* regions between adjacent dictionary edges.
1065 	*/
1066 	if( eBottomLeft->Onext == eTopLeft ) {
1067 		/* No right-going edges -- add a temporary "fixable" edge */
1068 		ConnectRightVertex( tess, regUp, eBottomLeft );
1069 	} else {
1070 		AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TRUE );
1071 	}
1072 }
1073 
1074 
1075 /* Make the sentinel coordinates big enough that they will never be
1076 * merged with real input features.
1077 */
1078 
AddSentinel(TESStesselator * tess,TESSreal smin,TESSreal smax,TESSreal t)1079 static void AddSentinel( TESStesselator *tess, TESSreal smin, TESSreal smax, TESSreal t )
1080 /*
1081 * We add two sentinel edges above and below all other edges,
1082 * to avoid special cases at the top and bottom.
1083 */
1084 {
1085 	TESShalfEdge *e;
1086 	ActiveRegion *reg = (ActiveRegion *)bucketAlloc( tess->regionPool );
1087 	if (reg == NULL) longjmp(tess->env,1);
1088 
1089 	e = tessMeshMakeEdge( tess->mesh );
1090 	if (e == NULL) longjmp(tess->env,1);
1091 
1092 	e->Org->s = smax;
1093 	e->Org->t = t;
1094 	e->Dst->s = smin;
1095 	e->Dst->t = t;
1096 	tess->event = e->Dst;		/* initialize it */
1097 
1098 	reg->eUp = e;
1099 	reg->windingNumber = 0;
1100 	reg->inside = FALSE;
1101 	reg->fixUpperEdge = FALSE;
1102 	reg->sentinel = TRUE;
1103 	reg->dirty = FALSE;
1104 	reg->nodeUp = dictInsert( tess->dict, reg );
1105 	if (reg->nodeUp == NULL) longjmp(tess->env,1);
1106 }
1107 
1108 
InitEdgeDict(TESStesselator * tess)1109 static void InitEdgeDict( TESStesselator *tess )
1110 /*
1111 * We maintain an ordering of edge intersections with the sweep line.
1112 * This order is maintained in a dynamic dictionary.
1113 */
1114 {
1115 	TESSreal w, h;
1116 	TESSreal smin, smax, tmin, tmax;
1117 
1118 	tess->dict = dictNewDict( &tess->alloc, tess, (int (*)(void *, DictKey, DictKey)) EdgeLeq );
1119 	if (tess->dict == NULL) longjmp(tess->env,1);
1120 
1121 	w = (tess->bmax[0] - tess->bmin[0]);
1122 	h = (tess->bmax[1] - tess->bmin[1]);
1123 
1124         /* If the bbox is empty, ensure that sentinels are not coincident by
1125            slightly enlarging it. To avoid floating point precision issues,
1126         make sure to enlarge by a minimal amount. */
1127 	smin = tess->bmin[0] - (w > 0.01 ? w : 0.01);
1128 	smax = tess->bmax[0] + (w > 0.01 ? w : 0.01);
1129 	tmin = tess->bmin[1] - (h > 0.01 ? h : 0.01);
1130 	tmax = tess->bmax[1] + (h > 0.01 ? h : 0.01);
1131 
1132 	AddSentinel( tess, smin, smax, tmin );
1133 	AddSentinel( tess, smin, smax, tmax );
1134 }
1135 
1136 
DoneEdgeDict(TESStesselator * tess)1137 static void DoneEdgeDict( TESStesselator *tess )
1138 {
1139 	ActiveRegion *reg;
1140 	int fixedEdges = 0;
1141 
1142 	while( (reg = (ActiveRegion *)dictKey( dictMin( tess->dict ))) != NULL ) {
1143 		/*
1144 		* At the end of all processing, the dictionary should contain
1145 		* only the two sentinel edges, plus at most one "fixable" edge
1146 		* created by ConnectRightVertex().
1147 		*/
1148 		if( ! reg->sentinel ) {
1149 			assert( reg->fixUpperEdge );
1150 			assert( ++fixedEdges == 1 );
1151 		}
1152 		assert( reg->windingNumber == 0 );
1153 		DeleteRegion( tess, reg );
1154 		/*    tessMeshDelete( reg->eUp );*/
1155 	}
1156 	dictDeleteDict( &tess->alloc, tess->dict );
1157 }
1158 
1159 
RemoveDegenerateEdges(TESStesselator * tess)1160 static void RemoveDegenerateEdges( TESStesselator *tess )
1161 /*
1162 * Remove zero-length edges, and contours with fewer than 3 vertices.
1163 */
1164 {
1165 	TESShalfEdge *e, *eNext, *eLnext;
1166 	TESShalfEdge *eHead = &tess->mesh->eHead;
1167 
1168 	/*LINTED*/
1169 	for( e = eHead->next; e != eHead; e = eNext ) {
1170 		eNext = e->next;
1171 		eLnext = e->Lnext;
1172 
1173 		if( VertEq( e->Org, e->Dst ) && e->Lnext->Lnext != e ) {
1174 			/* Zero-length edge, contour has at least 3 edges */
1175 
1176 			SpliceMergeVertices( tess, eLnext, e );	/* deletes e->Org */
1177 			if ( !tessMeshDelete( tess->mesh, e ) ) longjmp(tess->env,1); /* e is a self-loop */
1178 			e = eLnext;
1179 			eLnext = e->Lnext;
1180 		}
1181 		if( eLnext->Lnext == e ) {
1182 			/* Degenerate contour (one or two edges) */
1183 
1184 			if( eLnext != e ) {
1185 				if( eLnext == eNext || eLnext == eNext->Sym ) { eNext = eNext->next; }
1186 				if ( !tessMeshDelete( tess->mesh, eLnext ) ) longjmp(tess->env,1);
1187 			}
1188 			if( e == eNext || e == eNext->Sym ) { eNext = eNext->next; }
1189 			if ( !tessMeshDelete( tess->mesh, e ) ) longjmp(tess->env,1);
1190 		}
1191 	}
1192 }
1193 
InitPriorityQ(TESStesselator * tess)1194 static int InitPriorityQ( TESStesselator *tess )
1195 /*
1196 * Insert all vertices into the priority queue which determines the
1197 * order in which vertices cross the sweep line.
1198 */
1199 {
1200 	PriorityQ *pq;
1201 	TESSvertex *v, *vHead;
1202 	int vertexCount = 0;
1203 
1204 	vHead = &tess->mesh->vHead;
1205 	for( v = vHead->next; v != vHead; v = v->next ) {
1206 		vertexCount++;
1207 	}
1208 	/* Make sure there is enough space for sentinels. */
1209 	vertexCount += MAX( 8, tess->alloc.extraVertices );
1210 
1211 	pq = tess->pq = pqNewPriorityQ( &tess->alloc, vertexCount, (int (*)(PQkey, PQkey)) tesvertLeq );
1212 	if (pq == NULL) return 0;
1213 
1214 	vHead = &tess->mesh->vHead;
1215 	for( v = vHead->next; v != vHead; v = v->next ) {
1216 		v->pqHandle = pqInsert( &tess->alloc, pq, v );
1217 		if (v->pqHandle == INV_HANDLE)
1218 			break;
1219 	}
1220 	if (v != vHead || !pqInit( &tess->alloc, pq ) ) {
1221 		pqDeletePriorityQ( &tess->alloc, tess->pq );
1222 		tess->pq = NULL;
1223 		return 0;
1224 	}
1225 
1226 	return 1;
1227 }
1228 
1229 
DonePriorityQ(TESStesselator * tess)1230 static void DonePriorityQ( TESStesselator *tess )
1231 {
1232 	pqDeletePriorityQ( &tess->alloc, tess->pq );
1233 }
1234 
1235 
RemoveDegenerateFaces(TESStesselator * tess,TESSmesh * mesh)1236 static int RemoveDegenerateFaces( TESStesselator *tess, TESSmesh *mesh )
1237 /*
1238 * Delete any degenerate faces with only two edges.  WalkDirtyRegions()
1239 * will catch almost all of these, but it won't catch degenerate faces
1240 * produced by splice operations on already-processed edges.
1241 * The two places this can happen are in FinishLeftRegions(), when
1242 * we splice in a "temporary" edge produced by ConnectRightVertex(),
1243 * and in CheckForLeftSplice(), where we splice already-processed
1244 * edges to ensure that our dictionary invariants are not violated
1245 * by numerical errors.
1246 *
1247 * In both these cases it is *very* dangerous to delete the offending
1248 * edge at the time, since one of the routines further up the stack
1249 * will sometimes be keeping a pointer to that edge.
1250 */
1251 {
1252 	TESSface *f, *fNext;
1253 	TESShalfEdge *e;
1254 
1255 	/*LINTED*/
1256 	for( f = mesh->fHead.next; f != &mesh->fHead; f = fNext ) {
1257 		fNext = f->next;
1258 		e = f->anEdge;
1259 		assert( e->Lnext != e );
1260 
1261 		if( e->Lnext->Lnext == e ) {
1262 			/* A face with only two edges */
1263 			AddWinding( e->Onext, e );
1264 			if ( !tessMeshDelete( tess->mesh, e ) ) return 0;
1265 		}
1266 	}
1267 	return 1;
1268 }
1269 
tessComputeInterior(TESStesselator * tess)1270 int tessComputeInterior( TESStesselator *tess )
1271 /*
1272 * tessComputeInterior( tess ) computes the planar arrangement specified
1273 * by the given contours, and further subdivides this arrangement
1274 * into regions.  Each region is marked "inside" if it belongs
1275 * to the polygon, according to the rule given by tess->windingRule.
1276 * Each interior region is guaranteed be monotone.
1277 */
1278 {
1279 	TESSvertex *v, *vNext;
1280 
1281 	/* Each vertex defines an event for our sweep line.  Start by inserting
1282 	* all the vertices in a priority queue.  Events are processed in
1283 	* lexicographic order, ie.
1284 	*
1285 	*	e1 < e2  iff  e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y)
1286 	*/
1287 	RemoveDegenerateEdges( tess );
1288 	if ( !InitPriorityQ( tess ) ) return 0; /* if error */
1289 	InitEdgeDict( tess );
1290 
1291 	while( (v = (TESSvertex *)pqExtractMin( tess->pq )) != NULL ) {
1292 		for( ;; ) {
1293 			vNext = (TESSvertex *)pqMinimum( tess->pq );
1294 			if( vNext == NULL || ! VertEq( vNext, v )) break;
1295 
1296 			/* Merge together all vertices at exactly the same location.
1297 			* This is more efficient than processing them one at a time,
1298 			* simplifies the code (see ConnectLeftDegenerate), and is also
1299 			* important for correct handling of certain degenerate cases.
1300 			* For example, suppose there are two identical edges A and B
1301 			* that belong to different contours (so without this code they would
1302 			* be processed by separate sweep events).  Suppose another edge C
1303 			* crosses A and B from above.  When A is processed, we split it
1304 			* at its intersection point with C.  However this also splits C,
1305 			* so when we insert B we may compute a slightly different
1306 			* intersection point.  This might leave two edges with a small
1307 			* gap between them.  This kind of error is especially obvious
1308 			* when using boundary extraction (TESS_BOUNDARY_ONLY).
1309 			*/
1310 			vNext = (TESSvertex *)pqExtractMin( tess->pq );
1311 			SpliceMergeVertices( tess, v->anEdge, vNext->anEdge );
1312 		}
1313 		SweepEvent( tess, v );
1314 	}
1315 
1316 	/* Set tess->event for debugging purposes */
1317 	tess->event = ((ActiveRegion *) dictKey( dictMin( tess->dict )))->eUp->Org;
1318 	DebugEvent( tess );
1319 	DoneEdgeDict( tess );
1320 	DonePriorityQ( tess );
1321 
1322 	if ( !RemoveDegenerateFaces( tess, tess->mesh ) ) return 0;
1323 	tessMeshCheckMesh( tess->mesh );
1324 
1325 	return 1;
1326 }
1327