// see license file for original license.

#ifndef tools_glutess_glutess
#define tools_glutess_glutess

#include "_tess"

GLUAPI GLUtesselator* GLUAPIENTRY gluNewTess (void);
GLUAPI void GLUAPIENTRY gluDeleteTess (GLUtesselator* tess);

GLUAPI void GLUAPIENTRY gluTessBeginContour (GLUtesselator* tess);
GLUAPI void GLUAPIENTRY gluTessBeginPolygon (GLUtesselator* tess, GLUvoid* data);
GLUAPI void GLUAPIENTRY gluTessCallback (GLUtesselator* tess, GLUenum which, _GLUfuncptr CallBackFunc);
GLUAPI void GLUAPIENTRY gluTessEndContour (GLUtesselator* tess);
GLUAPI void GLUAPIENTRY gluTessEndPolygon (GLUtesselator* tess);
GLUAPI void GLUAPIENTRY gluTessNormal (GLUtesselator* tess, GLUdouble valueX, GLUdouble valueY, GLUdouble valueZ);
GLUAPI void GLUAPIENTRY gluTessProperty (GLUtesselator* tess, GLUenum which, GLUdouble data);
GLUAPI void GLUAPIENTRY gluTessVertex (GLUtesselator* tess, GLUdouble *location, GLUvoid* data);

#include "mesh"
#include "normal"
#include "sweep"
#include "tessmono"
#include "render"

#define GLU_TESS_DEFAULT_TOLERANCE 0.0
#define GLU_TESS_MESH		100112	/* void (*)(GLUmesh *mesh)	    */

/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noBegin( GLUenum /*type*/ ) {}
/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noEdgeFlag( GLUboolean /*boundaryEdge*/ ) {}
/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noVertex( void * /*data*/ ) {}
/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noEnd( void ) {}
/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noError( GLUenum /*errnum*/ ) {}
/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noCombine( GLUdouble /*coords*/[3], void* /*data*/[4],
								 GLUfloat /*weight*/[4], void** /*dataOut*/ ) {}
/*ARGSUSED*/ inline/*static*/ void GLUAPIENTRY static_noMesh( GLUmesh* /*mesh*/ ) {}


inline /*ARGSUSED*/ void GLUAPIENTRY __gl_noBeginData( GLUenum /*type*/, void* /*polygonData*/ ) {}
inline /*ARGSUSED*/ void GLUAPIENTRY __gl_noEdgeFlagData( GLUboolean /*boundaryEdge*/, void* /*polygonData*/ ) {}
inline /*ARGSUSED*/ void GLUAPIENTRY __gl_noVertexData( void* /*data*/, void* /*polygonData*/ ) {}
inline /*ARGSUSED*/ void GLUAPIENTRY __gl_noEndData( void* /*polygonData*/ ) {}
inline /*ARGSUSED*/ void GLUAPIENTRY __gl_noErrorData( GLUenum /*errnum*/, void* /*polygonData*/ ) {}
inline /*ARGSUSED*/ void GLUAPIENTRY __gl_noCombineData( GLUdouble /*coords*/[3],
							 void* /*data*/[4],
							 GLUfloat /*weight*/[4],
							 void** /*outData*/,
							 void* /*polygonData*/ ) {}

/* Half-edges are allocated in pairs (see mesh.c) */
//typedef struct { GLUhalfEdge e, eSym; } EdgePair;

inline size_t MAX_FAST_ALLOC() {
  static const size_t s_value = (GLU_MAX(sizeof(EdgePair),GLU_MAX(sizeof(GLUvertex),sizeof(GLUface))));
  return s_value;
}

inline GLUtesselator * GLUAPIENTRY
gluNewTess( void )
{
  GLUtesselator *tess;

  /* Only initialize fields which can be changed by the api.  Other fields
   * are initialized where they are used.
   */

  if (memInit( MAX_FAST_ALLOC() ) == 0) {
     return 0;			/* out of memory */
  }
  tess = (GLUtesselator *)memAlloc( sizeof( GLUtesselator ));
  if (tess == NULL) {
     return 0;			/* out of memory */
  }

  tess->state = T_DORMANT;

  tess->normal[0] = 0;
  tess->normal[1] = 0;
  tess->normal[2] = 0;

  tess->relTolerance = GLU_TESS_DEFAULT_TOLERANCE;
  tess->windingRule = GLU_TESS_WINDING_ODD;
  tess->flagBoundary = TOOLS_GLU_FALSE;
  tess->boundaryOnly = TOOLS_GLU_FALSE;

  tess->callBegin = &static_noBegin;
  tess->callEdgeFlag = &static_noEdgeFlag;
  tess->callVertex = &static_noVertex;
  tess->callEnd = &static_noEnd;

  tess->callError = &static_noError;
  tess->callCombine = &static_noCombine;
  tess->callMesh = &static_noMesh;

  tess->callBeginData= &__gl_noBeginData;
  tess->callEdgeFlagData= &__gl_noEdgeFlagData;
  tess->callVertexData= &__gl_noVertexData;
  tess->callEndData= &__gl_noEndData;
  tess->callErrorData= &__gl_noErrorData;
  tess->callCombineData= &__gl_noCombineData;

  tess->polygonData= NULL;

  return tess;
}

inline/*static*/ void static_MakeDormant( GLUtesselator *tess )
{
  /* Return the tessellator to its original dormant state. */

  if( tess->mesh != NULL ) {
    __gl_meshDeleteMesh( tess->mesh );
  }
  tess->state = T_DORMANT;
  tess->lastEdge = NULL;
  tess->mesh = NULL;
}

#define RequireState( tess, s )   if( tess->state != s ) static_GotoState(tess,s)

inline/*static*/ void static_GotoState( GLUtesselator *tess, enum TessState newState )
{
  while( tess->state != newState ) {
    /* We change the current state one level at a time, to get to
     * the desired state.
     */
    if( tess->state < newState ) {
      switch( tess->state ) {
      case T_DORMANT:
	CALL_ERROR_OR_ERROR_DATA( GLU_TESS_MISSING_BEGIN_POLYGON );
	gluTessBeginPolygon( tess, NULL );
	break;
      case T_IN_POLYGON:
	CALL_ERROR_OR_ERROR_DATA( GLU_TESS_MISSING_BEGIN_CONTOUR );
	gluTessBeginContour( tess );
	break;
      default:
	 ;
      }
    } else {
      switch( tess->state ) {
      case T_IN_CONTOUR:
	CALL_ERROR_OR_ERROR_DATA( GLU_TESS_MISSING_END_CONTOUR );
	gluTessEndContour( tess );
	break;
      case T_IN_POLYGON:
	CALL_ERROR_OR_ERROR_DATA( GLU_TESS_MISSING_END_POLYGON );
	/* gluTessEndPolygon( tess ) is too much work! */
	static_MakeDormant( tess );
	break;
      default:
	 ;
      }
    }
  }
}


inline void GLUAPIENTRY
gluDeleteTess( GLUtesselator *tess )
{
  RequireState( tess, T_DORMANT );
  memFree( tess );
}


inline void GLUAPIENTRY
gluTessProperty( GLUtesselator *tess, GLUenum which, GLUdouble value )
{
  GLUenum windingRule;

  switch( which ) {
  case GLU_TESS_TOLERANCE:
    if( value < 0.0 || value > 1.0 ) break;
    tess->relTolerance = value;
    return;

  case GLU_TESS_WINDING_RULE:
    windingRule = (GLUenum) value;
    if( windingRule != value ) break;	/* not an integer */

    switch( windingRule ) {
    case GLU_TESS_WINDING_ODD:
    case GLU_TESS_WINDING_NONZERO:
    case GLU_TESS_WINDING_POSITIVE:
    case GLU_TESS_WINDING_NEGATIVE:
    case GLU_TESS_WINDING_ABS_GEQ_TWO:
      tess->windingRule = windingRule;
      return;
    default:
      break;
    }
    return; //G.Barrand : add : seen with g++-8.1.0.

  case GLU_TESS_BOUNDARY_ONLY:
    tess->boundaryOnly = (value != 0);
    return;

  default:
    CALL_ERROR_OR_ERROR_DATA( GLU_INVALID_ENUM );
    return;
  }
  CALL_ERROR_OR_ERROR_DATA( GLU_INVALID_VALUE );
}

/* Returns tessellator property */
inline void GLUAPIENTRY
gluGetTessProperty( GLUtesselator *tess, GLUenum which, GLUdouble *value )
{
   switch (which) {
   case GLU_TESS_TOLERANCE:
      /* tolerance should be in range [0..1] */
      assert(0.0 <= tess->relTolerance && tess->relTolerance <= 1.0);
      *value= tess->relTolerance;
      break;
   case GLU_TESS_WINDING_RULE:
      assert(tess->windingRule == GLU_TESS_WINDING_ODD ||
	     tess->windingRule == GLU_TESS_WINDING_NONZERO ||
	     tess->windingRule == GLU_TESS_WINDING_POSITIVE ||
	     tess->windingRule == GLU_TESS_WINDING_NEGATIVE ||
	     tess->windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
      *value= tess->windingRule;
      break;
   case GLU_TESS_BOUNDARY_ONLY:
      assert(tess->boundaryOnly == TOOLS_GLU_TRUE || tess->boundaryOnly == TOOLS_GLU_FALSE);
      *value= tess->boundaryOnly;
      break;
   default:
      *value= 0.0;
      CALL_ERROR_OR_ERROR_DATA( GLU_INVALID_ENUM );
      break;
   }
} /* gluGetTessProperty() */

inline void GLUAPIENTRY
gluTessNormal( GLUtesselator *tess, GLUdouble x, GLUdouble y, GLUdouble z )
{
  tess->normal[0] = x;
  tess->normal[1] = y;
  tess->normal[2] = z;
}

// G.Barrand : begin : g++-8.1.0 : the five below functions introduced to avoid warnings :
//                                   warning :cast between incompatible function types
inline void GLUAPIENTRY
gluTessCallback_GLU_TESS_VERTEX_DATA(GLUtesselator *tess,void (GLUAPIENTRY* a_fn)(void *, void *)) {
  tess->callVertexData = (a_fn == NULL) ? &__gl_noVertexData : a_fn;
}
inline void GLUAPIENTRY
gluTessCallback_GLU_TESS_BEGIN_DATA(GLUtesselator *tess,void (GLUAPIENTRY* a_fn)(GLUenum, void *)) {
  tess->callBeginData = (a_fn == NULL) ? &__gl_noBeginData : a_fn;
}
inline void GLUAPIENTRY
gluTessCallback_GLU_TESS_END_DATA(GLUtesselator *tess,void (GLUAPIENTRY* a_fn)(void *)) {
  tess->callEndData = (a_fn == NULL) ? &__gl_noEndData : a_fn;
}
inline void GLUAPIENTRY
gluTessCallback_GLU_TESS_ERROR_DATA(GLUtesselator *tess,void (GLUAPIENTRY* a_fn)(GLUenum, void *)) {
  tess->callErrorData = (a_fn == NULL) ? &__gl_noErrorData : a_fn;
}
inline void GLUAPIENTRY
gluTessCallback_GLU_TESS_COMBINE_DATA(GLUtesselator *tess,
                                      void (GLUAPIENTRY* a_fn)(GLUdouble [3],void *[4],GLUfloat [4],void **,void *)) {
  tess->callCombineData = (a_fn == NULL) ? &__gl_noCombineData : a_fn;
}
// G.Barrand : end : g++-8.1.0.

inline void GLUAPIENTRY
gluTessCallback( GLUtesselator *tess, GLUenum which, _GLUfuncptr fn)
{
  switch( which ) {
  case GLU_TESS_BEGIN:
    tess->callBegin = (fn == NULL) ? &static_noBegin : (void (GLUAPIENTRY *)(GLUenum)) fn;
    return;
  case GLU_TESS_BEGIN_DATA:
    tess->callBeginData = (fn == NULL) ?
	&__gl_noBeginData : (void (GLUAPIENTRY *)(GLUenum, void *)) fn;
    return;
  case GLU_TESS_EDGE_FLAG:
    tess->callEdgeFlag = (fn == NULL) ? &static_noEdgeFlag :
					(void (GLUAPIENTRY *)(GLUboolean)) fn;
    /* If the client wants boundary edges to be flagged,
     * we render everything as separate triangles (no strips or fans).
     */
    tess->flagBoundary = (fn != NULL);
    return;
  case GLU_TESS_EDGE_FLAG_DATA:
    tess->callEdgeFlagData= (fn == NULL) ?
	&__gl_noEdgeFlagData : (void (GLUAPIENTRY *)(GLUboolean, void *)) fn;
    /* If the client wants boundary edges to be flagged,
     * we render everything as separate triangles (no strips or fans).
     */
    tess->flagBoundary = (fn != NULL);
    return;
  case GLU_TESS_VERTEX:
    tess->callVertex = (fn == NULL) ? &static_noVertex :
				      (void (GLUAPIENTRY *)(void *)) fn;
    return;
  case GLU_TESS_VERTEX_DATA:
    tess->callVertexData = (fn == NULL) ?
	&__gl_noVertexData : (void (GLUAPIENTRY *)(void *, void *)) fn;
    return;
  case GLU_TESS_END:
    tess->callEnd = (fn == NULL) ? &static_noEnd : (void (GLUAPIENTRY *)(void)) fn;
    return;
  case GLU_TESS_END_DATA:
    tess->callEndData = (fn == NULL) ? &__gl_noEndData :
				       (void (GLUAPIENTRY *)(void *)) fn;
    return;
  case GLU_TESS_ERROR:
    tess->callError = (fn == NULL) ? &static_noError : (void (GLUAPIENTRY *)(GLUenum)) fn;
    return;
  case GLU_TESS_ERROR_DATA:
    tess->callErrorData = (fn == NULL) ?
	&__gl_noErrorData : (void (GLUAPIENTRY *)(GLUenum, void *)) fn;
    return;
  case GLU_TESS_COMBINE:
    tess->callCombine = (fn == NULL) ? &static_noCombine :
	(void (GLUAPIENTRY *)(GLUdouble [3],void *[4], GLUfloat [4], void ** )) fn;
    return;
  case GLU_TESS_COMBINE_DATA:
    tess->callCombineData = (fn == NULL) ? &__gl_noCombineData :
					   (void (GLUAPIENTRY *)(GLUdouble [3],
						     void *[4],
						     GLUfloat [4],
						     void **,
						     void *)) fn;
    return;
  case GLU_TESS_MESH:
    tess->callMesh = (fn == NULL) ? &static_noMesh : (void (GLUAPIENTRY *)(GLUmesh *)) fn;
    return;
  default:
    CALL_ERROR_OR_ERROR_DATA( GLU_INVALID_ENUM );
    return;
  }
}

inline/*static*/ int static_AddVertex( GLUtesselator *tess, GLUdouble coords[3], void *data )
{
  GLUhalfEdge *e;

  e = tess->lastEdge;
  if( e == NULL ) {
    /* Make a self-loop (one vertex, one edge). */

    e = __gl_meshMakeEdge( tess->mesh );
    if (e == NULL) return 0;
    if ( !__gl_meshSplice( e, e->Sym ) ) return 0;
  } else {
    /* Create a new vertex and edge which immediately follow e
     * in the ordering around the left face.
     */
    if (__gl_meshSplitEdge( e ) == NULL) return 0;
    e = e->Lnext;
  }

  /* The new vertex is now e->Org. */
  e->Org->data = data;
  e->Org->coords[0] = coords[0];
  e->Org->coords[1] = coords[1];
  e->Org->coords[2] = coords[2];

  /* The winding of an edge says how the winding number changes as we
   * cross from the edge''s right face to its left face.  We add the
   * vertices in such an order that a CCW contour will add +1 to
   * the winding number of the region inside the contour.
   */
  e->winding = 1;
  e->Sym->winding = -1;

  tess->lastEdge = e;

  return 1;
}


inline/*static*/ void static_CacheVertex( GLUtesselator *tess, GLUdouble coords[3], void *data )
{
  CachedVertex *v = &tess->cache[tess->cacheCount];

  v->data = data;
  v->coords[0] = coords[0];
  v->coords[1] = coords[1];
  v->coords[2] = coords[2];
  ++tess->cacheCount;
}


inline/*static*/ int static_EmptyCache( GLUtesselator *tess )
{
  CachedVertex *v = tess->cache;
  CachedVertex *vLast;

  tess->mesh = __gl_meshNewMesh();
  if (tess->mesh == NULL) return 0;

  for( vLast = v + tess->cacheCount; v < vLast; ++v ) {
    if ( !static_AddVertex( tess, v->coords, v->data ) ) return 0;
  }
  tess->cacheCount = 0;
  tess->emptyCache = TOOLS_GLU_FALSE;

  return 1;
}


inline void GLUAPIENTRY
gluTessVertex( GLUtesselator *tess, GLUdouble coords[3], void *data )
{
  int i, tooLarge = TOOLS_GLU_FALSE;
  GLUdouble x, clamped[3];

  RequireState( tess, T_IN_CONTOUR );

  if( tess->emptyCache ) {
    if ( !static_EmptyCache( tess ) ) {
       CALL_ERROR_OR_ERROR_DATA( GLU_OUT_OF_MEMORY );
       return;
    }
    tess->lastEdge = NULL;
  }
  for( i = 0; i < 3; ++i ) {
    x = coords[i];
    if( x < - GLU_TESS_MAX_COORD ) {
      x = - GLU_TESS_MAX_COORD;
      tooLarge = TOOLS_GLU_TRUE;
    }
    if( x > GLU_TESS_MAX_COORD ) {
      x = GLU_TESS_MAX_COORD;
      tooLarge = TOOLS_GLU_TRUE;
    }
    clamped[i] = x;
  }
  if( tooLarge ) {
    CALL_ERROR_OR_ERROR_DATA( GLU_TESS_COORD_TOO_LARGE );
  }

  if( tess->mesh == NULL ) {
    if( tess->cacheCount < GLU_TESS_MAX_CACHE ) {
      static_CacheVertex( tess, clamped, data );
      return;
    }
    if ( !static_EmptyCache( tess ) ) {
       CALL_ERROR_OR_ERROR_DATA( GLU_OUT_OF_MEMORY );
       return;
    }
  }
  if ( !static_AddVertex( tess, clamped, data ) ) {
       CALL_ERROR_OR_ERROR_DATA( GLU_OUT_OF_MEMORY );
  }
}


inline void GLUAPIENTRY
gluTessBeginPolygon( GLUtesselator *tess, void *data )
{
  RequireState( tess, T_DORMANT );

  tess->state = T_IN_POLYGON;
  tess->cacheCount = 0;
  tess->emptyCache = TOOLS_GLU_FALSE;
  tess->mesh = NULL;

  tess->polygonData= data;
}


inline void GLUAPIENTRY
gluTessBeginContour( GLUtesselator *tess )
{
  RequireState( tess, T_IN_POLYGON );

  tess->state = T_IN_CONTOUR;
  tess->lastEdge = NULL;
  if( tess->cacheCount > 0 ) {
    /* Just set a flag so we don't get confused by empty contours
     * -- these can be generated accidentally with the obsolete
     * NextContour() interface.
     */
    tess->emptyCache = TOOLS_GLU_TRUE;
  }
}


inline void GLUAPIENTRY
gluTessEndContour( GLUtesselator *tess )
{
  RequireState( tess, T_IN_CONTOUR );
  tess->state = T_IN_POLYGON;
}

inline void GLUAPIENTRY
gluTessEndPolygon( GLUtesselator *tess )
{
  GLUmesh *mesh;

  if (setjmp(tess->env) != 0) { 
     /* come back here if out of memory */
     CALL_ERROR_OR_ERROR_DATA( GLU_OUT_OF_MEMORY );
     return;
  }

  RequireState( tess, T_IN_POLYGON );
  tess->state = T_DORMANT;

  if( tess->mesh == NULL ) {
    if( ! tess->flagBoundary && tess->callMesh == &static_noMesh ) {

      /* Try some special code to make the easy cases go quickly
       * (eg. convex polygons).  This code does NOT handle multiple contours,
       * intersections, edge flags, and of course it does not generate
       * an explicit mesh either.
       */
      if( __gl_renderCache( tess )) {
	tess->polygonData= NULL;
	return;
      }
    }
    if ( !static_EmptyCache( tess ) ) longjmp(tess->env,1); /* could've used a label*/
  }

  /* Determine the polygon normal and project vertices onto the plane
   * of the polygon.
   */
  __gl_projectPolygon( tess );

  /* __gl_computeInterior( tess ) computes the planar arrangement specified
   * by the given contours, and further subdivides this arrangement
   * into regions.  Each region is marked "inside" if it belongs
   * to the polygon, according to the rule given by tess->windingRule.
   * Each interior region is guaranteed be monotone.
   */
  if ( !__gl_computeInterior( tess ) ) {
     longjmp(tess->env,1);	/* could've used a label */
  }

  mesh = tess->mesh;
  if( ! tess->fatalError ) {
    int rc = 1;

    /* If the user wants only the boundary contours, we throw away all edges
     * except those which separate the interior from the exterior.
     * Otherwise we tessellate all the regions marked "inside".
     */
    if( tess->boundaryOnly ) {
      rc = __gl_meshSetWindingNumber( mesh, 1, TOOLS_GLU_TRUE );
    } else {
      rc = __gl_meshTessellateInterior( mesh );
    }
    if (rc == 0) longjmp(tess->env,1);	/* could've used a label */

    __gl_meshCheckMesh( mesh );

    if( tess->callBegin != &static_noBegin || tess->callEnd != &static_noEnd
       || tess->callVertex != &static_noVertex || tess->callEdgeFlag != &static_noEdgeFlag
       || tess->callBeginData != &__gl_noBeginData
       || tess->callEndData != &__gl_noEndData
       || tess->callVertexData != &__gl_noVertexData
       || tess->callEdgeFlagData != &__gl_noEdgeFlagData )
    {
      if( tess->boundaryOnly ) {
	__gl_renderBoundary( tess, mesh );  /* output boundary contours */
      } else {
	__gl_renderMesh( tess, mesh );	   /* output strips and fans */
      }
    }
    if( tess->callMesh != &static_noMesh ) {

      /* Throw away the exterior faces, so that all faces are interior.
       * This way the user doesn't have to check the "inside" flag,
       * and we don't need to even reveal its existence.  It also leaves
       * the freedom for an implementation to not generate the exterior
       * faces in the first place.
       */
      __gl_meshDiscardExterior( mesh );
      (*tess->callMesh)( mesh );		/* user wants the mesh itself */
      tess->mesh = NULL;
      tess->polygonData= NULL;
      return;
    }
  }
  __gl_meshDeleteMesh( mesh );
  tess->polygonData= NULL;
  tess->mesh = NULL;
}


#include "undef"

#endif
