/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
 * Copyright 2008-2013 Pelican Mapping
 * http://osgearth.org
 *
 * osgEarth is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */
#ifndef OSGEARTHSYMBOLOGY_GEOMETRY_H
#define OSGEARTHSYMBOLOGY_GEOMETRY_H 1

#include <osgEarthSymbology/Common>
#include <osgEarth/GeoData>
#include <osgEarth/Containers>
#include <vector>
#include <stack>

namespace osgEarth { namespace Symbology 
{
    using namespace osgEarth;

    /** Options for the Geometry::buffer() operation. */
    class BufferParameters
    {
    public:
        enum CapStyle  { CAP_DEFAULT, CAP_SQUARE, CAP_ROUND, CAP_FLAT };
        enum JoinStyle { JOIN_ROUND, JOIN_MITRE, JOIN_BEVEL};
        BufferParameters( CapStyle capStyle =CAP_DEFAULT, JoinStyle joinStyle = JOIN_ROUND, int cornerSegs =0, bool singleSided=false, bool leftSide=false )
            : _capStyle(capStyle), _joinStyle(joinStyle),_cornerSegs(cornerSegs), _singleSided(singleSided), _leftSide(leftSide) { }
        CapStyle  _capStyle;
        JoinStyle _joinStyle;
        int       _cornerSegs; // # of line segment making up a rounded corner
        bool      _singleSided; //Whether or not to do a single sided buffer
        bool      _leftSide;    //If doing a single sided buffer are we buffering to the left?  If false, buffer to the right
    };

    typedef std::vector<osg::Vec3d> Vec3dVector;

    /**
     * Baseline geometry class. All Geometry objects derive from this
     * class, even MultiGeometry.
     */
    class OSGEARTHSYMBOLOGY_EXPORT Geometry : public osgEarth::MixinVector<osg::Vec3d,osg::Referenced>
    {
    public:
        Geometry( int capacity =0 );
        Geometry( const Geometry& rhs );
        Geometry( const Vec3dVector* toCopy );

        /** dtor - intentionally public */
        virtual ~Geometry();

    public:
        enum Type {
            TYPE_UNKNOWN,
            TYPE_POINTSET,
            TYPE_LINESTRING,
            TYPE_RING,
            TYPE_POLYGON,
            TYPE_MULTI
        };

        enum Orientation {
            ORIENTATION_CCW,
            ORIENTATION_CW,
            ORIENTATION_DEGENERATE
        };

        static std::string toString( Type t ) {
            return 
                t == TYPE_POINTSET ?   "pointset" :
                t == TYPE_LINESTRING ? "linestring" :
                t == TYPE_RING ?       "ring" :
                t == TYPE_POLYGON ?    "polygon" :
                t == TYPE_MULTI ?      "multi" :
                "unknown";
        }

        /** Creates a geometry from a vector array */
        static Geometry* create( Type type, const Vec3dVector* toCopy );

        // true if osgEarth is compiled for buffering
        static bool hasBufferOperation();

    public:
        /**
         * Gets the total number of points in this geometry.
         */
        virtual int getTotalPointCount() const;

        /**
         * Gets the total number of geometry components
         */
        virtual unsigned getNumComponents() const { return 1; }

        /**
         * Gets the total number of geometries; it is the total of all parts of all
         * components. Also can be seen as the number of Geometry objects that would
         * be returned by a full GeometryIterator.
         */
        virtual unsigned getNumGeometries() const { return 1; }

        /**
         * Converts this geometry to another type. This function will return "this" if
         * the type is the same, and will return NULL if the conversion is impossible.
         */
        virtual Geometry* cloneAs( const Geometry::Type& newType ) const;

        /**
         * Creates a new Vec3Array (single-precision), copies the part into it, and
         * returns the new object. 
         */
        osg::Vec3Array* toVec3Array() const;

        /**
         * Creates a new Vec3dArray (double-precision), copies the part into it, and
         * returns the new object.
         */
        osg::Vec3dArray* toVec3dArray() const;

        /**
         * Gets the bounds of this geometry
         */
        virtual Bounds getBounds() const;

        /**
         * Whether the geometry is lines
         */
        bool isLinear() const { return getComponentType() == TYPE_LINESTRING || getComponentType() == TYPE_RING; }

        /**
         * Runs a buffer (dialate/erode) operation on this geometry and returns the
         * result in the output parameter. Returns true if the op succeeded.
         */
        bool buffer(
            double distance,
            osg::ref_ptr<Geometry>& output,
            const BufferParameters& bp =BufferParameters() ) const;

        /**
         * Crops this geometry to the region represented by the crop polygon, returning
         * the result in the output parameter. Returns true if the op succeeded.
         */
        bool crop(
            const class Polygon* cropPolygon,
            osg::ref_ptr<Geometry>& output ) const;

        /**
         * Boolean difference - subtracts diffPolygon from this geometry, and put the
         * result in output.
         */
        bool difference(
            const class Polygon* diffPolygon,
            osg::ref_ptr<Geometry>& output ) const;

        /**
         * Localizes this geometry relative to its centroid, and returns the localization
         * offset.
         */
        osg::Vec3d localize();

        /**
         * Reverses a call the localize(), given the same offset returned by that method.
         */
        void delocalize( const osg::Vec3d& offset );
        
        /**
         * Reorders the points in the geometry so that, if the last point was connected
         * to the first in a ring, they would be would in the specified direction.
         */
        virtual void rewind( Orientation ori );

        /**
         * Get the winding orientation of the geometry (if you consider the last point
         * to connect back to the first in a ring.)
         */
        Orientation getOrientation() const;

    public:
        virtual Type getType() const { return TYPE_UNKNOWN; }
        virtual Type getComponentType() const { return getType(); }
        virtual bool isValid() const { return size() >= 1; }

        virtual Geometry* clone() const { return cloneAs(getType()); }

        void push_back(const osg::Vec3d& v ) {
            osgEarth::MixinVector<osg::Vec3d,osg::Referenced>::push_back(v); }
        void push_back(double x, double y) { 
            osgEarth::MixinVector<osg::Vec3d,osg::Referenced>::push_back(osg::Vec3d(x,y,0.)); }
        void push_back(double x, double y, double z) { 
            osgEarth::MixinVector<osg::Vec3d,osg::Referenced>::push_back(osg::Vec3d(x,y,z)); }

    protected:
    };

    typedef std::vector< osg::ref_ptr<Geometry> > GeometryCollection;

    /**
     * An unordered collections of points.
     */
    class OSGEARTHSYMBOLOGY_EXPORT PointSet : public Geometry
    {
    public:
        PointSet( int capacity =0 ) : Geometry( capacity ) { }
        PointSet( const Vec3dVector* toCopy ) : Geometry( toCopy ) { }
        PointSet( const PointSet& rhs );

        /** dtor */
        virtual ~PointSet();

    public:
        virtual Type getType() const { return Geometry::TYPE_POINTSET; }
    };

    /**
     * An ordered set of points forming a single contiguous line string.
     */
    class OSGEARTHSYMBOLOGY_EXPORT LineString : public Geometry
    {
    public:
        LineString( int capacity =0 ) : Geometry( capacity ) { }
        LineString( const LineString& rhs );
        LineString( const Vec3dVector* toCopy );

        /** dtor */
        virtual ~LineString();

        double getLength() const;
        bool getSegment(double length, osg::Vec3d& start, osg::Vec3d& end);

    public:
        virtual Type getType() const { return Geometry::TYPE_LINESTRING; }
        virtual bool isValid() const { return size() >= 2; }
    };

    /**
     * A Ring is a closed region. It is open (the first and last
     * points are not the same). It has an orientation, i.e. it is either
     * wound clockwise or counter-clockwise.
     */
    class OSGEARTHSYMBOLOGY_EXPORT Ring : public Geometry
    {
    public:
        Ring( int capacity =0 ) : Geometry( capacity ) { }
        Ring( const Ring& ring );
        Ring( const Vec3dVector* toCopy );

        /** dtor */
        virtual ~Ring();

        // override
        virtual Geometry* cloneAs( const Geometry::Type& newType ) const;

        // tests whether the point falls withing the ring
        virtual bool contains2D( double x, double y ) const;

        // gets the signed area of a part that is known to be open.
        virtual double getSignedArea2D() const;

        // ensures that the first and last points are not idential.
        virtual void open();

        // ensures that the first and last points are identical.
        virtual void close();

        // opens and winds the ring in the specified direction
        virtual void rewind( Orientation ori );

    public:
        virtual Type getType() const { return Geometry::TYPE_RING; }
        virtual bool isValid() const { return size() >= 3; }
    };

    typedef std::vector<osg::ref_ptr<Ring> > RingCollection;

    /**
     * A Polygon is a geometry that consists of one outer boundary Ring, and
     * zero or more inner "hole" rings. The boundary ring is would CCW, and the
     * inner "holes" are wound CW.
     */
    class OSGEARTHSYMBOLOGY_EXPORT Polygon : public Ring
    {
    public:
        Polygon( int capacity =0 ) : Ring( capacity ) { }
        Polygon( const Polygon& rhs );
        Polygon( const Vec3dVector* toCopy );

        /** dtor */
        virtual ~Polygon();
        
    public:
        virtual Type getType() const { return Geometry::TYPE_POLYGON; }
        virtual int getTotalPointCount() const;
        
        virtual unsigned getNumGeometries() const { return 1 + _holes.size(); }

        // tests whether the point falls withing the polygon (but not its holes)
        virtual bool contains2D( double x, double y ) const;

        virtual void open();

        virtual void close();

    public:
        RingCollection& getHoles() { return _holes; }
        const RingCollection& getHoles() const { return _holes; }

    protected:
        RingCollection _holes;
    };

    /**
     * A collection of multiple geometries (aka, a "multi-part" geometry).
     */
    class OSGEARTHSYMBOLOGY_EXPORT MultiGeometry : public Geometry
    {
    public:
        MultiGeometry() { }
        MultiGeometry( const GeometryCollection& parts );
        MultiGeometry( const MultiGeometry& rhs );

        /** dtor */
        virtual ~MultiGeometry();

    public:
        virtual Type getType() const { return Geometry::TYPE_MULTI; }        
        virtual Type getComponentType() const;
        virtual int getTotalPointCount() const;        
        virtual unsigned getNumComponents() const { return _parts.size(); }
        
        virtual unsigned getNumGeometries() const;

        // override
        virtual Geometry* cloneAs( const Geometry::Type& newType ) const;
        virtual bool isValid() const;
        virtual Bounds getBounds() const;
        virtual void rewind( Orientation ori );

    public:
        GeometryCollection& getComponents() { return _parts; }
        const GeometryCollection& getComponents() const { return _parts; }

        Geometry* add( Geometry* geom ) { _parts.push_back(geom); return geom; }

    protected:
        GeometryCollection _parts;
    };

    /**
     * Iterates over a Geometry object, returning each component Geometry
     * in turn. The iterator automatically traverses MultiGeometry objects,
     * returning their components. The interator NEVER returns an actual
     * MultiGeometry object.
     */
    class OSGEARTHSYMBOLOGY_EXPORT GeometryIterator
    {
    public:
        /**
         * New iterator.
         *
         * traversePolyHoles: set to TRUE to return Polygons AND Polygon hole geometries;
         *                    set to FALSE to only return Polygon (outer ring).
         *
         * traverseMultiGeometry: set to TRUE to return MG children, but never an MG itself;
         *                        set to FALSE to return MGs and NOT their children.
         */
        GeometryIterator(
            Geometry* geom,
            bool      traversePolygonHoles  =true );

        bool hasMore() const;
        Geometry* next();

    private:
        Geometry* _next;
        std::stack<Geometry*> _stack;
        bool _traverseMulti;
        bool _traversePolyHoles;

        void fetchNext();
    };

    class OSGEARTHSYMBOLOGY_EXPORT ConstGeometryIterator
    {
    public:
        /**
         * New iterator.
         *
         * traversePolyHoles: set to TRUE to return Polygons AND Polygon hole geometries;
         *                    set to FALSE to only return Polygon (outer ring).
         *
         * traverseMultiGeometry: set to TRUE to return MG children, but never an MG itself;
         *                        set to FALSE to return MGs and NOT their children.
         */
        ConstGeometryIterator(
            const Geometry* geom,
            bool            traversePolygonHoles  =true );

        bool hasMore() const;
        const Geometry* next();

    private:
        const Geometry* _next;
        std::stack<const Geometry*> _stack;
        bool _traverseMulti;
        bool _traversePolyHoles;

        void fetchNext();
    };

    typedef std::pair<osg::Vec3d, osg::Vec3d> Segment;

    class OSGEARTHSYMBOLOGY_EXPORT ConstSegmentIterator
    {
    public:
        ConstSegmentIterator( const Geometry* verts, bool forceClosedLoop =false );        
        bool hasMore() const { return !_done; }
        Segment next();

    private:
        const Vec3dVector* _verts;
        Vec3dVector::const_iterator _iter;
        bool _done;
        bool _closeLoop;
    };

    typedef std::vector<osg::ref_ptr<Geometry> > GeometryList;

} } // namespace osgEarth::Symbology


#endif // OSGEARTHSYMBOLOGY_GEOMETRY_H

