/* osgEarth
* Copyright 2025 Pelican Mapping
* MIT License
*/
#ifndef OSGEARTH_SCREEN_SPACE_LAYOUT_H
#define OSGEARTH_SCREEN_SPACE_LAYOUT_H 1

#include <osgEarth/Common>
#include <osgEarth/Config>
#include <osgEarth/Color>
#include <osg/Drawable>
#include <osgUtil/RenderLeaf>
#include <limits.h>

#define OSGEARTH_SCREEN_SPACE_LAYOUT_BIN "osgearth_ScreenSpaceLayoutBin"

namespace osgEarth
{
    /**
     * Interface that exposes layout information.
     */
    class ScreenSpaceLayoutData : public osg::Referenced
    {
    public:
        /** Install and return a LayoutData on a drawable. */
        static ScreenSpaceLayoutData* getOrCreate(osg::Node* drawable) {
            if (!drawable) return 0L;
            ScreenSpaceLayoutData* ld = dynamic_cast<ScreenSpaceLayoutData*>(drawable->getUserData());
            if (!ld) {
                ld = new ScreenSpaceLayoutData();
                drawable->setUserData(ld);
            }
            return ld;
        }

        /** Decluttering priority - FLT_MAX means don't declutter */
        void setPriority(float value) { _priority = value; }
        float getPriority() const     { return _priority; }

        /** Offset from geoposition in screen pixels */
        void setPixelOffset(const osg::Vec2s& value) { _pixelOffset = value; }
        const osg::Vec2s& getPixelOffset() const     { return _pixelOffset; }

        //! Whether the position is fixed (cannot be moved)
        void setFixed(bool value) { _fixed = value; }
        bool getFixed() const { return _fixed; }

        /** World point for label rotation reference */
        void setAnchorPoint(const osg::Vec3d& value) { _anchorPoint = value; }
        const osg::Vec3d& getAnchorPoint() const { return _anchorPoint; }

        /** Reference point for label rotation reference */
        void setProjPoint(const osg::Vec3d& value) { _refPoint = value; }
        const osg::Vec3d& getProjPoint() const { return _refPoint; }

        //! Fixed screen space rotation angle
        void setRotationDegrees(float value) { _angle_deg = value; }
        float getRotationDegrees() const { return _angle_deg; }

    public:
        float _priority = 0.0f;
        osg::Vec2s _pixelOffset;
        osg::Vec3d _anchorPoint, _refPoint;
        float _angle_deg = 0.0f;
        bool _fixed = false;
        bool _unique = false;
    };

    /**
     * Custom functor that compares two RenderLeaf's and returns TRUE if the left-hand one
     * is higher priority, otherwise FALSE. You can call setDeclutterPriorityFunctor()
     * to set a custom priority-sorting functor.
     */
    struct DeclutterSortFunctor : public osg::Referenced
    {
        virtual bool operator() ( const osgUtil::RenderLeaf* lhs, const osgUtil::RenderLeaf* rhs ) const =0;
        virtual ~DeclutterSortFunctor() { }
    };

    /**
     * Options to control the annotation decluttering engine.
     */
    class OSGEARTH_EXPORT ScreenSpaceLayoutOptions : public ConfigOptions
    {
    public:
        enum Technique {
            TECHNIQUE_LABELS,
            TECHNIQUE_CALLOUTS
        };

        ScreenSpaceLayoutOptions(const ConfigOptions& co = ConfigOptions()) : ConfigOptions(co)
        {
            fromConfig(_conf);
        }

        /** Alpha value of a fully-occluded object */
        OE_OPTION(float, minAnimationAlpha, 0.35f);

        /** Scale factor of a fully-occluded object */
        OE_OPTION(float, minAnimationScale, 0.45f);

        /** Time (in seconds) for an object to transition from occluded to visible */
        OE_OPTION(float, inAnimationTime, 0.00f);

        /** Time (in seconds) for an object to transition from visible to occluded */
        OE_OPTION(float, outAnimationTime, 0.00f);

        /** If set, activate the ScreenSpaceLayoutData priority-based sorting */
        OE_OPTION(bool, sortByPriority, false);

        /** If set, activate the ScreenSpaceLayoutData distance-based sorting */
        OE_OPTION(bool, sortByDistance, true);

        /** Whether to always start rendering text on a pixel boundary, thereby 
          * minimizing filtering artifacts. */
        OE_OPTION(bool, snapToPixel, false);

        /** Maximum number of objects to draw after sorting */
        OE_OPTION(unsigned, maxObjects, INT_MAX);

        /** Render bin number to use for the screen layout */
        OE_OPTION(int, renderOrder, 13);

        //! Technique to use for drawing
        OE_OPTION(Technique, technique, TECHNIQUE_LABELS);

        //! For callouts, the maximum length of a leader line in pixels
        OE_OPTION(float, leaderLineMaxLength, 60.0f);

        //! For callouts, the maximum length of a leader line in pixels
        OE_OPTION(Color, leaderLineColor, Color::White);

        //! For callouts, the width of a leader line in pixels
        OE_OPTION(float, leaderLineWidth, 1.0f);

    public:

        Config getConfig() const;
        void fromConfig( const Config& conf );
    };


    struct OSGEARTH_EXPORT ScreenSpaceLayout
    {
        /**
         * Assigns a stateset to the screen-space layout engine.
         * Drawables rendered while this stateset is active will be projected from
         * scene space to 2D screen space with optional decluttering.
         */
        static void activate(osg::StateSet* stateSet); //, int binNum =13);

        /**
         * Deactivates the use of the screen-space layout engine for a stateset.
         */
        static void deactivate(osg::StateSet* stateSet);

        /**
         * Enables or disables decluttering globally.
         */
        static void setDeclutteringEnabled(bool enabled);

        /**
         * Applies the provided options to the layout engine.
         */
        static void setOptions(const ScreenSpaceLayoutOptions& options);

        /**
         * Fetches the current layout options
         */
        static const ScreenSpaceLayoutOptions& getOptions();

    public: // advanced

        /**
         * Sets a functor to use to determine render leaf priority for declutter sorting.
         */
        static void setSortFunctor( DeclutterSortFunctor* f );

        /**
         * Clears a custom priority functor that was set using setDeclutterPriorityFunctor,
         * reverting to the default behavior (which is to sort by distance from the camera).
         */
        static void clearSortFunctor();

        // internal
        static bool globallyEnabled;
    };

} // namespace osgEarth

#endif //OSGEARTH_SCREEN_SPACE_LAYOUT_H
