/* osgEarth
 * Copyright 2025 Pelican Mapping
 * MIT License
 */

#ifndef OSGEARTH_TERRAIN_MESH_LAYER_H
#define OSGEARTH_TERRAIN_MESH_LAYER_H 1

#include <osgEarth/Common>
#include <osgEarth/Config>
#include <osgEarth/TileLayer>
#include <osgEarth/TileMesher>

namespace osgEarth
{
    /**
     * Layer providing meshed terrain files (TileMesh)
     */
    class OSGEARTH_EXPORT TerrainMeshLayer : public TileLayer
    {
    public: // Serialization
        class OSGEARTH_EXPORT Options : public TileLayer::Options {
        public:
            META_LayerOptions(osgEarth, Options, TileLayer::Options);
            OE_OPTION(URI, uri);
            OE_OPTION(bool, invertY);
            virtual Config getConfig() const;
        private:
            void fromConfig(const Config& conf);
        };

    public:
        META_Layer(osgEarth, TerrainMeshLayer, Options, TileLayer, terrainmesh);

        //! URI from which to fetch terrain mesh tiles
        void setURI(const URI& value) {
            options().uri() = value;
        }

        //! URI from which to fetch terrain mesh tiles
        const optional<URI>& getURI() const { 
            return options().uri(); 
        }

    public: // methods

        //! Creates a tile mesh for the given tile key.
        //! @param key TileKey for which to create the tile mesh
        //! @param progress Optional progress/cancelation callback
        TileMesh createTile(const TileKey& key, ProgressCallback* progress) const;

    protected:

        //! Override to create a tile mesh in a subclass implementation.
        //! Default implementation simply uses the default tile mesher.
        virtual TileMesh createTileImplementation(const TileKey& key, ProgressCallback* progress) const;

    protected: // Layer

        void init() override;

        //! Open the layer for reading.
        Status openImplementation() override;

        //! Called when this layer is added to a map (after open)
        void addedToMap(const Map*) override;
        void removedFromMap(const Map*) override;

        //! Called when this layer is added to a map node
        void prepareForRendering(TerrainEngine*) override;

        void applyConstraints(const TileKey& key, TileMesh& mesh) const;

    private:
        osg::observer_ptr<const Map> _map;
        TerrainEngine* _engine = nullptr;
};

} // namespace osgEarth

OSGEARTH_SPECIALIZE_CONFIG(osgEarth::TerrainMeshLayer::Options);


#endif // OSGEARTH_TERRAIN_MESH_LAYER_H
