Back to home page

EIC code displayed by LXR

 
 

    


Warning, /include/Geant4/tools/glutess/sweep is written in an unsupported language. File is not indexed.

0001 // see license file for original license.
0002 
0003 #ifndef tools_glutess_sweep
0004 #define tools_glutess_sweep
0005 
0006 #include "mesh"
0007 #include "dict"
0008 
0009 /* For each pair of adjacent edges crossing the sweep line, there is
0010  * an ActiveRegion to represent the region between them.  The active
0011  * regions are kept in sorted order in a dynamic dictionary.  As the
0012  * sweep line crosses each vertex, we update the affected regions.
0013  */
0014 
0015 struct ActiveRegion {
0016   GLUhalfEdge   *eUp;           /* upper edge, directed right to left */
0017   DictNode      *nodeUp;        /* dictionary node corresponding to eUp */
0018   int           windingNumber;  /* used to determine which regions are
0019                                  * inside the polygon */
0020   GLUboolean    inside;         /* is this region inside the polygon? */
0021   GLUboolean    sentinel;       /* marks fake edges at t = +/-infinity */
0022   GLUboolean    dirty;          /* marks regions where the upper or lower
0023                                  * edge has changed, but we haven't checked
0024                                  * whether they intersect yet */
0025   GLUboolean    fixUpperEdge;   /* marks temporary edges introduced when
0026                                  * we process a "right vertex" (one without
0027                                  * any edges leaving to the right) */
0028 };
0029 
0030 #define RegionBelow(r)  ((ActiveRegion *) dictKey(dictPred((r)->nodeUp)))
0031 #define RegionAbove(r)  ((ActiveRegion *) dictKey(dictSucc((r)->nodeUp)))
0032 
0033 ////////////////////////////////////////////////////////
0034 /// inlined C code : ///////////////////////////////////
0035 ////////////////////////////////////////////////////////
0036 
0037 #include "geom"
0038 #include "_tess"
0039 #include "priorityq"
0040 
0041 #define DebugEvent( tess )
0042 
0043 /*
0044  * Invariants for the Edge Dictionary.
0045  * - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2)
0046  *   at any valid location of the sweep event
0047  * - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2
0048  *   share a common endpoint
0049  * - for each e, e->Dst has been processed, but not e->Org
0050  * - each edge e satisfies VertLeq(e->Dst,event) && VertLeq(event,e->Org)
0051  *   where "event" is the current sweep line event.
0052  * - no edge e has zero length
0053  *
0054  * Invariants for the Mesh (the processed portion).
0055  * - the portion of the mesh left of the sweep line is a planar graph,
0056  *   ie. there is *some* way to embed it in the plane
0057  * - no processed edge has zero length
0058  * - no two processed vertices have identical coordinates
0059  * - each "inside" region is monotone, ie. can be broken into two chains
0060  *   of monotonically increasing vertices according to VertLeq(v1,v2)
0061  *   - a non-invariant: these chains may intersect (very slightly)
0062  *
0063  * Invariants for the Sweep.
0064  * - if none of the edges incident to the event vertex have an activeRegion
0065  *   (ie. none of these edges are in the edge dictionary), then the vertex
0066  *   has only right-going edges.
0067  * - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced
0068  *   by ConnectRightVertex), then it is the only right-going edge from
0069  *   its associated vertex.  (This says that these edges exist only
0070  *   when it is necessary.)
0071  */
0072 
0073 /* When we merge two edges into one, we need to compute the combined
0074  * winding of the new edge.
0075  */
0076 #define AddWinding(eDst,eSrc)   (eDst->winding += eSrc->winding, \
0077                                  eDst->Sym->winding += eSrc->Sym->winding)
0078 
0079 inline/*static*/ void static_SweepEvent( GLUtesselator *tess, GLUvertex *vEvent );
0080 inline/*static*/ void static_WalkDirtyRegions( GLUtesselator *tess, ActiveRegion *regUp );
0081 inline/*static*/ int static_CheckForRightSplice( GLUtesselator *tess, ActiveRegion *regUp );
0082 
0083 inline/*static*/ int static_EdgeLeq( GLUtesselator *tess, ActiveRegion *reg1,
0084                     ActiveRegion *reg2 )
0085 /*
0086  * Both edges must be directed from right to left (this is the canonical
0087  * direction for the upper edge of each region).
0088  *
0089  * The strategy is to evaluate a "t" value for each edge at the
0090  * current sweep line position, given by tess->event.  The calculations
0091  * are designed to be very stable, but of course they are not perfect.
0092  *
0093  * Special case: if both edge destinations are at the sweep event,
0094  * we sort the edges by slope (they would otherwise compare equally).
0095  */
0096 {
0097   GLUvertex *event = tess->event;
0098   GLUhalfEdge *e1, *e2;
0099   GLUdouble t1, t2;
0100 
0101   e1 = reg1->eUp;
0102   e2 = reg2->eUp;
0103 
0104   if( e1->Dst == event ) {
0105     if( e2->Dst == event ) {
0106       /* Two edges right of the sweep line which meet at the sweep event.
0107        * Sort them by slope.
0108        */
0109       if( VertLeq( e1->Org, e2->Org )) {
0110         return EdgeSign( e2->Dst, e1->Org, e2->Org ) <= 0;
0111       }
0112       return EdgeSign( e1->Dst, e2->Org, e1->Org ) >= 0;
0113     }
0114     return EdgeSign( e2->Dst, event, e2->Org ) <= 0;
0115   }
0116   if( e2->Dst == event ) {
0117     return EdgeSign( e1->Dst, event, e1->Org ) >= 0;
0118   }
0119 
0120   /* General case - compute signed distance *from* e1, e2 to event */
0121   t1 = EdgeEval( e1->Dst, event, e1->Org );
0122   t2 = EdgeEval( e2->Dst, event, e2->Org );
0123   return (t1 >= t2);
0124 }
0125 
0126 
0127 inline/*static*/ void static_DeleteRegion( GLUtesselator *tess, ActiveRegion *reg )
0128 {
0129   if( reg->fixUpperEdge ) {
0130     /* It was created with zero winding number, so it better be
0131      * deleted with zero winding number (ie. it better not get merged
0132      * with a real edge).
0133      */
0134     assert( reg->eUp->winding == 0 );
0135   }
0136   reg->eUp->activeRegion = NULL;
0137   dictDelete( tess->dict, reg->nodeUp ); /* __gl_dictListDelete */
0138   memFree( reg );
0139 }
0140 
0141 
0142 inline/*static*/ int static_FixUpperEdge( ActiveRegion *reg, GLUhalfEdge *newEdge )
0143 /*
0144  * Replace an upper edge which needs fixing (see ConnectRightVertex).
0145  */
0146 {
0147   assert( reg->fixUpperEdge );
0148   if ( !__gl_meshDelete( reg->eUp ) ) return 0;
0149   reg->fixUpperEdge = TOOLS_GLU_FALSE;
0150   reg->eUp = newEdge;
0151   newEdge->activeRegion = reg;
0152 
0153   return 1;
0154 }
0155 
0156 inline/*static*/ ActiveRegion *static_TopLeftRegion( ActiveRegion *reg )
0157 {
0158   GLUvertex *org = reg->eUp->Org;
0159   GLUhalfEdge *e;
0160 
0161   /* Find the region above the uppermost edge with the same origin */
0162   do {
0163     reg = RegionAbove( reg );
0164   } while( reg->eUp->Org == org );
0165 
0166   /* If the edge above was a temporary edge introduced by ConnectRightVertex,
0167    * now is the time to fix it.
0168    */
0169   if( reg->fixUpperEdge ) {
0170     e = __gl_meshConnect( RegionBelow(reg)->eUp->Sym, reg->eUp->Lnext );
0171     if (e == NULL) return NULL;
0172     if ( !static_FixUpperEdge( reg, e ) ) return NULL;
0173     reg = RegionAbove( reg );
0174   }
0175   return reg;
0176 }
0177 
0178 inline/*static*/ ActiveRegion *static_TopRightRegion( ActiveRegion *reg )
0179 {
0180   GLUvertex *dst = reg->eUp->Dst;
0181 
0182   /* Find the region above the uppermost edge with the same destination */
0183   do {
0184     reg = RegionAbove( reg );
0185   } while( reg->eUp->Dst == dst );
0186   return reg;
0187 }
0188 
0189 inline/*static*/ ActiveRegion *static_AddRegionBelow( GLUtesselator *tess,
0190                                      ActiveRegion *regAbove,
0191                                      GLUhalfEdge *eNewUp )
0192 /*
0193  * Add a new active region to the sweep line, *somewhere* below "regAbove"
0194  * (according to where the new edge belongs in the sweep-line dictionary).
0195  * The upper edge of the new region will be "eNewUp".
0196  * Winding number and "inside" flag are not updated.
0197  */
0198 {
0199   ActiveRegion *regNew = (ActiveRegion *)memAlloc( sizeof( ActiveRegion ));
0200   if (regNew == NULL) longjmp(tess->env,1);
0201 
0202   regNew->eUp = eNewUp;
0203   /* __gl_dictListInsertBefore */
0204   regNew->nodeUp = dictInsertBefore( tess->dict, regAbove->nodeUp, regNew );
0205   if (regNew->nodeUp == NULL) longjmp(tess->env,1);
0206   regNew->fixUpperEdge = TOOLS_GLU_FALSE;
0207   regNew->sentinel = TOOLS_GLU_FALSE;
0208   regNew->dirty = TOOLS_GLU_FALSE;
0209 
0210   eNewUp->activeRegion = regNew;
0211   return regNew;
0212 }
0213 
0214 inline/*static*/ GLUboolean static_IsWindingInside( GLUtesselator *tess, int n )
0215 {
0216   switch( tess->windingRule ) {
0217   case GLU_TESS_WINDING_ODD:
0218     return (n & 1);
0219   case GLU_TESS_WINDING_NONZERO:
0220     return (n != 0);
0221   case GLU_TESS_WINDING_POSITIVE:
0222     return (n > 0);
0223   case GLU_TESS_WINDING_NEGATIVE:
0224     return (n < 0);
0225   case GLU_TESS_WINDING_ABS_GEQ_TWO:
0226     return (n >= 2) || (n <= -2);
0227   }
0228   /*LINTED*/
0229   assert( TOOLS_GLU_FALSE );
0230   /*NOTREACHED*/
0231   return TOOLS_GLU_FALSE;  /* avoid compiler complaints */
0232 }
0233 
0234 
0235 inline/*static*/ void static_ComputeWinding( GLUtesselator *tess, ActiveRegion *reg )
0236 {
0237   reg->windingNumber = RegionAbove(reg)->windingNumber + reg->eUp->winding;
0238   reg->inside = static_IsWindingInside( tess, reg->windingNumber );
0239 }
0240 
0241 
0242 inline/*static*/ void static_FinishRegion( GLUtesselator *tess, ActiveRegion *reg )
0243 /*
0244  * Delete a region from the sweep line.  This happens when the upper
0245  * and lower chains of a region meet (at a vertex on the sweep line).
0246  * The "inside" flag is copied to the appropriate mesh face (we could
0247  * not do this before -- since the structure of the mesh is always
0248  * changing, this face may not have even existed until now).
0249  */
0250 {
0251   GLUhalfEdge *e = reg->eUp;
0252   GLUface *f = e->Lface;
0253 
0254   f->inside = reg->inside;
0255   f->anEdge = e;   /* optimization for __gl_meshTessellateMonoRegion() */
0256   static_DeleteRegion( tess, reg );
0257 }
0258 
0259 
0260 inline/*static*/ GLUhalfEdge *static_FinishLeftRegions( GLUtesselator *tess,
0261                ActiveRegion *regFirst, ActiveRegion *regLast )
0262 /*
0263  * We are given a vertex with one or more left-going edges.  All affected
0264  * edges should be in the edge dictionary.  Starting at regFirst->eUp,
0265  * we walk down deleting all regions where both edges have the same
0266  * origin vOrg.  At the same time we copy the "inside" flag from the
0267  * active region to the face, since at this point each face will belong
0268  * to at most one region (this was not necessarily true until this point
0269  * in the sweep).  The walk stops at the region above regLast; if regLast
0270  * is NULL we walk as far as possible.  At the same time we relink the
0271  * mesh if necessary, so that the ordering of edges around vOrg is the
0272  * same as in the dictionary.
0273  */
0274 {
0275   ActiveRegion *reg, *regPrev;
0276   GLUhalfEdge *e, *ePrev;
0277 
0278   regPrev = regFirst;
0279   ePrev = regFirst->eUp;
0280   while( regPrev != regLast ) {
0281     regPrev->fixUpperEdge = TOOLS_GLU_FALSE;    /* placement was OK */
0282     reg = RegionBelow( regPrev );
0283     e = reg->eUp;
0284     if( e->Org != ePrev->Org ) {
0285       if( ! reg->fixUpperEdge ) {
0286         /* Remove the last left-going edge.  Even though there are no further
0287          * edges in the dictionary with this origin, there may be further
0288          * such edges in the mesh (if we are adding left edges to a vertex
0289          * that has already been processed).  Thus it is important to call
0290          * FinishRegion rather than just DeleteRegion.
0291          */
0292         static_FinishRegion( tess, regPrev );
0293         break;
0294       }
0295       /* If the edge below was a temporary edge introduced by
0296        * ConnectRightVertex, now is the time to fix it.
0297        */
0298       e = __gl_meshConnect( ePrev->Lprev, e->Sym );
0299       if (e == NULL) longjmp(tess->env,1);
0300       if ( !static_FixUpperEdge( reg, e ) ) longjmp(tess->env,1);
0301     }
0302 
0303     /* Relink edges so that ePrev->Onext == e */
0304     if( ePrev->Onext != e ) {
0305       if ( !__gl_meshSplice( e->Oprev, e ) ) longjmp(tess->env,1);
0306       if ( !__gl_meshSplice( ePrev, e ) ) longjmp(tess->env,1);
0307     }
0308     static_FinishRegion( tess, regPrev );       /* may change reg->eUp */
0309     ePrev = reg->eUp;
0310     regPrev = reg;
0311   }
0312   return ePrev;
0313 }
0314 
0315 
0316 inline/*static*/ void static_AddRightEdges( GLUtesselator *tess, ActiveRegion *regUp,
0317        GLUhalfEdge *eFirst, GLUhalfEdge *eLast, GLUhalfEdge *eTopLeft,
0318        GLUboolean cleanUp )
0319 /*
0320  * Purpose: insert right-going edges into the edge dictionary, and update
0321  * winding numbers and mesh connectivity appropriately.  All right-going
0322  * edges share a common origin vOrg.  Edges are inserted CCW starting at
0323  * eFirst; the last edge inserted is eLast->Oprev.  If vOrg has any
0324  * left-going edges already processed, then eTopLeft must be the edge
0325  * such that an imaginary upward vertical segment from vOrg would be
0326  * contained between eTopLeft->Oprev and eTopLeft; otherwise eTopLeft
0327  * should be NULL.
0328  */
0329 {
0330   ActiveRegion *reg, *regPrev;
0331   GLUhalfEdge *e, *ePrev;
0332   int firstTime = TOOLS_GLU_TRUE;
0333 
0334   /* Insert the new right-going edges in the dictionary */
0335   e = eFirst;
0336   do {
0337     assert( VertLeq( e->Org, e->Dst ));
0338     static_AddRegionBelow( tess, regUp, e->Sym );
0339     e = e->Onext;
0340   } while ( e != eLast );
0341 
0342   /* Walk *all* right-going edges from e->Org, in the dictionary order,
0343    * updating the winding numbers of each region, and re-linking the mesh
0344    * edges to match the dictionary ordering (if necessary).
0345    */
0346   if( eTopLeft == NULL ) {
0347     eTopLeft = RegionBelow( regUp )->eUp->Rprev;
0348   }
0349   regPrev = regUp;
0350   ePrev = eTopLeft;
0351   for( ;; ) {
0352     reg = RegionBelow( regPrev );
0353     e = reg->eUp->Sym;
0354     if( e->Org != ePrev->Org ) break;
0355 
0356     if( e->Onext != ePrev ) {
0357       /* Unlink e from its current position, and relink below ePrev */
0358       if ( !__gl_meshSplice( e->Oprev, e ) ) longjmp(tess->env,1);
0359       if ( !__gl_meshSplice( ePrev->Oprev, e ) ) longjmp(tess->env,1);
0360     }
0361     /* Compute the winding number and "inside" flag for the new regions */
0362     reg->windingNumber = regPrev->windingNumber - e->winding;
0363     reg->inside = static_IsWindingInside( tess, reg->windingNumber );
0364 
0365     /* Check for two outgoing edges with same slope -- process these
0366      * before any intersection tests (see example in __gl_computeInterior).
0367      */
0368     regPrev->dirty = TOOLS_GLU_TRUE;
0369     if( ! firstTime && static_CheckForRightSplice( tess, regPrev )) {
0370       AddWinding( e, ePrev );
0371       static_DeleteRegion( tess, regPrev );
0372       if ( !__gl_meshDelete( ePrev ) ) longjmp(tess->env,1);
0373     }
0374     firstTime = TOOLS_GLU_FALSE;
0375     regPrev = reg;
0376     ePrev = e;
0377   }
0378   regPrev->dirty = TOOLS_GLU_TRUE;
0379   assert( regPrev->windingNumber - e->winding == reg->windingNumber );
0380 
0381   if( cleanUp ) {
0382     /* Check for intersections between newly adjacent edges. */
0383     static_WalkDirtyRegions( tess, regPrev );
0384   }
0385 }
0386 
0387 
0388 inline/*static*/ void static_CallCombine( GLUtesselator *tess, GLUvertex *isect,
0389                          void *data[4], GLUfloat weights[4], int needed )
0390 {
0391   GLUdouble coords[3];
0392 
0393   /* Copy coord data in case the callback changes it. */
0394   coords[0] = isect->coords[0];
0395   coords[1] = isect->coords[1];
0396   coords[2] = isect->coords[2];
0397 
0398   isect->data = NULL;
0399   CALL_COMBINE_OR_COMBINE_DATA( coords, data, weights, &isect->data );
0400   if( isect->data == NULL ) {
0401     if( ! needed ) {
0402       isect->data = data[0];
0403     } else if( ! tess->fatalError ) {
0404       /* The only way fatal error is when two edges are found to intersect,
0405        * but the user has not provided the callback necessary to handle
0406        * generated intersection points.
0407        */
0408       CALL_ERROR_OR_ERROR_DATA( GLU_TESS_NEED_COMBINE_CALLBACK );
0409       tess->fatalError = TOOLS_GLU_TRUE;
0410     }
0411   }
0412 }
0413 
0414 inline/*static*/ void static_SpliceMergeVertices( GLUtesselator *tess, GLUhalfEdge *e1,
0415                                  GLUhalfEdge *e2 )
0416 /*
0417  * Two vertices with idential coordinates are combined into one.
0418  * e1->Org is kept, while e2->Org is discarded.
0419  */
0420 {
0421   void *data[4] = { NULL, NULL, NULL, NULL };
0422   GLUfloat weights[4] = { 0.5, 0.5, 0.0, 0.0 };
0423 
0424   data[0] = e1->Org->data;
0425   data[1] = e2->Org->data;
0426   static_CallCombine( tess, e1->Org, data, weights, TOOLS_GLU_FALSE );
0427   if ( !__gl_meshSplice( e1, e2 ) ) longjmp(tess->env,1);
0428 }
0429 
0430 inline/*static*/ void static_VertexWeights( GLUvertex *isect, GLUvertex *org, GLUvertex *dst,
0431                            GLUfloat *weights )
0432 /*
0433  * Find some weights which describe how the intersection vertex is
0434  * a linear combination of "org" and "dest".  Each of the two edges
0435  * which generated "isect" is allocated 50% of the weight; each edge
0436  * splits the weight between its org and dst according to the
0437  * relative distance to "isect".
0438  */
0439 {
0440   GLUdouble t1 = VertL1dist( org, isect );
0441   GLUdouble t2 = VertL1dist( dst, isect );
0442 
0443   weights[0] = float(0.5 * t2 / (t1 + t2));
0444   weights[1] = float(0.5 * t1 / (t1 + t2));
0445   isect->coords[0] += weights[0]*org->coords[0] + weights[1]*dst->coords[0];
0446   isect->coords[1] += weights[0]*org->coords[1] + weights[1]*dst->coords[1];
0447   isect->coords[2] += weights[0]*org->coords[2] + weights[1]*dst->coords[2];
0448 }
0449 
0450 
0451 inline/*static*/ void static_GetIntersectData( GLUtesselator *tess, GLUvertex *isect,
0452        GLUvertex *orgUp, GLUvertex *dstUp,
0453        GLUvertex *orgLo, GLUvertex *dstLo )
0454 /*
0455  * We've computed a new intersection point, now we need a "data" pointer
0456  * from the user so that we can refer to this new vertex in the
0457  * rendering callbacks.
0458  */
0459 {
0460   void *data[4];
0461   GLUfloat weights[4];
0462 
0463   data[0] = orgUp->data;
0464   data[1] = dstUp->data;
0465   data[2] = orgLo->data;
0466   data[3] = dstLo->data;
0467 
0468   isect->coords[0] = isect->coords[1] = isect->coords[2] = 0;
0469   static_VertexWeights( isect, orgUp, dstUp, &weights[0] );
0470   static_VertexWeights( isect, orgLo, dstLo, &weights[2] );
0471 
0472   static_CallCombine( tess, isect, data, weights, TOOLS_GLU_TRUE );
0473 }
0474 
0475 inline/*static*/ int static_CheckForRightSplice( GLUtesselator *tess, ActiveRegion *regUp )
0476 /*
0477  * Check the upper and lower edge of "regUp", to make sure that the
0478  * eUp->Org is above eLo, or eLo->Org is below eUp (depending on which
0479  * origin is leftmost).
0480  *
0481  * The main purpose is to splice right-going edges with the same
0482  * dest vertex and nearly identical slopes (ie. we can't distinguish
0483  * the slopes numerically).  However the splicing can also help us
0484  * to recover from numerical errors.  For example, suppose at one
0485  * point we checked eUp and eLo, and decided that eUp->Org is barely
0486  * above eLo.  Then later, we split eLo into two edges (eg. from
0487  * a splice operation like this one).  This can change the result of
0488  * our test so that now eUp->Org is incident to eLo, or barely below it.
0489  * We must correct this condition to maintain the dictionary invariants.
0490  *
0491  * One possibility is to check these edges for intersection again
0492  * (ie. CheckForIntersect).  This is what we do if possible.  However
0493  * CheckForIntersect requires that tess->event lies between eUp and eLo,
0494  * so that it has something to fall back on when the intersection
0495  * calculation gives us an unusable answer.  So, for those cases where
0496  * we can't check for intersection, this routine fixes the problem
0497  * by just splicing the offending vertex into the other edge.
0498  * This is a guaranteed solution, no matter how degenerate things get.
0499  * Basically this is a combinatorial solution to a numerical problem.
0500  */
0501 {
0502   ActiveRegion *regLo = RegionBelow(regUp);
0503   GLUhalfEdge *eUp = regUp->eUp;
0504   GLUhalfEdge *eLo = regLo->eUp;
0505 
0506   if( VertLeq( eUp->Org, eLo->Org )) {
0507     if( EdgeSign( eLo->Dst, eUp->Org, eLo->Org ) > 0 ) return TOOLS_GLU_FALSE;
0508 
0509     /* eUp->Org appears to be below eLo */
0510     if( ! VertEq( eUp->Org, eLo->Org )) {
0511       /* Splice eUp->Org into eLo */
0512       if ( __gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
0513       if ( !__gl_meshSplice( eUp, eLo->Oprev ) ) longjmp(tess->env,1);
0514       regUp->dirty = regLo->dirty = TOOLS_GLU_TRUE;
0515 
0516     } else if( eUp->Org != eLo->Org ) {
0517       /* merge the two vertices, discarding eUp->Org */
0518       pqDelete( tess->pq, eUp->Org->pqHandle ); /* __gl_pqSortDelete */
0519       static_SpliceMergeVertices( tess, eLo->Oprev, eUp );
0520     }
0521   } else {
0522     if( EdgeSign( eUp->Dst, eLo->Org, eUp->Org ) < 0 ) return TOOLS_GLU_FALSE;
0523 
0524     /* eLo->Org appears to be above eUp, so splice eLo->Org into eUp */
0525     RegionAbove(regUp)->dirty = regUp->dirty = TOOLS_GLU_TRUE;
0526     if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
0527     if ( !__gl_meshSplice( eLo->Oprev, eUp ) ) longjmp(tess->env,1);
0528   }
0529   return TOOLS_GLU_TRUE;
0530 }
0531 
0532 inline/*static*/ int static_CheckForLeftSplice( GLUtesselator *tess, ActiveRegion *regUp )
0533 /*
0534  * Check the upper and lower edge of "regUp", to make sure that the
0535  * eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which
0536  * destination is rightmost).
0537  *
0538  * Theoretically, this should always be true.  However, splitting an edge
0539  * into two pieces can change the results of previous tests.  For example,
0540  * suppose at one point we checked eUp and eLo, and decided that eUp->Dst
0541  * is barely above eLo.  Then later, we split eLo into two edges (eg. from
0542  * a splice operation like this one).  This can change the result of
0543  * the test so that now eUp->Dst is incident to eLo, or barely below it.
0544  * We must correct this condition to maintain the dictionary invariants
0545  * (otherwise new edges might get inserted in the wrong place in the
0546  * dictionary, and bad stuff will happen).
0547  *
0548  * We fix the problem by just splicing the offending vertex into the
0549  * other edge.
0550  */
0551 {
0552   ActiveRegion *regLo = RegionBelow(regUp);
0553   GLUhalfEdge *eUp = regUp->eUp;
0554   GLUhalfEdge *eLo = regLo->eUp;
0555   GLUhalfEdge *e;
0556 
0557   assert( ! VertEq( eUp->Dst, eLo->Dst ));
0558 
0559   if( VertLeq( eUp->Dst, eLo->Dst )) {
0560     if( EdgeSign( eUp->Dst, eLo->Dst, eUp->Org ) < 0 ) return TOOLS_GLU_FALSE;
0561 
0562     /* eLo->Dst is above eUp, so splice eLo->Dst into eUp */
0563     RegionAbove(regUp)->dirty = regUp->dirty = TOOLS_GLU_TRUE;
0564     e = __gl_meshSplitEdge( eUp );
0565     if (e == NULL) longjmp(tess->env,1);
0566     if ( !__gl_meshSplice( eLo->Sym, e ) ) longjmp(tess->env,1);
0567     e->Lface->inside = regUp->inside;
0568   } else {
0569     if( EdgeSign( eLo->Dst, eUp->Dst, eLo->Org ) > 0 ) return TOOLS_GLU_FALSE;
0570 
0571     /* eUp->Dst is below eLo, so splice eUp->Dst into eLo */
0572     regUp->dirty = regLo->dirty = TOOLS_GLU_TRUE;
0573     e = __gl_meshSplitEdge( eLo );
0574     if (e == NULL) longjmp(tess->env,1);
0575     if ( !__gl_meshSplice( eUp->Lnext, eLo->Sym ) ) longjmp(tess->env,1);
0576     e->Rface->inside = regUp->inside;
0577   }
0578   return TOOLS_GLU_TRUE;
0579 }
0580 
0581 
0582 inline/*static*/ int static_CheckForIntersect( GLUtesselator *tess, ActiveRegion *regUp )
0583 /*
0584  * Check the upper and lower edges of the given region to see if
0585  * they intersect.  If so, create the intersection and add it
0586  * to the data structures.
0587  *
0588  * Returns TOOLS_GLU_TRUE if adding the new intersection resulted in a recursive
0589  * call to AddRightEdges(); in this case all "dirty" regions have been
0590  * checked for intersections, and possibly regUp has been deleted.
0591  */
0592 {
0593   ActiveRegion *regLo = RegionBelow(regUp);
0594   GLUhalfEdge *eUp = regUp->eUp;
0595   GLUhalfEdge *eLo = regLo->eUp;
0596   GLUvertex *orgUp = eUp->Org;
0597   GLUvertex *orgLo = eLo->Org;
0598   GLUvertex *dstUp = eUp->Dst;
0599   GLUvertex *dstLo = eLo->Dst;
0600   GLUdouble tMinUp, tMaxLo;
0601   GLUvertex isect, *orgMin;
0602   GLUhalfEdge *e;
0603 
0604   assert( ! VertEq( dstLo, dstUp ));
0605   assert( EdgeSign( dstUp, tess->event, orgUp ) <= 0 );
0606   assert( EdgeSign( dstLo, tess->event, orgLo ) >= 0 );
0607   assert( orgUp != tess->event && orgLo != tess->event );
0608   assert( ! regUp->fixUpperEdge && ! regLo->fixUpperEdge );
0609 
0610   if( orgUp == orgLo ) return TOOLS_GLU_FALSE;  /* right endpoints are the same */
0611 
0612   tMinUp = GLU_MIN( orgUp->t, dstUp->t );
0613   tMaxLo = GLU_MAX( orgLo->t, dstLo->t );
0614   if( tMinUp > tMaxLo ) return TOOLS_GLU_FALSE; /* t ranges do not overlap */
0615 
0616   if( VertLeq( orgUp, orgLo )) {
0617     if( EdgeSign( dstLo, orgUp, orgLo ) > 0 ) return TOOLS_GLU_FALSE;
0618   } else {
0619     if( EdgeSign( dstUp, orgLo, orgUp ) < 0 ) return TOOLS_GLU_FALSE;
0620   }
0621 
0622   /* At this point the edges intersect, at least marginally */
0623   DebugEvent( tess );
0624 
0625   __gl_edgeIntersect( dstUp, orgUp, dstLo, orgLo, &isect );
0626   /* The following properties are guaranteed: */
0627   assert( GLU_MIN( orgUp->t, dstUp->t ) <= isect.t );
0628   assert( isect.t <= GLU_MAX( orgLo->t, dstLo->t ));
0629   assert( GLU_MIN( dstLo->s, dstUp->s ) <= isect.s );
0630   assert( isect.s <= GLU_MAX( orgLo->s, orgUp->s ));
0631 
0632   if( VertLeq( &isect, tess->event )) {
0633     /* The intersection point lies slightly to the left of the sweep line,
0634      * so move it until it''s slightly to the right of the sweep line.
0635      * (If we had perfect numerical precision, this would never happen
0636      * in the first place).  The easiest and safest thing to do is
0637      * replace the intersection by tess->event.
0638      */
0639     isect.s = tess->event->s;
0640     isect.t = tess->event->t;
0641   }
0642   /* Similarly, if the computed intersection lies to the right of the
0643    * rightmost origin (which should rarely happen), it can cause
0644    * unbelievable inefficiency on sufficiently degenerate inputs.
0645    * (If you have the test program, try running test54.d with the
0646    * "X zoom" option turned on).
0647    */
0648   orgMin = VertLeq( orgUp, orgLo ) ? orgUp : orgLo;
0649   if( VertLeq( orgMin, &isect )) {
0650     isect.s = orgMin->s;
0651     isect.t = orgMin->t;
0652   }
0653 
0654   if( VertEq( &isect, orgUp ) || VertEq( &isect, orgLo )) {
0655     /* Easy case -- intersection at one of the right endpoints */
0656     (void) static_CheckForRightSplice( tess, regUp );
0657     return TOOLS_GLU_FALSE;
0658   }
0659 
0660   if(    (! VertEq( dstUp, tess->event )
0661           && EdgeSign( dstUp, tess->event, &isect ) >= 0)
0662       || (! VertEq( dstLo, tess->event )
0663           && EdgeSign( dstLo, tess->event, &isect ) <= 0 ))
0664   {
0665     /* Very unusual -- the new upper or lower edge would pass on the
0666      * wrong side of the sweep event, or through it.  This can happen
0667      * due to very small numerical errors in the intersection calculation.
0668      */
0669     if( dstLo == tess->event ) {
0670       /* Splice dstLo into eUp, and process the new region(s) */
0671       if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
0672       if ( !__gl_meshSplice( eLo->Sym, eUp ) ) longjmp(tess->env,1);
0673       regUp = static_TopLeftRegion( regUp );
0674       if (regUp == NULL) longjmp(tess->env,1);
0675       eUp = RegionBelow(regUp)->eUp;
0676       static_FinishLeftRegions( tess, RegionBelow(regUp), regLo );
0677       static_AddRightEdges( tess, regUp, eUp->Oprev, eUp, eUp, TOOLS_GLU_TRUE );
0678       return TOOLS_GLU_TRUE;
0679     }
0680     if( dstUp == tess->event ) {
0681       /* Splice dstUp into eLo, and process the new region(s) */
0682       if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
0683       if ( !__gl_meshSplice( eUp->Lnext, eLo->Oprev ) ) longjmp(tess->env,1);
0684       regLo = regUp;
0685       regUp = static_TopRightRegion( regUp );
0686       e = RegionBelow(regUp)->eUp->Rprev;
0687       regLo->eUp = eLo->Oprev;
0688       eLo = static_FinishLeftRegions( tess, regLo, NULL );
0689       static_AddRightEdges( tess, regUp, eLo->Onext, eUp->Rprev, e, TOOLS_GLU_TRUE );
0690       return TOOLS_GLU_TRUE;
0691     }
0692     /* Special case: called from ConnectRightVertex.  If either
0693      * edge passes on the wrong side of tess->event, split it
0694      * (and wait for ConnectRightVertex to splice it appropriately).
0695      */
0696     if( EdgeSign( dstUp, tess->event, &isect ) >= 0 ) {
0697       RegionAbove(regUp)->dirty = regUp->dirty = TOOLS_GLU_TRUE;
0698       if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
0699       eUp->Org->s = tess->event->s;
0700       eUp->Org->t = tess->event->t;
0701     }
0702     if( EdgeSign( dstLo, tess->event, &isect ) <= 0 ) {
0703       regUp->dirty = regLo->dirty = TOOLS_GLU_TRUE;
0704       if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
0705       eLo->Org->s = tess->event->s;
0706       eLo->Org->t = tess->event->t;
0707     }
0708     /* leave the rest for ConnectRightVertex */
0709     return TOOLS_GLU_FALSE;
0710   }
0711 
0712   /* General case -- split both edges, splice into new vertex.
0713    * When we do the splice operation, the order of the arguments is
0714    * arbitrary as far as correctness goes.  However, when the operation
0715    * creates a new face, the work done is proportional to the size of
0716    * the new face.  We expect the faces in the processed part of
0717    * the mesh (ie. eUp->Lface) to be smaller than the faces in the
0718    * unprocessed original contours (which will be eLo->Oprev->Lface).
0719    */
0720   if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
0721   if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
0722   if ( !__gl_meshSplice( eLo->Oprev, eUp ) ) longjmp(tess->env,1);
0723   eUp->Org->s = isect.s;
0724   eUp->Org->t = isect.t;
0725   eUp->Org->pqHandle = pqInsert( tess->pq, eUp->Org ); /* __gl_pqSortInsert */
0726   if (eUp->Org->pqHandle == LONG_MAX) {
0727      pqDeletePriorityQ(tess->pq);       /* __gl_pqSortDeletePriorityQ */
0728      tess->pq = NULL;
0729      longjmp(tess->env,1);
0730   }
0731   static_GetIntersectData( tess, eUp->Org, orgUp, dstUp, orgLo, dstLo );
0732   RegionAbove(regUp)->dirty = regUp->dirty = regLo->dirty = TOOLS_GLU_TRUE;
0733   return TOOLS_GLU_FALSE;
0734 }
0735 
0736 inline/*static*/ void static_WalkDirtyRegions( GLUtesselator *tess, ActiveRegion *regUp )
0737 /*
0738  * When the upper or lower edge of any region changes, the region is
0739  * marked "dirty".  This routine walks through all the dirty regions
0740  * and makes sure that the dictionary invariants are satisfied
0741  * (see the comments at the beginning of this file).  Of course
0742  * new dirty regions can be created as we make changes to restore
0743  * the invariants.
0744  */
0745 {
0746   ActiveRegion *regLo = RegionBelow(regUp);
0747   GLUhalfEdge *eUp, *eLo;
0748 
0749   for( ;; ) {
0750     /* Find the lowest dirty region (we walk from the bottom up). */
0751     while( regLo->dirty ) {
0752       regUp = regLo;
0753       regLo = RegionBelow(regLo);
0754     }
0755     if( ! regUp->dirty ) {
0756       regLo = regUp;
0757       regUp = RegionAbove( regUp );
0758       if( regUp == NULL || ! regUp->dirty ) {
0759         /* We've walked all the dirty regions */
0760         return;
0761       }
0762     }
0763     regUp->dirty = TOOLS_GLU_FALSE;
0764     eUp = regUp->eUp;
0765     eLo = regLo->eUp;
0766 
0767     if( eUp->Dst != eLo->Dst ) {
0768       /* Check that the edge ordering is obeyed at the Dst vertices. */
0769       if( static_CheckForLeftSplice( tess, regUp )) {
0770 
0771         /* If the upper or lower edge was marked fixUpperEdge, then
0772          * we no longer need it (since these edges are needed only for
0773          * vertices which otherwise have no right-going edges).
0774          */
0775         if( regLo->fixUpperEdge ) {
0776           static_DeleteRegion( tess, regLo );
0777           if ( !__gl_meshDelete( eLo ) ) longjmp(tess->env,1);
0778           regLo = RegionBelow( regUp );
0779           eLo = regLo->eUp;
0780         } else if( regUp->fixUpperEdge ) {
0781           static_DeleteRegion( tess, regUp );
0782           if ( !__gl_meshDelete( eUp ) ) longjmp(tess->env,1);
0783           regUp = RegionAbove( regLo );
0784           eUp = regUp->eUp;
0785         }
0786       }
0787     }
0788     if( eUp->Org != eLo->Org ) {
0789       if(    eUp->Dst != eLo->Dst
0790           && ! regUp->fixUpperEdge && ! regLo->fixUpperEdge
0791           && (eUp->Dst == tess->event || eLo->Dst == tess->event) )
0792       {
0793         /* When all else fails in CheckForIntersect(), it uses tess->event
0794          * as the intersection location.  To make this possible, it requires
0795          * that tess->event lie between the upper and lower edges, and also
0796          * that neither of these is marked fixUpperEdge (since in the worst
0797          * case it might splice one of these edges into tess->event, and
0798          * violate the invariant that fixable edges are the only right-going
0799          * edge from their associated vertex).
0800          */
0801         if( static_CheckForIntersect( tess, regUp )) {
0802           /* WalkDirtyRegions() was called recursively; we're done */
0803           return;
0804         }
0805       } else {
0806         /* Even though we can't use CheckForIntersect(), the Org vertices
0807          * may violate the dictionary edge ordering.  Check and correct this.
0808          */
0809         (void) static_CheckForRightSplice( tess, regUp );
0810       }
0811     }
0812     if( eUp->Org == eLo->Org && eUp->Dst == eLo->Dst ) {
0813       /* A degenerate loop consisting of only two edges -- delete it. */
0814       AddWinding( eLo, eUp );
0815       static_DeleteRegion( tess, regUp );
0816       if ( !__gl_meshDelete( eUp ) ) longjmp(tess->env,1);
0817       regUp = RegionAbove( regLo );
0818     }
0819   }
0820 }
0821 
0822 
0823 inline/*static*/ void static_ConnectRightVertex( GLUtesselator *tess, ActiveRegion *regUp,
0824                                 GLUhalfEdge *eBottomLeft )
0825 /*
0826  * Purpose: connect a "right" vertex vEvent (one where all edges go left)
0827  * to the unprocessed portion of the mesh.  Since there are no right-going
0828  * edges, two regions (one above vEvent and one below) are being merged
0829  * into one.  "regUp" is the upper of these two regions.
0830  *
0831  * There are two reasons for doing this (adding a right-going edge):
0832  *  - if the two regions being merged are "inside", we must add an edge
0833  *    to keep them separated (the combined region would not be monotone).
0834  *  - in any case, we must leave some record of vEvent in the dictionary,
0835  *    so that we can merge vEvent with features that we have not seen yet.
0836  *    For example, maybe there is a vertical edge which passes just to
0837  *    the right of vEvent; we would like to splice vEvent into this edge.
0838  *
0839  * However, we don't want to connect vEvent to just any vertex.  We don''t
0840  * want the new edge to cross any other edges; otherwise we will create
0841  * intersection vertices even when the input data had no self-intersections.
0842  * (This is a bad thing; if the user's input data has no intersections,
0843  * we don't want to generate any false intersections ourselves.)
0844  *
0845  * Our eventual goal is to connect vEvent to the leftmost unprocessed
0846  * vertex of the combined region (the union of regUp and regLo).
0847  * But because of unseen vertices with all right-going edges, and also
0848  * new vertices which may be created by edge intersections, we don''t
0849  * know where that leftmost unprocessed vertex is.  In the meantime, we
0850  * connect vEvent to the closest vertex of either chain, and mark the region
0851  * as "fixUpperEdge".  This flag says to delete and reconnect this edge
0852  * to the next processed vertex on the boundary of the combined region.
0853  * Quite possibly the vertex we connected to will turn out to be the
0854  * closest one, in which case we won''t need to make any changes.
0855  */
0856 {
0857   GLUhalfEdge *eNew;
0858   GLUhalfEdge *eTopLeft = eBottomLeft->Onext;
0859   ActiveRegion *regLo = RegionBelow(regUp);
0860   GLUhalfEdge *eUp = regUp->eUp;
0861   GLUhalfEdge *eLo = regLo->eUp;
0862   int degenerate = TOOLS_GLU_FALSE;
0863 
0864   if( eUp->Dst != eLo->Dst ) {
0865     (void) static_CheckForIntersect( tess, regUp );
0866   }
0867 
0868   /* Possible new degeneracies: upper or lower edge of regUp may pass
0869    * through vEvent, or may coincide with new intersection vertex
0870    */
0871   if( VertEq( eUp->Org, tess->event )) {
0872     if ( !__gl_meshSplice( eTopLeft->Oprev, eUp ) ) longjmp(tess->env,1);
0873     regUp = static_TopLeftRegion( regUp );
0874     if (regUp == NULL) longjmp(tess->env,1);
0875     eTopLeft = RegionBelow( regUp )->eUp;
0876     static_FinishLeftRegions( tess, RegionBelow(regUp), regLo );
0877     degenerate = TOOLS_GLU_TRUE;
0878   }
0879   if( VertEq( eLo->Org, tess->event )) {
0880     if ( !__gl_meshSplice( eBottomLeft, eLo->Oprev ) ) longjmp(tess->env,1);
0881     eBottomLeft = static_FinishLeftRegions( tess, regLo, NULL );
0882     degenerate = TOOLS_GLU_TRUE;
0883   }
0884   if( degenerate ) {
0885     static_AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TOOLS_GLU_TRUE );
0886     return;
0887   }
0888 
0889   /* Non-degenerate situation -- need to add a temporary, fixable edge.
0890    * Connect to the closer of eLo->Org, eUp->Org.
0891    */
0892   if( VertLeq( eLo->Org, eUp->Org )) {
0893     eNew = eLo->Oprev;
0894   } else {
0895     eNew = eUp;
0896   }
0897   eNew = __gl_meshConnect( eBottomLeft->Lprev, eNew );
0898   if (eNew == NULL) longjmp(tess->env,1);
0899 
0900   /* Prevent cleanup, otherwise eNew might disappear before we've even
0901    * had a chance to mark it as a temporary edge.
0902    */
0903   static_AddRightEdges( tess, regUp, eNew, eNew->Onext, eNew->Onext, TOOLS_GLU_FALSE );
0904   eNew->Sym->activeRegion->fixUpperEdge = TOOLS_GLU_TRUE;
0905   static_WalkDirtyRegions( tess, regUp );
0906 }
0907 
0908 /* Because vertices at exactly the same location are merged together
0909  * before we process the sweep event, some degenerate cases can't occur.
0910  * However if someone eventually makes the modifications required to
0911  * merge features which are close together, the cases below marked
0912  * TOLERANCE_NONZERO will be useful.  They were debugged before the
0913  * code to merge identical vertices in the main loop was added.
0914  */
0915 //#define TOLERANCE_NONZERO     TOOLS_GLU_FALSE
0916 
0917 inline/*static*/ void static_ConnectLeftDegenerate( GLUtesselator *tess,
0918                                    ActiveRegion *regUp, GLUvertex *vEvent )
0919 /*
0920  * The event vertex lies exacty on an already-processed edge or vertex.
0921  * Adding the new vertex involves splicing it into the already-processed
0922  * part of the mesh.
0923  */
0924 {
0925   GLUhalfEdge *e, *eTopLeft, *eTopRight, *eLast;
0926   ActiveRegion *reg;
0927 
0928   e = regUp->eUp;
0929   if( VertEq( e->Org, vEvent )) {
0930     /* e->Org is an unprocessed vertex - just combine them, and wait
0931      * for e->Org to be pulled from the queue
0932      */
0933     assert( /*TOLERANCE_NONZERO*/ TOOLS_GLU_FALSE );
0934     static_SpliceMergeVertices( tess, e, vEvent->anEdge );
0935     return;
0936   }
0937 
0938   if( ! VertEq( e->Dst, vEvent )) {
0939     /* General case -- splice vEvent into edge e which passes through it */
0940     if (__gl_meshSplitEdge( e->Sym ) == NULL) longjmp(tess->env,1);
0941     if( regUp->fixUpperEdge ) {
0942       /* This edge was fixable -- delete unused portion of original edge */
0943       if ( !__gl_meshDelete( e->Onext ) ) longjmp(tess->env,1);
0944       regUp->fixUpperEdge = TOOLS_GLU_FALSE;
0945     }
0946     if ( !__gl_meshSplice( vEvent->anEdge, e ) ) longjmp(tess->env,1);
0947     static_SweepEvent( tess, vEvent ); /* recurse */
0948     return;
0949   }
0950 
0951   /* vEvent coincides with e->Dst, which has already been processed.
0952    * Splice in the additional right-going edges.
0953    */
0954   assert( /*TOLERANCE_NONZERO*/ TOOLS_GLU_FALSE );
0955   regUp = static_TopRightRegion( regUp );
0956   reg = RegionBelow( regUp );
0957   eTopRight = reg->eUp->Sym;
0958   eTopLeft = eLast = eTopRight->Onext;
0959   if( reg->fixUpperEdge ) {
0960     /* Here e->Dst has only a single fixable edge going right.
0961      * We can delete it since now we have some real right-going edges.
0962      */
0963     assert( eTopLeft != eTopRight );   /* there are some left edges too */
0964     static_DeleteRegion( tess, reg );
0965     if ( !__gl_meshDelete( eTopRight ) ) longjmp(tess->env,1);
0966     eTopRight = eTopLeft->Oprev;
0967   }
0968   if ( !__gl_meshSplice( vEvent->anEdge, eTopRight ) ) longjmp(tess->env,1);
0969   if( ! EdgeGoesLeft( eTopLeft )) {
0970     /* e->Dst had no left-going edges -- indicate this to AddRightEdges() */
0971     eTopLeft = NULL;
0972   }
0973   static_AddRightEdges( tess, regUp, eTopRight->Onext, eLast, eTopLeft, TOOLS_GLU_TRUE );
0974 }
0975 
0976 
0977 inline/*static*/ void static_ConnectLeftVertex( GLUtesselator *tess, GLUvertex *vEvent )
0978 /*
0979  * Purpose: connect a "left" vertex (one where both edges go right)
0980  * to the processed portion of the mesh.  Let R be the active region
0981  * containing vEvent, and let U and L be the upper and lower edge
0982  * chains of R.  There are two possibilities:
0983  *
0984  * - the normal case: split R into two regions, by connecting vEvent to
0985  *   the rightmost vertex of U or L lying to the left of the sweep line
0986  *
0987  * - the degenerate case: if vEvent is close enough to U or L, we
0988  *   merge vEvent into that edge chain.  The subcases are:
0989  *      - merging with the rightmost vertex of U or L
0990  *      - merging with the active edge of U or L
0991  *      - merging with an already-processed portion of U or L
0992  */
0993 {
0994   ActiveRegion *regUp, *regLo, *reg;
0995   GLUhalfEdge *eUp, *eLo, *eNew;
0996   ActiveRegion tmp;
0997 
0998   /* assert( vEvent->anEdge->Onext->Onext == vEvent->anEdge ); */
0999 
1000   /* Get a pointer to the active region containing vEvent */
1001   tmp.eUp = vEvent->anEdge->Sym;
1002   /* __GL_DICTLISTKEY */ /* __gl_dictListSearch */
1003   regUp = (ActiveRegion *)dictKey( dictSearch( tess->dict, &tmp ));
1004   regLo = RegionBelow( regUp );
1005   eUp = regUp->eUp;
1006   eLo = regLo->eUp;
1007 
1008   /* Try merging with U or L first */
1009   if( EdgeSign( eUp->Dst, vEvent, eUp->Org ) == 0 ) {
1010     static_ConnectLeftDegenerate( tess, regUp, vEvent );
1011     return;
1012   }
1013 
1014   /* Connect vEvent to rightmost processed vertex of either chain.
1015    * e->Dst is the vertex that we will connect to vEvent.
1016    */
1017   reg = VertLeq( eLo->Dst, eUp->Dst ) ? regUp : regLo;
1018 
1019   if( regUp->inside || reg->fixUpperEdge) {
1020     if( reg == regUp ) {
1021       eNew = __gl_meshConnect( vEvent->anEdge->Sym, eUp->Lnext );
1022       if (eNew == NULL) longjmp(tess->env,1);
1023     } else {
1024       GLUhalfEdge *tempHalfEdge= __gl_meshConnect( eLo->Dnext, vEvent->anEdge);
1025       if (tempHalfEdge == NULL) longjmp(tess->env,1);
1026 
1027       eNew = tempHalfEdge->Sym;
1028     }
1029     if( reg->fixUpperEdge ) {
1030       if ( !static_FixUpperEdge( reg, eNew ) ) longjmp(tess->env,1);
1031     } else {
1032       static_ComputeWinding( tess, static_AddRegionBelow( tess, regUp, eNew ));
1033     }
1034     static_SweepEvent( tess, vEvent );
1035   } else {
1036     /* The new vertex is in a region which does not belong to the polygon.
1037      * We don''t need to connect this vertex to the rest of the mesh.
1038      */
1039     static_AddRightEdges( tess, regUp, vEvent->anEdge, vEvent->anEdge, NULL, TOOLS_GLU_TRUE );
1040   }
1041 }
1042 
1043 
1044 inline/*static*/ void static_SweepEvent( GLUtesselator *tess, GLUvertex *vEvent )
1045 /*
1046  * Does everything necessary when the sweep line crosses a vertex.
1047  * Updates the mesh and the edge dictionary.
1048  */
1049 {
1050   ActiveRegion *regUp, *reg;
1051   GLUhalfEdge *e, *eTopLeft, *eBottomLeft;
1052 
1053   tess->event = vEvent;         /* for access in EdgeLeq() */
1054   DebugEvent( tess );
1055 
1056   /* Check if this vertex is the right endpoint of an edge that is
1057    * already in the dictionary.  In this case we don't need to waste
1058    * time searching for the location to insert new edges.
1059    */
1060   e = vEvent->anEdge;
1061   while( e->activeRegion == NULL ) {
1062     e = e->Onext;
1063     if( e == vEvent->anEdge ) {
1064       /* All edges go right -- not incident to any processed edges */
1065       static_ConnectLeftVertex( tess, vEvent );
1066       return;
1067     }
1068   }
1069 
1070   /* Processing consists of two phases: first we "finish" all the
1071    * active regions where both the upper and lower edges terminate
1072    * at vEvent (ie. vEvent is closing off these regions).
1073    * We mark these faces "inside" or "outside" the polygon according
1074    * to their winding number, and delete the edges from the dictionary.
1075    * This takes care of all the left-going edges from vEvent.
1076    */
1077   regUp = static_TopLeftRegion( e->activeRegion );
1078   if (regUp == NULL) longjmp(tess->env,1);
1079   reg = RegionBelow( regUp );
1080   eTopLeft = reg->eUp;
1081   eBottomLeft = static_FinishLeftRegions( tess, reg, NULL );
1082 
1083   /* Next we process all the right-going edges from vEvent.  This
1084    * involves adding the edges to the dictionary, and creating the
1085    * associated "active regions" which record information about the
1086    * regions between adjacent dictionary edges.
1087    */
1088   if( eBottomLeft->Onext == eTopLeft ) {
1089     /* No right-going edges -- add a temporary "fixable" edge */
1090     static_ConnectRightVertex( tess, regUp, eBottomLeft );
1091   } else {
1092     static_AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TOOLS_GLU_TRUE );
1093   }
1094 }
1095 
1096 
1097 /* Make the sentinel coordinates big enough that they will never be
1098  * merged with real input features.  (Even with the largest possible
1099  * input contour and the maximum tolerance of 1.0, no merging will be
1100  * done with coordinates larger than 3 * GLU_TESS_MAX_COORD).
1101  */
1102 //#define SENTINEL_COORD (4 * GLU_TESS_MAX_COORD)
1103 inline GLUdouble SENTINEL_COORD() {
1104   static const GLUdouble s_value = 4 * GLU_TESS_MAX_COORD;
1105   return s_value;
1106 }
1107 
1108 inline/*static*/ void static_AddSentinel( GLUtesselator *tess, GLUdouble t )
1109 /*
1110  * We add two sentinel edges above and below all other edges,
1111  * to avoid special cases at the top and bottom.
1112  */
1113 {
1114   GLUhalfEdge *e;
1115   ActiveRegion *reg = (ActiveRegion *)memAlloc( sizeof( ActiveRegion ));
1116   if (reg == NULL) longjmp(tess->env,1);
1117 
1118   e = __gl_meshMakeEdge( tess->mesh );
1119   if (e == NULL) longjmp(tess->env,1);
1120 
1121   e->Org->s = SENTINEL_COORD();
1122   e->Org->t = t;
1123   e->Dst->s = -SENTINEL_COORD();
1124   e->Dst->t = t;
1125   tess->event = e->Dst;         /* initialize it */
1126 
1127   reg->eUp = e;
1128   reg->windingNumber = 0;
1129   reg->inside = TOOLS_GLU_FALSE;
1130   reg->fixUpperEdge = TOOLS_GLU_FALSE;
1131   reg->sentinel = TOOLS_GLU_TRUE;
1132   reg->dirty = TOOLS_GLU_FALSE;
1133   reg->nodeUp = dictInsert( tess->dict, reg ); /* __gl_dictListInsertBefore */
1134   if (reg->nodeUp == NULL) longjmp(tess->env,1);
1135 }
1136 
1137 
1138 inline/*static*/ void static_InitEdgeDict( GLUtesselator *tess )
1139 /*
1140  * We maintain an ordering of edge intersections with the sweep line.
1141  * This order is maintained in a dynamic dictionary.
1142  */
1143 {
1144   /* __gl_dictListNewDict */
1145   tess->dict = dictNewDict( tess, (int (*)(void *, DictKey, DictKey)) static_EdgeLeq );
1146   if (tess->dict == NULL) longjmp(tess->env,1);
1147 
1148   static_AddSentinel( tess, -SENTINEL_COORD() );
1149   static_AddSentinel( tess, SENTINEL_COORD() );
1150 }
1151 
1152 
1153 inline/*static*/ void static_DoneEdgeDict( GLUtesselator *tess )
1154 {
1155   ActiveRegion *reg;
1156 #ifndef NDEBUG
1157   int fixedEdges = 0;
1158 #endif
1159 
1160   /* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */
1161   while( (reg = (ActiveRegion *)dictKey( dictMin( tess->dict ))) != NULL ) {
1162     /*
1163      * At the end of all processing, the dictionary should contain
1164      * only the two sentinel edges, plus at most one "fixable" edge
1165      * created by ConnectRightVertex().
1166      */
1167     if( ! reg->sentinel ) {
1168       assert( reg->fixUpperEdge );
1169     //G.Barrand : fix a Coverity diagnostic : begin :
1170     //assert( ++fixedEdges == 1 );
1171 #ifndef NDEBUG
1172       fixedEdges++;
1173 #endif
1174       assert( fixedEdges == 1 );
1175     //G.Barrand : end.
1176     }
1177     assert( reg->windingNumber == 0 );
1178     static_DeleteRegion( tess, reg );
1179 /*    __gl_meshDelete( reg->eUp );*/
1180   }
1181   dictDeleteDict( tess->dict ); /* __gl_dictListDeleteDict */
1182 }
1183 
1184 
1185 inline/*static*/ void static_RemoveDegenerateEdges( GLUtesselator *tess )
1186 /*
1187  * Remove zero-length edges, and contours with fewer than 3 vertices.
1188  */
1189 {
1190   GLUhalfEdge *e, *eNext, *eLnext;
1191   GLUhalfEdge *eHead = &tess->mesh->eHead;
1192 
1193   /*LINTED*/
1194   for( e = eHead->next; e != eHead; e = eNext ) {
1195     eNext = e->next;
1196     eLnext = e->Lnext;
1197 
1198     if( VertEq( e->Org, e->Dst ) && e->Lnext->Lnext != e ) {
1199       /* Zero-length edge, contour has at least 3 edges */
1200 
1201       static_SpliceMergeVertices( tess, eLnext, e );    /* deletes e->Org */
1202       if ( !__gl_meshDelete( e ) ) longjmp(tess->env,1); /* e is a self-loop */
1203       e = eLnext;
1204       eLnext = e->Lnext;
1205     }
1206     if( eLnext->Lnext == e ) {
1207       /* Degenerate contour (one or two edges) */
1208 
1209       if( eLnext != e ) {
1210         if( eLnext == eNext || eLnext == eNext->Sym ) { eNext = eNext->next; }
1211         if ( !__gl_meshDelete( eLnext ) ) longjmp(tess->env,1);
1212       }
1213       if( e == eNext || e == eNext->Sym ) { eNext = eNext->next; }
1214       if ( !__gl_meshDelete( e ) ) longjmp(tess->env,1);
1215     }
1216   }
1217 }
1218 
1219 inline/*static*/ int static_InitPriorityQ( GLUtesselator *tess )
1220 /*
1221  * Insert all vertices into the priority queue which determines the
1222  * order in which vertices cross the sweep line.
1223  */
1224 {
1225   PriorityQ *pq;
1226   GLUvertex *v, *vHead;
1227 
1228   /* __gl_pqSortNewPriorityQ */
1229   pq = tess->pq = pqNewPriorityQ( (int (*)(PQkey, PQkey)) __gl_vertLeq );
1230   if (pq == NULL) return 0;
1231 
1232   vHead = &tess->mesh->vHead;
1233   for( v = vHead->next; v != vHead; v = v->next ) {
1234     v->pqHandle = pqInsert( pq, v ); /* __gl_pqSortInsert */
1235     if (v->pqHandle == LONG_MAX) break;
1236   }
1237   if (v != vHead || !pqInit( pq ) ) { /* __gl_pqSortInit */
1238     pqDeletePriorityQ(tess->pq);        /* __gl_pqSortDeletePriorityQ */
1239     tess->pq = NULL;
1240     return 0;
1241   }
1242 
1243   return 1;
1244 }
1245 
1246 
1247 inline/*static*/ void static_DonePriorityQ( GLUtesselator *tess )
1248 {
1249   pqDeletePriorityQ( tess->pq ); /* __gl_pqSortDeletePriorityQ */
1250 }
1251 
1252 
1253 inline/*static*/ int static_RemoveDegenerateFaces( GLUmesh *mesh )
1254 /*
1255  * Delete any degenerate faces with only two edges.  WalkDirtyRegions()
1256  * will catch almost all of these, but it won't catch degenerate faces
1257  * produced by splice operations on already-processed edges.
1258  * The two places this can happen are in FinishLeftRegions(), when
1259  * we splice in a "temporary" edge produced by ConnectRightVertex(),
1260  * and in CheckForLeftSplice(), where we splice already-processed
1261  * edges to ensure that our dictionary invariants are not violated
1262  * by numerical errors.
1263  *
1264  * In both these cases it is *very* dangerous to delete the offending
1265  * edge at the time, since one of the routines further up the stack
1266  * will sometimes be keeping a pointer to that edge.
1267  */
1268 {
1269   GLUface *f, *fNext;
1270   GLUhalfEdge *e;
1271 
1272   /*LINTED*/
1273   for( f = mesh->fHead.next; f != &mesh->fHead; f = fNext ) {
1274     fNext = f->next;
1275     e = f->anEdge;
1276     assert( e->Lnext != e );
1277 
1278     if( e->Lnext->Lnext == e ) {
1279       /* A face with only two edges */
1280       AddWinding( e->Onext, e );
1281       if ( !__gl_meshDelete( e ) ) return 0;
1282     }
1283   }
1284   return 1;
1285 }
1286 
1287 inline int __gl_computeInterior( GLUtesselator *tess )
1288 /*
1289  * __gl_computeInterior( tess ) computes the planar arrangement specified
1290  * by the given contours, and further subdivides this arrangement
1291  * into regions.  Each region is marked "inside" if it belongs
1292  * to the polygon, according to the rule given by tess->windingRule.
1293  * Each interior region is guaranteed be monotone.
1294  */
1295 {
1296   GLUvertex *v, *vNext;
1297 
1298   tess->fatalError = TOOLS_GLU_FALSE;
1299 
1300   /* Each vertex defines an event for our sweep line.  Start by inserting
1301    * all the vertices in a priority queue.  Events are processed in
1302    * lexicographic order, ie.
1303    *
1304    *    e1 < e2  iff  e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y)
1305    */
1306   static_RemoveDegenerateEdges( tess );
1307   if ( !static_InitPriorityQ( tess ) ) return 0; /* if error */
1308   static_InitEdgeDict( tess );
1309 
1310   /* __gl_pqSortExtractMin */
1311   while( (v = (GLUvertex *)pqExtractMin( tess->pq )) != NULL ) {
1312     for( ;; ) {
1313       vNext = (GLUvertex *)pqMinimum( tess->pq ); /* __gl_pqSortMinimum */
1314       if( vNext == NULL || ! VertEq( vNext, v )) break;
1315 
1316       /* Merge together all vertices at exactly the same location.
1317        * This is more efficient than processing them one at a time,
1318        * simplifies the code (see ConnectLeftDegenerate), and is also
1319        * important for correct handling of certain degenerate cases.
1320        * For example, suppose there are two identical edges A and B
1321        * that belong to different contours (so without this code they would
1322        * be processed by separate sweep events).  Suppose another edge C
1323        * crosses A and B from above.  When A is processed, we split it
1324        * at its intersection point with C.  However this also splits C,
1325        * so when we insert B we may compute a slightly different
1326        * intersection point.  This might leave two edges with a small
1327        * gap between them.  This kind of error is especially obvious
1328        * when using boundary extraction (GLU_TESS_BOUNDARY_ONLY).
1329        */
1330       vNext = (GLUvertex *)pqExtractMin( tess->pq ); /* __gl_pqSortExtractMin*/
1331       static_SpliceMergeVertices( tess, v->anEdge, vNext->anEdge );
1332     }
1333     static_SweepEvent( tess, v );
1334   }
1335 
1336   /* Set tess->event for debugging purposes */
1337   /* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */
1338   tess->event = ((ActiveRegion *) dictKey( dictMin( tess->dict )))->eUp->Org;
1339   DebugEvent( tess );
1340   static_DoneEdgeDict( tess );
1341   static_DonePriorityQ( tess );
1342 
1343   if ( !static_RemoveDegenerateFaces( tess->mesh ) ) return 0;
1344   __gl_meshCheckMesh( tess->mesh );
1345 
1346   return 1;
1347 }
1348 
1349 #endif