webservices: Add support for double records in the writer.
[wine.git] / dlls / glu32 / sweep.c
bloba909e2be33bc87330d18e6eecbea7fab5f9c8edd
1 /*
2 * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3 * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice including the dates of first publication and
13 * either this permission notice or a reference to
14 * http://oss.sgi.com/projects/FreeB/
15 * shall be included in all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
22 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
25 * Except as contained in this notice, the name of Silicon Graphics, Inc.
26 * shall not be used in advertising or otherwise to promote the sale, use or
27 * other dealings in this Software without prior written authorization from
28 * Silicon Graphics, Inc.
31 ** Author: Eric Veach, July 1994.
35 #include <stdarg.h>
36 #include <assert.h>
37 #include <setjmp.h> /* longjmp */
38 #include <limits.h> /* LONG_MAX */
40 #include "windef.h"
41 #include "winbase.h"
43 #include "mesh.h"
44 #include "tess.h"
46 /* dictionary functions (used to be in dict.c) */
48 typedef void *DictKey;
49 typedef struct DictNode DictNode;
51 #define dictKey(n) ((n)->key)
52 #define dictSucc(n) ((n)->next)
53 #define dictPred(n) ((n)->prev)
54 #define dictMin(d) ((d)->head.next)
55 #define dictMax(d) ((d)->head.prev)
56 #define dictInsert(d,k) (dictInsertBefore((d),&(d)->head,(k)))
58 struct DictNode {
59 DictKey key;
60 DictNode *next;
61 DictNode *prev;
64 struct Dict {
65 DictNode head;
66 void *frame;
67 int (*leq)(void *frame, DictKey key1, DictKey key2);
70 static Dict *dictNewDict( void *frame,
71 int (*leq)(void *frame, DictKey key1, DictKey key2) )
73 Dict *dict = HeapAlloc( GetProcessHeap(), 0, sizeof( Dict ));
74 DictNode *head;
76 if (dict == NULL) return NULL;
78 head = &dict->head;
80 head->key = NULL;
81 head->next = head;
82 head->prev = head;
84 dict->frame = frame;
85 dict->leq = leq;
87 return dict;
90 static void dictDeleteDict( Dict *dict )
92 DictNode *node, *next;
94 for( node = dict->head.next; node != &dict->head; node = next ) {
95 next = node->next;
96 HeapFree( GetProcessHeap(), 0, node );
98 HeapFree( GetProcessHeap(), 0, dict );
101 static DictNode *dictInsertBefore( Dict *dict, DictNode *node, DictKey key )
103 DictNode *newNode;
105 do {
106 node = node->prev;
107 } while( node->key != NULL && ! (*dict->leq)(dict->frame, node->key, key));
109 newNode = HeapAlloc( GetProcessHeap(), 0, sizeof( DictNode ));
110 if (newNode == NULL) return NULL;
112 newNode->key = key;
113 newNode->next = node->next;
114 node->next->prev = newNode;
115 newNode->prev = node;
116 node->next = newNode;
118 return newNode;
121 static void dictDelete( Dict *dict, DictNode *node )
123 node->next->prev = node->prev;
124 node->prev->next = node->next;
125 HeapFree( GetProcessHeap(), 0, node );
128 static DictNode *dictSearch( Dict *dict, DictKey key )
130 DictNode *node = &dict->head;
132 do {
133 node = node->next;
134 } while( node->key != NULL && ! (*dict->leq)(dict->frame, key, node->key));
136 return node;
140 /* For each pair of adjacent edges crossing the sweep line, there is
141 * an ActiveRegion to represent the region between them. The active
142 * regions are kept in sorted order in a dynamic dictionary. As the
143 * sweep line crosses each vertex, we update the affected regions.
146 struct ActiveRegion {
147 GLUhalfEdge *eUp; /* upper edge, directed right to left */
148 DictNode *nodeUp; /* dictionary node corresponding to eUp */
149 int windingNumber; /* used to determine which regions are
150 * inside the polygon */
151 GLboolean inside; /* is this region inside the polygon? */
152 GLboolean sentinel; /* marks fake edges at t = +/-infinity */
153 GLboolean dirty; /* marks regions where the upper or lower
154 * edge has changed, but we haven't checked
155 * whether they intersect yet */
156 GLboolean fixUpperEdge; /* marks temporary edges introduced when
157 * we process a "right vertex" (one without
158 * any edges leaving to the right) */
161 #define RegionBelow(r) ((ActiveRegion *) dictKey(dictPred((r)->nodeUp)))
162 #define RegionAbove(r) ((ActiveRegion *) dictKey(dictSucc((r)->nodeUp)))
165 #define DebugEvent( tess )
168 * Invariants for the Edge Dictionary.
169 * - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2)
170 * at any valid location of the sweep event
171 * - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2
172 * share a common endpoint
173 * - for each e, e->Dst has been processed, but not e->Org
174 * - each edge e satisfies VertLeq(e->Dst,event) && VertLeq(event,e->Org)
175 * where "event" is the current sweep line event.
176 * - no edge e has zero length
178 * Invariants for the Mesh (the processed portion).
179 * - the portion of the mesh left of the sweep line is a planar graph,
180 * ie. there is *some* way to embed it in the plane
181 * - no processed edge has zero length
182 * - no two processed vertices have identical coordinates
183 * - each "inside" region is monotone, ie. can be broken into two chains
184 * of monotonically increasing vertices according to VertLeq(v1,v2)
185 * - a non-invariant: these chains may intersect (very slightly)
187 * Invariants for the Sweep.
188 * - if none of the edges incident to the event vertex have an activeRegion
189 * (ie. none of these edges are in the edge dictionary), then the vertex
190 * has only right-going edges.
191 * - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced
192 * by ConnectRightVertex), then it is the only right-going edge from
193 * its associated vertex. (This says that these edges exist only
194 * when it is necessary.)
197 #undef MAX
198 #undef MIN
199 #define MAX(x,y) ((x) >= (y) ? (x) : (y))
200 #define MIN(x,y) ((x) <= (y) ? (x) : (y))
202 /* When we merge two edges into one, we need to compute the combined
203 * winding of the new edge.
205 #define AddWinding(eDst,eSrc) (eDst->winding += eSrc->winding, \
206 eDst->Sym->winding += eSrc->Sym->winding)
208 static void SweepEvent( GLUtesselator *tess, GLUvertex *vEvent );
209 static void WalkDirtyRegions( GLUtesselator *tess, ActiveRegion *regUp );
210 static int CheckForRightSplice( GLUtesselator *tess, ActiveRegion *regUp );
212 static int EdgeLeq( GLUtesselator *tess, ActiveRegion *reg1,
213 ActiveRegion *reg2 )
215 * Both edges must be directed from right to left (this is the canonical
216 * direction for the upper edge of each region).
218 * The strategy is to evaluate a "t" value for each edge at the
219 * current sweep line position, given by tess->event. The calculations
220 * are designed to be very stable, but of course they are not perfect.
222 * Special case: if both edge destinations are at the sweep event,
223 * we sort the edges by slope (they would otherwise compare equally).
226 GLUvertex *event = tess->event;
227 GLUhalfEdge *e1, *e2;
228 GLdouble t1, t2;
230 e1 = reg1->eUp;
231 e2 = reg2->eUp;
233 if( e1->Dst == event ) {
234 if( e2->Dst == event ) {
235 /* Two edges right of the sweep line which meet at the sweep event.
236 * Sort them by slope.
238 if( VertLeq( e1->Org, e2->Org )) {
239 return EdgeSign( e2->Dst, e1->Org, e2->Org ) <= 0;
241 return EdgeSign( e1->Dst, e2->Org, e1->Org ) >= 0;
243 return EdgeSign( e2->Dst, event, e2->Org ) <= 0;
245 if( e2->Dst == event ) {
246 return EdgeSign( e1->Dst, event, e1->Org ) >= 0;
249 /* General case - compute signed distance *from* e1, e2 to event */
250 t1 = EdgeEval( e1->Dst, event, e1->Org );
251 t2 = EdgeEval( e2->Dst, event, e2->Org );
252 return (t1 >= t2);
256 static void DeleteRegion( GLUtesselator *tess, ActiveRegion *reg )
258 if( reg->fixUpperEdge ) {
259 /* It was created with zero winding number, so it better be
260 * deleted with zero winding number (ie. it better not get merged
261 * with a real edge).
263 assert( reg->eUp->winding == 0 );
265 reg->eUp->activeRegion = NULL;
266 dictDelete( tess->dict, reg->nodeUp );
267 HeapFree( GetProcessHeap(), 0, reg );
271 static int FixUpperEdge( ActiveRegion *reg, GLUhalfEdge *newEdge )
273 * Replace an upper edge which needs fixing (see ConnectRightVertex).
276 assert( reg->fixUpperEdge );
277 if ( !__gl_meshDelete( reg->eUp ) ) return 0;
278 reg->fixUpperEdge = FALSE;
279 reg->eUp = newEdge;
280 newEdge->activeRegion = reg;
282 return 1;
285 static ActiveRegion *TopLeftRegion( ActiveRegion *reg )
287 GLUvertex *org = reg->eUp->Org;
288 GLUhalfEdge *e;
290 /* Find the region above the uppermost edge with the same origin */
291 do {
292 reg = RegionAbove( reg );
293 } while( reg->eUp->Org == org );
295 /* If the edge above was a temporary edge introduced by ConnectRightVertex,
296 * now is the time to fix it.
298 if( reg->fixUpperEdge ) {
299 e = __gl_meshConnect( RegionBelow(reg)->eUp->Sym, reg->eUp->Lnext );
300 if (e == NULL) return NULL;
301 if ( !FixUpperEdge( reg, e ) ) return NULL;
302 reg = RegionAbove( reg );
304 return reg;
307 static ActiveRegion *TopRightRegion( ActiveRegion *reg )
309 GLUvertex *dst = reg->eUp->Dst;
311 /* Find the region above the uppermost edge with the same destination */
312 do {
313 reg = RegionAbove( reg );
314 } while( reg->eUp->Dst == dst );
315 return reg;
318 static ActiveRegion *AddRegionBelow( GLUtesselator *tess,
319 ActiveRegion *regAbove,
320 GLUhalfEdge *eNewUp )
322 * Add a new active region to the sweep line, *somewhere* below "regAbove"
323 * (according to where the new edge belongs in the sweep-line dictionary).
324 * The upper edge of the new region will be "eNewUp".
325 * Winding number and "inside" flag are not updated.
328 ActiveRegion *regNew = HeapAlloc( GetProcessHeap(), 0, sizeof( ActiveRegion ));
329 if (regNew == NULL) longjmp(tess->env,1);
331 regNew->eUp = eNewUp;
332 regNew->nodeUp = dictInsertBefore( tess->dict, regAbove->nodeUp, regNew );
333 if (regNew->nodeUp == NULL) longjmp(tess->env,1);
334 regNew->fixUpperEdge = FALSE;
335 regNew->sentinel = FALSE;
336 regNew->dirty = FALSE;
338 eNewUp->activeRegion = regNew;
339 return regNew;
342 static GLboolean IsWindingInside( GLUtesselator *tess, int n )
344 switch( tess->windingRule ) {
345 case GLU_TESS_WINDING_ODD:
346 return (n & 1);
347 case GLU_TESS_WINDING_NONZERO:
348 return (n != 0);
349 case GLU_TESS_WINDING_POSITIVE:
350 return (n > 0);
351 case GLU_TESS_WINDING_NEGATIVE:
352 return (n < 0);
353 case GLU_TESS_WINDING_ABS_GEQ_TWO:
354 return (n >= 2) || (n <= -2);
356 /*LINTED*/
357 assert( FALSE );
358 /*NOTREACHED*/
359 return GL_FALSE; /* avoid compiler complaints */
363 static void ComputeWinding( GLUtesselator *tess, ActiveRegion *reg )
365 reg->windingNumber = RegionAbove(reg)->windingNumber + reg->eUp->winding;
366 reg->inside = IsWindingInside( tess, reg->windingNumber );
370 static void FinishRegion( GLUtesselator *tess, ActiveRegion *reg )
372 * Delete a region from the sweep line. This happens when the upper
373 * and lower chains of a region meet (at a vertex on the sweep line).
374 * The "inside" flag is copied to the appropriate mesh face (we could
375 * not do this before -- since the structure of the mesh is always
376 * changing, this face may not have even existed until now).
379 GLUhalfEdge *e = reg->eUp;
380 GLUface *f = e->Lface;
382 f->inside = reg->inside;
383 f->anEdge = e; /* optimization for __gl_meshTessellateMonoRegion() */
384 DeleteRegion( tess, reg );
388 static GLUhalfEdge *FinishLeftRegions( GLUtesselator *tess,
389 ActiveRegion *regFirst, ActiveRegion *regLast )
391 * We are given a vertex with one or more left-going edges. All affected
392 * edges should be in the edge dictionary. Starting at regFirst->eUp,
393 * we walk down deleting all regions where both edges have the same
394 * origin vOrg. At the same time we copy the "inside" flag from the
395 * active region to the face, since at this point each face will belong
396 * to at most one region (this was not necessarily true until this point
397 * in the sweep). The walk stops at the region above regLast; if regLast
398 * is NULL we walk as far as possible. At the same time we relink the
399 * mesh if necessary, so that the ordering of edges around vOrg is the
400 * same as in the dictionary.
403 ActiveRegion *reg, *regPrev;
404 GLUhalfEdge *e, *ePrev;
406 regPrev = regFirst;
407 ePrev = regFirst->eUp;
408 while( regPrev != regLast ) {
409 regPrev->fixUpperEdge = FALSE; /* placement was OK */
410 reg = RegionBelow( regPrev );
411 e = reg->eUp;
412 if( e->Org != ePrev->Org ) {
413 if( ! reg->fixUpperEdge ) {
414 /* Remove the last left-going edge. Even though there are no further
415 * edges in the dictionary with this origin, there may be further
416 * such edges in the mesh (if we are adding left edges to a vertex
417 * that has already been processed). Thus it is important to call
418 * FinishRegion rather than just DeleteRegion.
420 FinishRegion( tess, regPrev );
421 break;
423 /* If the edge below was a temporary edge introduced by
424 * ConnectRightVertex, now is the time to fix it.
426 e = __gl_meshConnect( ePrev->Lprev, e->Sym );
427 if (e == NULL) longjmp(tess->env,1);
428 if ( !FixUpperEdge( reg, e ) ) longjmp(tess->env,1);
431 /* Relink edges so that ePrev->Onext == e */
432 if( ePrev->Onext != e ) {
433 if ( !__gl_meshSplice( e->Oprev, e ) ) longjmp(tess->env,1);
434 if ( !__gl_meshSplice( ePrev, e ) ) longjmp(tess->env,1);
436 FinishRegion( tess, regPrev ); /* may change reg->eUp */
437 ePrev = reg->eUp;
438 regPrev = reg;
440 return ePrev;
444 static void AddRightEdges( GLUtesselator *tess, ActiveRegion *regUp,
445 GLUhalfEdge *eFirst, GLUhalfEdge *eLast, GLUhalfEdge *eTopLeft,
446 GLboolean cleanUp )
448 * Purpose: insert right-going edges into the edge dictionary, and update
449 * winding numbers and mesh connectivity appropriately. All right-going
450 * edges share a common origin vOrg. Edges are inserted CCW starting at
451 * eFirst; the last edge inserted is eLast->Oprev. If vOrg has any
452 * left-going edges already processed, then eTopLeft must be the edge
453 * such that an imaginary upward vertical segment from vOrg would be
454 * contained between eTopLeft->Oprev and eTopLeft; otherwise eTopLeft
455 * should be NULL.
458 ActiveRegion *reg, *regPrev;
459 GLUhalfEdge *e, *ePrev;
460 int firstTime = TRUE;
462 /* Insert the new right-going edges in the dictionary */
463 e = eFirst;
464 do {
465 assert( VertLeq( e->Org, e->Dst ));
466 AddRegionBelow( tess, regUp, e->Sym );
467 e = e->Onext;
468 } while ( e != eLast );
470 /* Walk *all* right-going edges from e->Org, in the dictionary order,
471 * updating the winding numbers of each region, and re-linking the mesh
472 * edges to match the dictionary ordering (if necessary).
474 if( eTopLeft == NULL ) {
475 eTopLeft = RegionBelow( regUp )->eUp->Rprev;
477 regPrev = regUp;
478 ePrev = eTopLeft;
479 for( ;; ) {
480 reg = RegionBelow( regPrev );
481 e = reg->eUp->Sym;
482 if( e->Org != ePrev->Org ) break;
484 if( e->Onext != ePrev ) {
485 /* Unlink e from its current position, and relink below ePrev */
486 if ( !__gl_meshSplice( e->Oprev, e ) ) longjmp(tess->env,1);
487 if ( !__gl_meshSplice( ePrev->Oprev, e ) ) longjmp(tess->env,1);
489 /* Compute the winding number and "inside" flag for the new regions */
490 reg->windingNumber = regPrev->windingNumber - e->winding;
491 reg->inside = IsWindingInside( tess, reg->windingNumber );
493 /* Check for two outgoing edges with same slope -- process these
494 * before any intersection tests (see example in __gl_computeInterior).
496 regPrev->dirty = TRUE;
497 if( ! firstTime && CheckForRightSplice( tess, regPrev )) {
498 AddWinding( e, ePrev );
499 DeleteRegion( tess, regPrev );
500 if ( !__gl_meshDelete( ePrev ) ) longjmp(tess->env,1);
502 firstTime = FALSE;
503 regPrev = reg;
504 ePrev = e;
506 regPrev->dirty = TRUE;
507 assert( regPrev->windingNumber - e->winding == reg->windingNumber );
509 if( cleanUp ) {
510 /* Check for intersections between newly adjacent edges. */
511 WalkDirtyRegions( tess, regPrev );
516 static void CallCombine( GLUtesselator *tess, GLUvertex *isect,
517 void *data[4], GLfloat weights[4], int needed )
519 GLdouble coords[3];
521 /* Copy coord data in case the callback changes it. */
522 coords[0] = isect->coords[0];
523 coords[1] = isect->coords[1];
524 coords[2] = isect->coords[2];
526 isect->data = NULL;
527 CALL_COMBINE_OR_COMBINE_DATA( coords, data, weights, &isect->data );
528 if( isect->data == NULL ) {
529 if( ! needed ) {
530 isect->data = data[0];
531 } else if( ! tess->fatalError ) {
532 /* The only way fatal error is when two edges are found to intersect,
533 * but the user has not provided the callback necessary to handle
534 * generated intersection points.
536 CALL_ERROR_OR_ERROR_DATA( GLU_TESS_NEED_COMBINE_CALLBACK );
537 tess->fatalError = TRUE;
542 static void SpliceMergeVertices( GLUtesselator *tess, GLUhalfEdge *e1,
543 GLUhalfEdge *e2 )
545 * Two vertices with idential coordinates are combined into one.
546 * e1->Org is kept, while e2->Org is discarded.
549 void *data[4] = { NULL, NULL, NULL, NULL };
550 GLfloat weights[4] = { 0.5, 0.5, 0.0, 0.0 };
552 data[0] = e1->Org->data;
553 data[1] = e2->Org->data;
554 CallCombine( tess, e1->Org, data, weights, FALSE );
555 if ( !__gl_meshSplice( e1, e2 ) ) longjmp(tess->env,1);
558 static void VertexWeights( GLUvertex *isect, GLUvertex *org, GLUvertex *dst,
559 GLfloat *weights )
561 * Find some weights which describe how the intersection vertex is
562 * a linear combination of "org" and "dest". Each of the two edges
563 * which generated "isect" is allocated 50% of the weight; each edge
564 * splits the weight between its org and dst according to the
565 * relative distance to "isect".
568 GLdouble t1 = VertL1dist( org, isect );
569 GLdouble t2 = VertL1dist( dst, isect );
571 weights[0] = 0.5 * t2 / (t1 + t2);
572 weights[1] = 0.5 * t1 / (t1 + t2);
573 isect->coords[0] += weights[0]*org->coords[0] + weights[1]*dst->coords[0];
574 isect->coords[1] += weights[0]*org->coords[1] + weights[1]*dst->coords[1];
575 isect->coords[2] += weights[0]*org->coords[2] + weights[1]*dst->coords[2];
579 static void GetIntersectData( GLUtesselator *tess, GLUvertex *isect,
580 GLUvertex *orgUp, GLUvertex *dstUp,
581 GLUvertex *orgLo, GLUvertex *dstLo )
583 * We've computed a new intersection point, now we need a "data" pointer
584 * from the user so that we can refer to this new vertex in the
585 * rendering callbacks.
588 void *data[4];
589 GLfloat weights[4];
591 data[0] = orgUp->data;
592 data[1] = dstUp->data;
593 data[2] = orgLo->data;
594 data[3] = dstLo->data;
596 isect->coords[0] = isect->coords[1] = isect->coords[2] = 0;
597 VertexWeights( isect, orgUp, dstUp, &weights[0] );
598 VertexWeights( isect, orgLo, dstLo, &weights[2] );
600 CallCombine( tess, isect, data, weights, TRUE );
603 static int CheckForRightSplice( GLUtesselator *tess, ActiveRegion *regUp )
605 * Check the upper and lower edge of "regUp", to make sure that the
606 * eUp->Org is above eLo, or eLo->Org is below eUp (depending on which
607 * origin is leftmost).
609 * The main purpose is to splice right-going edges with the same
610 * dest vertex and nearly identical slopes (ie. we can't distinguish
611 * the slopes numerically). However the splicing can also help us
612 * to recover from numerical errors. For example, suppose at one
613 * point we checked eUp and eLo, and decided that eUp->Org is barely
614 * above eLo. Then later, we split eLo into two edges (eg. from
615 * a splice operation like this one). This can change the result of
616 * our test so that now eUp->Org is incident to eLo, or barely below it.
617 * We must correct this condition to maintain the dictionary invariants.
619 * One possibility is to check these edges for intersection again
620 * (ie. CheckForIntersect). This is what we do if possible. However
621 * CheckForIntersect requires that tess->event lies between eUp and eLo,
622 * so that it has something to fall back on when the intersection
623 * calculation gives us an unusable answer. So, for those cases where
624 * we can't check for intersection, this routine fixes the problem
625 * by just splicing the offending vertex into the other edge.
626 * This is a guaranteed solution, no matter how degenerate things get.
627 * Basically this is a combinatorial solution to a numerical problem.
630 ActiveRegion *regLo = RegionBelow(regUp);
631 GLUhalfEdge *eUp = regUp->eUp;
632 GLUhalfEdge *eLo = regLo->eUp;
634 if( VertLeq( eUp->Org, eLo->Org )) {
635 if( EdgeSign( eLo->Dst, eUp->Org, eLo->Org ) > 0 ) return FALSE;
637 /* eUp->Org appears to be below eLo */
638 if( ! VertEq( eUp->Org, eLo->Org )) {
639 /* Splice eUp->Org into eLo */
640 if ( __gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
641 if ( !__gl_meshSplice( eUp, eLo->Oprev ) ) longjmp(tess->env,1);
642 regUp->dirty = regLo->dirty = TRUE;
644 } else if( eUp->Org != eLo->Org ) {
645 /* merge the two vertices, discarding eUp->Org */
646 __gl_pqSortDelete( tess->pq, eUp->Org->pqHandle );
647 SpliceMergeVertices( tess, eLo->Oprev, eUp );
649 } else {
650 if( EdgeSign( eUp->Dst, eLo->Org, eUp->Org ) < 0 ) return FALSE;
652 /* eLo->Org appears to be above eUp, so splice eLo->Org into eUp */
653 RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
654 if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
655 if ( !__gl_meshSplice( eLo->Oprev, eUp ) ) longjmp(tess->env,1);
657 return TRUE;
660 static int CheckForLeftSplice( GLUtesselator *tess, ActiveRegion *regUp )
662 * Check the upper and lower edge of "regUp", to make sure that the
663 * eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which
664 * destination is rightmost).
666 * Theoretically, this should always be true. However, splitting an edge
667 * into two pieces can change the results of previous tests. For example,
668 * suppose at one point we checked eUp and eLo, and decided that eUp->Dst
669 * is barely above eLo. Then later, we split eLo into two edges (eg. from
670 * a splice operation like this one). This can change the result of
671 * the test so that now eUp->Dst is incident to eLo, or barely below it.
672 * We must correct this condition to maintain the dictionary invariants
673 * (otherwise new edges might get inserted in the wrong place in the
674 * dictionary, and bad stuff will happen).
676 * We fix the problem by just splicing the offending vertex into the
677 * other edge.
680 ActiveRegion *regLo = RegionBelow(regUp);
681 GLUhalfEdge *eUp = regUp->eUp;
682 GLUhalfEdge *eLo = regLo->eUp;
683 GLUhalfEdge *e;
685 assert( ! VertEq( eUp->Dst, eLo->Dst ));
687 if( VertLeq( eUp->Dst, eLo->Dst )) {
688 if( EdgeSign( eUp->Dst, eLo->Dst, eUp->Org ) < 0 ) return FALSE;
690 /* eLo->Dst is above eUp, so splice eLo->Dst into eUp */
691 RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
692 e = __gl_meshSplitEdge( eUp );
693 if (e == NULL) longjmp(tess->env,1);
694 if ( !__gl_meshSplice( eLo->Sym, e ) ) longjmp(tess->env,1);
695 e->Lface->inside = regUp->inside;
696 } else {
697 if( EdgeSign( eLo->Dst, eUp->Dst, eLo->Org ) > 0 ) return FALSE;
699 /* eUp->Dst is below eLo, so splice eUp->Dst into eLo */
700 regUp->dirty = regLo->dirty = TRUE;
701 e = __gl_meshSplitEdge( eLo );
702 if (e == NULL) longjmp(tess->env,1);
703 if ( !__gl_meshSplice( eUp->Lnext, eLo->Sym ) ) longjmp(tess->env,1);
704 e->Rface->inside = regUp->inside;
706 return TRUE;
710 static int CheckForIntersect( GLUtesselator *tess, ActiveRegion *regUp )
712 * Check the upper and lower edges of the given region to see if
713 * they intersect. If so, create the intersection and add it
714 * to the data structures.
716 * Returns TRUE if adding the new intersection resulted in a recursive
717 * call to AddRightEdges(); in this case all "dirty" regions have been
718 * checked for intersections, and possibly regUp has been deleted.
721 ActiveRegion *regLo = RegionBelow(regUp);
722 GLUhalfEdge *eUp = regUp->eUp;
723 GLUhalfEdge *eLo = regLo->eUp;
724 GLUvertex *orgUp = eUp->Org;
725 GLUvertex *orgLo = eLo->Org;
726 GLUvertex *dstUp = eUp->Dst;
727 GLUvertex *dstLo = eLo->Dst;
728 GLdouble tMinUp, tMaxLo;
729 GLUvertex isect, *orgMin;
730 GLUhalfEdge *e;
732 assert( ! VertEq( dstLo, dstUp ));
733 assert( EdgeSign( dstUp, tess->event, orgUp ) <= 0 );
734 assert( EdgeSign( dstLo, tess->event, orgLo ) >= 0 );
735 assert( orgUp != tess->event && orgLo != tess->event );
736 assert( ! regUp->fixUpperEdge && ! regLo->fixUpperEdge );
738 if( orgUp == orgLo ) return FALSE; /* right endpoints are the same */
740 tMinUp = MIN( orgUp->t, dstUp->t );
741 tMaxLo = MAX( orgLo->t, dstLo->t );
742 if( tMinUp > tMaxLo ) return FALSE; /* t ranges do not overlap */
744 if( VertLeq( orgUp, orgLo )) {
745 if( EdgeSign( dstLo, orgUp, orgLo ) > 0 ) return FALSE;
746 } else {
747 if( EdgeSign( dstUp, orgLo, orgUp ) < 0 ) return FALSE;
750 /* At this point the edges intersect, at least marginally */
751 DebugEvent( tess );
753 __gl_edgeIntersect( dstUp, orgUp, dstLo, orgLo, &isect );
754 /* The following properties are guaranteed: */
755 assert( MIN( orgUp->t, dstUp->t ) <= isect.t );
756 assert( isect.t <= MAX( orgLo->t, dstLo->t ));
757 assert( MIN( dstLo->s, dstUp->s ) <= isect.s );
758 assert( isect.s <= MAX( orgLo->s, orgUp->s ));
760 if( VertLeq( &isect, tess->event )) {
761 /* The intersection point lies slightly to the left of the sweep line,
762 * so move it until it''s slightly to the right of the sweep line.
763 * (If we had perfect numerical precision, this would never happen
764 * in the first place). The easiest and safest thing to do is
765 * replace the intersection by tess->event.
767 isect.s = tess->event->s;
768 isect.t = tess->event->t;
770 /* Similarly, if the computed intersection lies to the right of the
771 * rightmost origin (which should rarely happen), it can cause
772 * unbelievable inefficiency on sufficiently degenerate inputs.
773 * (If you have the test program, try running test54.d with the
774 * "X zoom" option turned on).
776 orgMin = VertLeq( orgUp, orgLo ) ? orgUp : orgLo;
777 if( VertLeq( orgMin, &isect )) {
778 isect.s = orgMin->s;
779 isect.t = orgMin->t;
782 if( VertEq( &isect, orgUp ) || VertEq( &isect, orgLo )) {
783 /* Easy case -- intersection at one of the right endpoints */
784 (void) CheckForRightSplice( tess, regUp );
785 return FALSE;
788 if( (! VertEq( dstUp, tess->event )
789 && EdgeSign( dstUp, tess->event, &isect ) >= 0)
790 || (! VertEq( dstLo, tess->event )
791 && EdgeSign( dstLo, tess->event, &isect ) <= 0 ))
793 /* Very unusual -- the new upper or lower edge would pass on the
794 * wrong side of the sweep event, or through it. This can happen
795 * due to very small numerical errors in the intersection calculation.
797 if( dstLo == tess->event ) {
798 /* Splice dstLo into eUp, and process the new region(s) */
799 if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
800 if ( !__gl_meshSplice( eLo->Sym, eUp ) ) longjmp(tess->env,1);
801 regUp = TopLeftRegion( regUp );
802 if (regUp == NULL) longjmp(tess->env,1);
803 eUp = RegionBelow(regUp)->eUp;
804 FinishLeftRegions( tess, RegionBelow(regUp), regLo );
805 AddRightEdges( tess, regUp, eUp->Oprev, eUp, eUp, TRUE );
806 return TRUE;
808 if( dstUp == tess->event ) {
809 /* Splice dstUp into eLo, and process the new region(s) */
810 if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
811 if ( !__gl_meshSplice( eUp->Lnext, eLo->Oprev ) ) longjmp(tess->env,1);
812 regLo = regUp;
813 regUp = TopRightRegion( regUp );
814 e = RegionBelow(regUp)->eUp->Rprev;
815 regLo->eUp = eLo->Oprev;
816 eLo = FinishLeftRegions( tess, regLo, NULL );
817 AddRightEdges( tess, regUp, eLo->Onext, eUp->Rprev, e, TRUE );
818 return TRUE;
820 /* Special case: called from ConnectRightVertex. If either
821 * edge passes on the wrong side of tess->event, split it
822 * (and wait for ConnectRightVertex to splice it appropriately).
824 if( EdgeSign( dstUp, tess->event, &isect ) >= 0 ) {
825 RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
826 if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
827 eUp->Org->s = tess->event->s;
828 eUp->Org->t = tess->event->t;
830 if( EdgeSign( dstLo, tess->event, &isect ) <= 0 ) {
831 regUp->dirty = regLo->dirty = TRUE;
832 if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
833 eLo->Org->s = tess->event->s;
834 eLo->Org->t = tess->event->t;
836 /* leave the rest for ConnectRightVertex */
837 return FALSE;
840 /* General case -- split both edges, splice into new vertex.
841 * When we do the splice operation, the order of the arguments is
842 * arbitrary as far as correctness goes. However, when the operation
843 * creates a new face, the work done is proportional to the size of
844 * the new face. We expect the faces in the processed part of
845 * the mesh (ie. eUp->Lface) to be smaller than the faces in the
846 * unprocessed original contours (which will be eLo->Oprev->Lface).
848 if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
849 if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
850 if ( !__gl_meshSplice( eLo->Oprev, eUp ) ) longjmp(tess->env,1);
851 eUp->Org->s = isect.s;
852 eUp->Org->t = isect.t;
853 eUp->Org->pqHandle = __gl_pqSortInsert( tess->pq, eUp->Org );
854 if (eUp->Org->pqHandle == LONG_MAX) {
855 __gl_pqSortDeletePriorityQ(tess->pq);
856 tess->pq = NULL;
857 longjmp(tess->env,1);
859 GetIntersectData( tess, eUp->Org, orgUp, dstUp, orgLo, dstLo );
860 RegionAbove(regUp)->dirty = regUp->dirty = regLo->dirty = TRUE;
861 return FALSE;
864 static void WalkDirtyRegions( GLUtesselator *tess, ActiveRegion *regUp )
866 * When the upper or lower edge of any region changes, the region is
867 * marked "dirty". This routine walks through all the dirty regions
868 * and makes sure that the dictionary invariants are satisfied
869 * (see the comments at the beginning of this file). Of course
870 * new dirty regions can be created as we make changes to restore
871 * the invariants.
874 ActiveRegion *regLo = RegionBelow(regUp);
875 GLUhalfEdge *eUp, *eLo;
877 for( ;; ) {
878 /* Find the lowest dirty region (we walk from the bottom up). */
879 while( regLo->dirty ) {
880 regUp = regLo;
881 regLo = RegionBelow(regLo);
883 if( ! regUp->dirty ) {
884 regLo = regUp;
885 regUp = RegionAbove( regUp );
886 if( regUp == NULL || ! regUp->dirty ) {
887 /* We've walked all the dirty regions */
888 return;
891 regUp->dirty = FALSE;
892 eUp = regUp->eUp;
893 eLo = regLo->eUp;
895 if( eUp->Dst != eLo->Dst ) {
896 /* Check that the edge ordering is obeyed at the Dst vertices. */
897 if( CheckForLeftSplice( tess, regUp )) {
899 /* If the upper or lower edge was marked fixUpperEdge, then
900 * we no longer need it (since these edges are needed only for
901 * vertices which otherwise have no right-going edges).
903 if( regLo->fixUpperEdge ) {
904 DeleteRegion( tess, regLo );
905 if ( !__gl_meshDelete( eLo ) ) longjmp(tess->env,1);
906 regLo = RegionBelow( regUp );
907 eLo = regLo->eUp;
908 } else if( regUp->fixUpperEdge ) {
909 DeleteRegion( tess, regUp );
910 if ( !__gl_meshDelete( eUp ) ) longjmp(tess->env,1);
911 regUp = RegionAbove( regLo );
912 eUp = regUp->eUp;
916 if( eUp->Org != eLo->Org ) {
917 if( eUp->Dst != eLo->Dst
918 && ! regUp->fixUpperEdge && ! regLo->fixUpperEdge
919 && (eUp->Dst == tess->event || eLo->Dst == tess->event) )
921 /* When all else fails in CheckForIntersect(), it uses tess->event
922 * as the intersection location. To make this possible, it requires
923 * that tess->event lie between the upper and lower edges, and also
924 * that neither of these is marked fixUpperEdge (since in the worst
925 * case it might splice one of these edges into tess->event, and
926 * violate the invariant that fixable edges are the only right-going
927 * edge from their associated vertex).
929 if( CheckForIntersect( tess, regUp )) {
930 /* WalkDirtyRegions() was called recursively; we're done */
931 return;
933 } else {
934 /* Even though we can't use CheckForIntersect(), the Org vertices
935 * may violate the dictionary edge ordering. Check and correct this.
937 (void) CheckForRightSplice( tess, regUp );
940 if( eUp->Org == eLo->Org && eUp->Dst == eLo->Dst ) {
941 /* A degenerate loop consisting of only two edges -- delete it. */
942 AddWinding( eLo, eUp );
943 DeleteRegion( tess, regUp );
944 if ( !__gl_meshDelete( eUp ) ) longjmp(tess->env,1);
945 regUp = RegionAbove( regLo );
951 static void ConnectRightVertex( GLUtesselator *tess, ActiveRegion *regUp,
952 GLUhalfEdge *eBottomLeft )
954 * Purpose: connect a "right" vertex vEvent (one where all edges go left)
955 * to the unprocessed portion of the mesh. Since there are no right-going
956 * edges, two regions (one above vEvent and one below) are being merged
957 * into one. "regUp" is the upper of these two regions.
959 * There are two reasons for doing this (adding a right-going edge):
960 * - if the two regions being merged are "inside", we must add an edge
961 * to keep them separated (the combined region would not be monotone).
962 * - in any case, we must leave some record of vEvent in the dictionary,
963 * so that we can merge vEvent with features that we have not seen yet.
964 * For example, maybe there is a vertical edge which passes just to
965 * the right of vEvent; we would like to splice vEvent into this edge.
967 * However, we don't want to connect vEvent to just any vertex. We don''t
968 * want the new edge to cross any other edges; otherwise we will create
969 * intersection vertices even when the input data had no self-intersections.
970 * (This is a bad thing; if the user's input data has no intersections,
971 * we don't want to generate any false intersections ourselves.)
973 * Our eventual goal is to connect vEvent to the leftmost unprocessed
974 * vertex of the combined region (the union of regUp and regLo).
975 * But because of unseen vertices with all right-going edges, and also
976 * new vertices which may be created by edge intersections, we don''t
977 * know where that leftmost unprocessed vertex is. In the meantime, we
978 * connect vEvent to the closest vertex of either chain, and mark the region
979 * as "fixUpperEdge". This flag says to delete and reconnect this edge
980 * to the next processed vertex on the boundary of the combined region.
981 * Quite possibly the vertex we connected to will turn out to be the
982 * closest one, in which case we won''t need to make any changes.
985 GLUhalfEdge *eNew;
986 GLUhalfEdge *eTopLeft = eBottomLeft->Onext;
987 ActiveRegion *regLo = RegionBelow(regUp);
988 GLUhalfEdge *eUp = regUp->eUp;
989 GLUhalfEdge *eLo = regLo->eUp;
990 int degenerate = FALSE;
992 if( eUp->Dst != eLo->Dst ) {
993 (void) CheckForIntersect( tess, regUp );
996 /* Possible new degeneracies: upper or lower edge of regUp may pass
997 * through vEvent, or may coincide with new intersection vertex
999 if( VertEq( eUp->Org, tess->event )) {
1000 if ( !__gl_meshSplice( eTopLeft->Oprev, eUp ) ) longjmp(tess->env,1);
1001 regUp = TopLeftRegion( regUp );
1002 if (regUp == NULL) longjmp(tess->env,1);
1003 eTopLeft = RegionBelow( regUp )->eUp;
1004 FinishLeftRegions( tess, RegionBelow(regUp), regLo );
1005 degenerate = TRUE;
1007 if( VertEq( eLo->Org, tess->event )) {
1008 if ( !__gl_meshSplice( eBottomLeft, eLo->Oprev ) ) longjmp(tess->env,1);
1009 eBottomLeft = FinishLeftRegions( tess, regLo, NULL );
1010 degenerate = TRUE;
1012 if( degenerate ) {
1013 AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TRUE );
1014 return;
1017 /* Non-degenerate situation -- need to add a temporary, fixable edge.
1018 * Connect to the closer of eLo->Org, eUp->Org.
1020 if( VertLeq( eLo->Org, eUp->Org )) {
1021 eNew = eLo->Oprev;
1022 } else {
1023 eNew = eUp;
1025 eNew = __gl_meshConnect( eBottomLeft->Lprev, eNew );
1026 if (eNew == NULL) longjmp(tess->env,1);
1028 /* Prevent cleanup, otherwise eNew might disappear before we've even
1029 * had a chance to mark it as a temporary edge.
1031 AddRightEdges( tess, regUp, eNew, eNew->Onext, eNew->Onext, FALSE );
1032 eNew->Sym->activeRegion->fixUpperEdge = TRUE;
1033 WalkDirtyRegions( tess, regUp );
1036 /* Because vertices at exactly the same location are merged together
1037 * before we process the sweep event, some degenerate cases can't occur.
1038 * However if someone eventually makes the modifications required to
1039 * merge features which are close together, the cases below marked
1040 * TOLERANCE_NONZERO will be useful. They were debugged before the
1041 * code to merge identical vertices in the main loop was added.
1043 #define TOLERANCE_NONZERO FALSE
1045 static void ConnectLeftDegenerate( GLUtesselator *tess,
1046 ActiveRegion *regUp, GLUvertex *vEvent )
1048 * The event vertex lies exacty on an already-processed edge or vertex.
1049 * Adding the new vertex involves splicing it into the already-processed
1050 * part of the mesh.
1053 GLUhalfEdge *e, *eTopLeft, *eTopRight, *eLast;
1054 ActiveRegion *reg;
1056 e = regUp->eUp;
1057 if( VertEq( e->Org, vEvent )) {
1058 /* e->Org is an unprocessed vertex - just combine them, and wait
1059 * for e->Org to be pulled from the queue
1061 assert( TOLERANCE_NONZERO );
1062 SpliceMergeVertices( tess, e, vEvent->anEdge );
1063 return;
1066 if( ! VertEq( e->Dst, vEvent )) {
1067 /* General case -- splice vEvent into edge e which passes through it */
1068 if (__gl_meshSplitEdge( e->Sym ) == NULL) longjmp(tess->env,1);
1069 if( regUp->fixUpperEdge ) {
1070 /* This edge was fixable -- delete unused portion of original edge */
1071 if ( !__gl_meshDelete( e->Onext ) ) longjmp(tess->env,1);
1072 regUp->fixUpperEdge = FALSE;
1074 if ( !__gl_meshSplice( vEvent->anEdge, e ) ) longjmp(tess->env,1);
1075 SweepEvent( tess, vEvent ); /* recurse */
1076 return;
1079 /* vEvent coincides with e->Dst, which has already been processed.
1080 * Splice in the additional right-going edges.
1082 assert( TOLERANCE_NONZERO );
1083 regUp = TopRightRegion( regUp );
1084 reg = RegionBelow( regUp );
1085 eTopRight = reg->eUp->Sym;
1086 eTopLeft = eLast = eTopRight->Onext;
1087 if( reg->fixUpperEdge ) {
1088 /* Here e->Dst has only a single fixable edge going right.
1089 * We can delete it since now we have some real right-going edges.
1091 assert( eTopLeft != eTopRight ); /* there are some left edges too */
1092 DeleteRegion( tess, reg );
1093 if ( !__gl_meshDelete( eTopRight ) ) longjmp(tess->env,1);
1094 eTopRight = eTopLeft->Oprev;
1096 if ( !__gl_meshSplice( vEvent->anEdge, eTopRight ) ) longjmp(tess->env,1);
1097 if( ! EdgeGoesLeft( eTopLeft )) {
1098 /* e->Dst had no left-going edges -- indicate this to AddRightEdges() */
1099 eTopLeft = NULL;
1101 AddRightEdges( tess, regUp, eTopRight->Onext, eLast, eTopLeft, TRUE );
1105 static void ConnectLeftVertex( GLUtesselator *tess, GLUvertex *vEvent )
1107 * Purpose: connect a "left" vertex (one where both edges go right)
1108 * to the processed portion of the mesh. Let R be the active region
1109 * containing vEvent, and let U and L be the upper and lower edge
1110 * chains of R. There are two possibilities:
1112 * - the normal case: split R into two regions, by connecting vEvent to
1113 * the rightmost vertex of U or L lying to the left of the sweep line
1115 * - the degenerate case: if vEvent is close enough to U or L, we
1116 * merge vEvent into that edge chain. The subcases are:
1117 * - merging with the rightmost vertex of U or L
1118 * - merging with the active edge of U or L
1119 * - merging with an already-processed portion of U or L
1122 ActiveRegion *regUp, *regLo, *reg;
1123 GLUhalfEdge *eUp, *eLo, *eNew;
1124 ActiveRegion tmp;
1126 /* assert( vEvent->anEdge->Onext->Onext == vEvent->anEdge ); */
1128 /* Get a pointer to the active region containing vEvent */
1129 tmp.eUp = vEvent->anEdge->Sym;
1130 regUp = (ActiveRegion *)dictKey( dictSearch( tess->dict, &tmp ));
1131 regLo = RegionBelow( regUp );
1132 eUp = regUp->eUp;
1133 eLo = regLo->eUp;
1135 /* Try merging with U or L first */
1136 if( EdgeSign( eUp->Dst, vEvent, eUp->Org ) == 0 ) {
1137 ConnectLeftDegenerate( tess, regUp, vEvent );
1138 return;
1141 /* Connect vEvent to rightmost processed vertex of either chain.
1142 * e->Dst is the vertex that we will connect to vEvent.
1144 reg = VertLeq( eLo->Dst, eUp->Dst ) ? regUp : regLo;
1146 if( regUp->inside || reg->fixUpperEdge) {
1147 if( reg == regUp ) {
1148 eNew = __gl_meshConnect( vEvent->anEdge->Sym, eUp->Lnext );
1149 if (eNew == NULL) longjmp(tess->env,1);
1150 } else {
1151 GLUhalfEdge *tempHalfEdge= __gl_meshConnect( eLo->Dnext, vEvent->anEdge);
1152 if (tempHalfEdge == NULL) longjmp(tess->env,1);
1154 eNew = tempHalfEdge->Sym;
1156 if( reg->fixUpperEdge ) {
1157 if ( !FixUpperEdge( reg, eNew ) ) longjmp(tess->env,1);
1158 } else {
1159 ComputeWinding( tess, AddRegionBelow( tess, regUp, eNew ));
1161 SweepEvent( tess, vEvent );
1162 } else {
1163 /* The new vertex is in a region which does not belong to the polygon.
1164 * We don''t need to connect this vertex to the rest of the mesh.
1166 AddRightEdges( tess, regUp, vEvent->anEdge, vEvent->anEdge, NULL, TRUE );
1171 static void SweepEvent( GLUtesselator *tess, GLUvertex *vEvent )
1173 * Does everything necessary when the sweep line crosses a vertex.
1174 * Updates the mesh and the edge dictionary.
1177 ActiveRegion *regUp, *reg;
1178 GLUhalfEdge *e, *eTopLeft, *eBottomLeft;
1180 tess->event = vEvent; /* for access in EdgeLeq() */
1181 DebugEvent( tess );
1183 /* Check if this vertex is the right endpoint of an edge that is
1184 * already in the dictionary. In this case we don't need to waste
1185 * time searching for the location to insert new edges.
1187 e = vEvent->anEdge;
1188 while( e->activeRegion == NULL ) {
1189 e = e->Onext;
1190 if( e == vEvent->anEdge ) {
1191 /* All edges go right -- not incident to any processed edges */
1192 ConnectLeftVertex( tess, vEvent );
1193 return;
1197 /* Processing consists of two phases: first we "finish" all the
1198 * active regions where both the upper and lower edges terminate
1199 * at vEvent (ie. vEvent is closing off these regions).
1200 * We mark these faces "inside" or "outside" the polygon according
1201 * to their winding number, and delete the edges from the dictionary.
1202 * This takes care of all the left-going edges from vEvent.
1204 regUp = TopLeftRegion( e->activeRegion );
1205 if (regUp == NULL) longjmp(tess->env,1);
1206 reg = RegionBelow( regUp );
1207 eTopLeft = reg->eUp;
1208 eBottomLeft = FinishLeftRegions( tess, reg, NULL );
1210 /* Next we process all the right-going edges from vEvent. This
1211 * involves adding the edges to the dictionary, and creating the
1212 * associated "active regions" which record information about the
1213 * regions between adjacent dictionary edges.
1215 if( eBottomLeft->Onext == eTopLeft ) {
1216 /* No right-going edges -- add a temporary "fixable" edge */
1217 ConnectRightVertex( tess, regUp, eBottomLeft );
1218 } else {
1219 AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TRUE );
1224 /* Make the sentinel coordinates big enough that they will never be
1225 * merged with real input features. (Even with the largest possible
1226 * input contour and the maximum tolerance of 1.0, no merging will be
1227 * done with coordinates larger than 3 * GLU_TESS_MAX_COORD).
1229 #define SENTINEL_COORD (4 * GLU_TESS_MAX_COORD)
1231 static void AddSentinel( GLUtesselator *tess, GLdouble t )
1233 * We add two sentinel edges above and below all other edges,
1234 * to avoid special cases at the top and bottom.
1237 GLUhalfEdge *e;
1238 ActiveRegion *reg = HeapAlloc( GetProcessHeap(), 0, sizeof( ActiveRegion ));
1239 if (reg == NULL) longjmp(tess->env,1);
1241 e = __gl_meshMakeEdge( tess->mesh );
1242 if (e == NULL) longjmp(tess->env,1);
1244 e->Org->s = SENTINEL_COORD;
1245 e->Org->t = t;
1246 e->Dst->s = -SENTINEL_COORD;
1247 e->Dst->t = t;
1248 tess->event = e->Dst; /* initialize it */
1250 reg->eUp = e;
1251 reg->windingNumber = 0;
1252 reg->inside = FALSE;
1253 reg->fixUpperEdge = FALSE;
1254 reg->sentinel = TRUE;
1255 reg->dirty = FALSE;
1256 reg->nodeUp = dictInsert( tess->dict, reg );
1257 if (reg->nodeUp == NULL) longjmp(tess->env,1);
1261 static void InitEdgeDict( GLUtesselator *tess )
1263 * We maintain an ordering of edge intersections with the sweep line.
1264 * This order is maintained in a dynamic dictionary.
1267 tess->dict = dictNewDict( tess, (int (*)(void *, DictKey, DictKey)) EdgeLeq );
1268 if (tess->dict == NULL) longjmp(tess->env,1);
1270 AddSentinel( tess, -SENTINEL_COORD );
1271 AddSentinel( tess, SENTINEL_COORD );
1275 static void DoneEdgeDict( GLUtesselator *tess )
1277 ActiveRegion *reg;
1278 #ifndef NDEBUG
1279 int fixedEdges = 0;
1280 #endif
1282 while( (reg = (ActiveRegion *)dictKey( dictMin( tess->dict ))) != NULL ) {
1284 * At the end of all processing, the dictionary should contain
1285 * only the two sentinel edges, plus at most one "fixable" edge
1286 * created by ConnectRightVertex().
1288 if( ! reg->sentinel ) {
1289 assert( reg->fixUpperEdge );
1290 assert( ++fixedEdges == 1 );
1292 assert( reg->windingNumber == 0 );
1293 DeleteRegion( tess, reg );
1294 /* __gl_meshDelete( reg->eUp );*/
1296 dictDeleteDict( tess->dict );
1300 static void RemoveDegenerateEdges( GLUtesselator *tess )
1302 * Remove zero-length edges, and contours with fewer than 3 vertices.
1305 GLUhalfEdge *e, *eNext, *eLnext;
1306 GLUhalfEdge *eHead = &tess->mesh->eHead;
1308 /*LINTED*/
1309 for( e = eHead->next; e != eHead; e = eNext ) {
1310 eNext = e->next;
1311 eLnext = e->Lnext;
1313 if( VertEq( e->Org, e->Dst ) && e->Lnext->Lnext != e ) {
1314 /* Zero-length edge, contour has at least 3 edges */
1316 SpliceMergeVertices( tess, eLnext, e ); /* deletes e->Org */
1317 if ( !__gl_meshDelete( e ) ) longjmp(tess->env,1); /* e is a self-loop */
1318 e = eLnext;
1319 eLnext = e->Lnext;
1321 if( eLnext->Lnext == e ) {
1322 /* Degenerate contour (one or two edges) */
1324 if( eLnext != e ) {
1325 if( eLnext == eNext || eLnext == eNext->Sym ) { eNext = eNext->next; }
1326 if ( !__gl_meshDelete( eLnext ) ) longjmp(tess->env,1);
1328 if( e == eNext || e == eNext->Sym ) { eNext = eNext->next; }
1329 if ( !__gl_meshDelete( e ) ) longjmp(tess->env,1);
1334 static int InitPriorityQ( GLUtesselator *tess )
1336 * Insert all vertices into the priority queue which determines the
1337 * order in which vertices cross the sweep line.
1340 PriorityQSort *pq;
1341 GLUvertex *v, *vHead;
1343 pq = tess->pq = __gl_pqSortNewPriorityQ( (int (*)(PQkey, PQkey)) __gl_vertLeq );
1344 if (pq == NULL) return 0;
1346 vHead = &tess->mesh->vHead;
1347 for( v = vHead->next; v != vHead; v = v->next ) {
1348 v->pqHandle = __gl_pqSortInsert( pq, v );
1349 if (v->pqHandle == LONG_MAX) break;
1351 if (v != vHead || !__gl_pqSortInit( pq ) ) {
1352 __gl_pqSortDeletePriorityQ(tess->pq);
1353 tess->pq = NULL;
1354 return 0;
1357 return 1;
1361 static void DonePriorityQ( GLUtesselator *tess )
1363 __gl_pqSortDeletePriorityQ( tess->pq );
1367 static int RemoveDegenerateFaces( GLUmesh *mesh )
1369 * Delete any degenerate faces with only two edges. WalkDirtyRegions()
1370 * will catch almost all of these, but it won't catch degenerate faces
1371 * produced by splice operations on already-processed edges.
1372 * The two places this can happen are in FinishLeftRegions(), when
1373 * we splice in a "temporary" edge produced by ConnectRightVertex(),
1374 * and in CheckForLeftSplice(), where we splice already-processed
1375 * edges to ensure that our dictionary invariants are not violated
1376 * by numerical errors.
1378 * In both these cases it is *very* dangerous to delete the offending
1379 * edge at the time, since one of the routines further up the stack
1380 * will sometimes be keeping a pointer to that edge.
1383 GLUface *f, *fNext;
1384 GLUhalfEdge *e;
1386 /*LINTED*/
1387 for( f = mesh->fHead.next; f != &mesh->fHead; f = fNext ) {
1388 fNext = f->next;
1389 e = f->anEdge;
1390 assert( e->Lnext != e );
1392 if( e->Lnext->Lnext == e ) {
1393 /* A face with only two edges */
1394 AddWinding( e->Onext, e );
1395 if ( !__gl_meshDelete( e ) ) return 0;
1398 return 1;
1401 int __gl_computeInterior( GLUtesselator *tess )
1403 * __gl_computeInterior( tess ) computes the planar arrangement specified
1404 * by the given contours, and further subdivides this arrangement
1405 * into regions. Each region is marked "inside" if it belongs
1406 * to the polygon, according to the rule given by tess->windingRule.
1407 * Each interior region is guaranteed be monotone.
1410 GLUvertex *v, *vNext;
1412 tess->fatalError = FALSE;
1414 /* Each vertex defines an event for our sweep line. Start by inserting
1415 * all the vertices in a priority queue. Events are processed in
1416 * lexicographic order, ie.
1418 * e1 < e2 iff e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y)
1420 RemoveDegenerateEdges( tess );
1421 if ( !InitPriorityQ( tess ) ) return 0; /* if error */
1422 InitEdgeDict( tess );
1424 /* __gl_pqSortExtractMin */
1425 while( (v = (GLUvertex *)__gl_pqSortExtractMin( tess->pq )) != NULL ) {
1426 for( ;; ) {
1427 vNext = (GLUvertex *)__gl_pqSortMinimum( tess->pq );
1428 if( vNext == NULL || ! VertEq( vNext, v )) break;
1430 /* Merge together all vertices at exactly the same location.
1431 * This is more efficient than processing them one at a time,
1432 * simplifies the code (see ConnectLeftDegenerate), and is also
1433 * important for correct handling of certain degenerate cases.
1434 * For example, suppose there are two identical edges A and B
1435 * that belong to different contours (so without this code they would
1436 * be processed by separate sweep events). Suppose another edge C
1437 * crosses A and B from above. When A is processed, we split it
1438 * at its intersection point with C. However this also splits C,
1439 * so when we insert B we may compute a slightly different
1440 * intersection point. This might leave two edges with a small
1441 * gap between them. This kind of error is especially obvious
1442 * when using boundary extraction (GLU_TESS_BOUNDARY_ONLY).
1444 vNext = (GLUvertex *)__gl_pqSortExtractMin( tess->pq );
1445 SpliceMergeVertices( tess, v->anEdge, vNext->anEdge );
1447 SweepEvent( tess, v );
1450 /* Set tess->event for debugging purposes */
1451 tess->event = ((ActiveRegion *) dictKey( dictMin( tess->dict )))->eUp->Org;
1452 DebugEvent( tess );
1453 DoneEdgeDict( tess );
1454 DonePriorityQ( tess );
1456 if ( !RemoveDegenerateFaces( tess->mesh ) ) return 0;
1457 __gl_meshCheckMesh( tess->mesh );
1459 return 1;