// Creates the shared "masking" layer based on a shapefile.
ImageLayer* createSharedLayer(const std::string& url)
{
    // configure the OGR driver to read the shapefile
    OGRFeatureOptions ogr;
    ogr.url() = url;

    // configure a rasterization driver to render the shapes to an
    // image layer.
    AGGLiteOptions agg;
    agg.featureOptions() = ogr;
    agg.styles() = new StyleSheet();

    // Render shapes as opaque white.
    Style style;
    style.getOrCreate<PolygonSymbol>()->fill()->color() = Color::White;
    agg.styles()->addStyle( style );

    // configure the image layer. We set it to "shared" to tell osgEarth to
    // generate a special image unit, making this layer's textures available
    // to all other layers. We also set "visible" to false sine we don't
    // want to actually render this layer in this example.
    ImageLayerOptions layer( "mask", agg );
    layer.shared()  = true;
    layer.visible() = false;
    layer.cachePolicy() = CachePolicy::NO_CACHE;

    return new ImageLayer(layer);
}
示例#2
0
TileIndex*
TileIndex::load(const std::string& filename)
{        
    if (!osgDB::fileExists( filename ) )
    {
        return 0;
    }

    //Load up an index file
    OGRFeatureOptions featureOpt;
    featureOpt.url() = filename;        
    featureOpt.buildSpatialIndex() = true;
    featureOpt.openWrite() = true;

    osg::ref_ptr< FeatureSource> features = FeatureSourceFactory::create( featureOpt );        
    if (!features.valid())
    {
        OE_NOTICE << "Can't load " << filename << std::endl;
        return 0;
    }
    Status s = features->open();
    if (s.isError())
    {
        OE_WARN << s.message();
        return 0L;
    }

    TileIndex* index = new TileIndex();
    index->_features = features.get();
    index->_filename = filename;
    return index;
}
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    if (argc < 2)
    {
        return usage("");
    }


    std::vector< FeatureID > toDelete;
    int fid;
    while (arguments.read("--delete", fid))
    {
        toDelete.push_back( fid );
    }

    std::vector< FeatureID > fids;
    while (arguments.read("--fid", fid))
    {
        fids.push_back( fid );
    }

    bool printFeatures = false;
    if (arguments.read("--printfeatures" )) printFeatures = true;

    std::string filename;

    //Get the first argument that is not an option
    for(int pos=1; pos<arguments.argc(); ++pos)
    {
        if (!arguments.isOption(pos))
        {
            filename  = arguments[ pos ];
        }
    }

    if (filename.empty())
    {
        return usage( "Please provide a filename" );
    }

    bool write = toDelete.size() > 0;



    //Open the feature source
    OGRFeatureOptions featureOpt;
    featureOpt.url() = filename;
    featureOpt.openWrite() = write;

    osg::ref_ptr< FeatureSource > features = FeatureSourceFactory::create( featureOpt );
    features->initialize("");
    features->getFeatureProfile();

    //Delete any features if requested
    if (toDelete.size() > 0)
    {
        for (unsigned int i = 0; i < toDelete.size(); ++i)
        {
            FeatureID fid = toDelete[i];
            std::cout << "Deleting Feature " << fid << std::endl;
            features->deleteFeature( fid );
        }
    }
    else if (fids.size() > 0)
    {
        //Print out any specific FIDs
        for (unsigned int i = 0; i < fids.size(); ++i)
        {
            FeatureID fid = fids[i];
            osg::ref_ptr< Feature > feature = features->getFeature( fid );
            if (feature.valid())
            {
                printFeature( feature.get() );
            }
            else
            {
                std::cout << "Couldn't get feature " << fid << std::endl;
            }
        }
    }
    else
    {
        //Print out feature info
        printStats( features.get() );

        if (printFeatures)
        {
            printAllFeatures( features.get() );
        }
    }

    return 0;
}
示例#4
0
osg::Group*
createLabels( Map* map )
{
    osg::ref_ptr<osg::Group> labels = new osg::Group();

    // first, open up the source shapefile
    OGRFeatureOptions fo;
    fo.url() = g_featureFile;

    osg::ref_ptr<FeatureSource> features = FeatureSourceFactory::create( fo );
    if ( !features.valid() )
    {
        OE_WARN << LC << "Unable to load features!" << std::endl;
        return 0L;
    }

    features->initialize( "" );
    const FeatureProfile* featureProfile = features->getFeatureProfile();
    if ( !featureProfile || !featureProfile->getSRS() )
    {
        OE_WARN << LC << "Feature data has no spatial reference!" << std::endl;
        return 0L;
    }

    osg::ref_ptr<FeatureCursor> cursor = features->createFeatureCursor();
    if ( !cursor.valid() )
    {
        OE_WARN << LC << "Failed to query the feature source!" << std::endl;
        return 0L;
    }

    //SceneControlBin* priorityBin = canvas->getSceneControls();

    unsigned count = 0;

    std::set<std::string> antiDupeSet;

    while( cursor->hasMore() )
    {
        Feature* feature = cursor->nextFeature();
        Geometry* geom = feature->getGeometry();

        if ( !geom )
            continue;

        // we will display the country name:
        std::string text = feature->getString( g_labelAttr );
        if ( text.empty() )
            continue;

        // and use the population to prioritize labels:
        float population = feature->getDouble(g_priorityAttr, 0.0);

        // remove duplicate labels:
        if ( g_removeDupes )
        {
            if ( antiDupeSet.find(text) != antiDupeSet.end() )
                continue;
            antiDupeSet.insert(text);
        }

        // calculate the world location of the label:
        osg::Vec3d centerPoint = geom->getBounds().center();

        osg::Vec3d mapPoint;
        if ( !map->toMapPoint( centerPoint, featureProfile->getSRS(), mapPoint ) )
            continue;

        osg::Vec3d worldPoint;
        if ( !map->mapPointToGeocentricPoint( mapPoint, worldPoint ) )
            continue;

        // create the label and place it:
        osg::MatrixTransform* xform = new osg::MatrixTransform( osg::Matrix::translate(worldPoint) );
        xform->setCullCallback( new CullNodeByNormal(worldPoint) );
        xform->addChild( new ControlNode(new LabelControl(text)) );
        labels->addChild( xform );

        ++count;

        //OE_NOTICE << LC << "Added: " << text << std::endl;
    }

    OE_NOTICE << LC << "Found " << count << " features. " << std::endl;

    return labels.release();
}
/** Packages an image layer as a TMS folder. */
int
makeTMS( osg::ArgumentParser& args )
{
    osgDB::Registry::instance()->getReaderWriterForExtension("png");
    osgDB::Registry::instance()->getReaderWriterForExtension("jpg");
    osgDB::Registry::instance()->getReaderWriterForExtension("tiff");

    //Read the min level
    unsigned int minLevel = 0;
    while (args.read("--min-level", minLevel));

    //Read the max level
    unsigned int maxLevel = 5;
    while (args.read("--max-level", maxLevel));
    

    std::vector< Bounds > bounds;
    // restrict packaging to user-specified bounds.    
    double xmin=DBL_MAX, ymin=DBL_MAX, xmax=DBL_MIN, ymax=DBL_MIN;
    while (args.read("--bounds", xmin, ymin, xmax, ymax ))
    {        
        Bounds b;
        b.xMin() = xmin, b.yMin() = ymin, b.xMax() = xmax, b.yMax() = ymax;
        bounds.push_back( b );
    }    

    std::string tileList;
    while (args.read( "--tiles", tileList ) );

    bool verbose = args.read("--verbose");

    unsigned int batchSize = 0;
    args.read("--batchsize", batchSize);

    // Read the concurrency level
    unsigned int concurrency = 0;
    args.read("-c", concurrency);
    args.read("--concurrency", concurrency);

    bool writeXML = true;

    // load up the map
    osg::ref_ptr<MapNode> mapNode = MapNode::load( args );
    if( !mapNode.valid() )
        return usage( "Failed to load a valid .earth file" );


    // Read in an index shapefile
    std::string index;
    while (args.read("--index", index))
    {        
        //Open the feature source
        OGRFeatureOptions featureOpt;
        featureOpt.url() = index;        

        osg::ref_ptr< FeatureSource > features = FeatureSourceFactory::create( featureOpt );
        features->initialize();
        features->getFeatureProfile();

        osg::ref_ptr< FeatureCursor > cursor = features->createFeatureCursor();
        while (cursor.valid() && cursor->hasMore())
        {
            osg::ref_ptr< Feature > feature = cursor->nextFeature();
            osgEarth::Bounds featureBounds = feature->getGeometry()->getBounds();
            GeoExtent ext( feature->getSRS(), featureBounds );
            ext = ext.transform( mapNode->getMapSRS() );
            bounds.push_back( ext.bounds() );            
        }
    }

    // see if the user wants to override the type extension (imagery only)
    std::string extension;
    args.read( "--ext", extension );

    // find a .earth file on the command line
    std::string earthFile = findArgumentWithExtension( args, ".earth" );
    
    // folder to which to write the TMS archive.
    std::string rootFolder;
    if( !args.read( "--out", rootFolder ) )
        rootFolder = Stringify() << earthFile << ".tms_repo";

    // whether to overwrite existing tile files
    //TODO:  Support
    bool overwrite = false;
    if( args.read( "--overwrite" ) )
        overwrite = true;

    // write out an earth file
    std::string outEarth;
    args.read( "--out-earth", outEarth );

    std::string dbOptions;
    args.read( "--db-options", dbOptions );
    std::string::size_type n = 0;
    while( (n = dbOptions.find( '"', n )) != dbOptions.npos )
    {
        dbOptions.erase( n, 1 );
    }

    osg::ref_ptr<osgDB::Options> options = new osgDB::Options( dbOptions );

    // whether to keep 'empty' tiles    
    bool keepEmpties = args.read( "--keep-empties" );

    //TODO:  Single color
    bool continueSingleColor = args.read( "--continue-single-color" );

    // elevation pixel depth
    unsigned elevationPixelDepth = 32;
    args.read( "--elevation-pixel-depth", elevationPixelDepth );
    
    // create a folder for the output
    osgDB::makeDirectory( rootFolder );
    if( !osgDB::fileExists( rootFolder ) )
        return usage( "Failed to create root output folder" );

    int imageLayerIndex = -1;
    args.read("--image", imageLayerIndex);

    int elevationLayerIndex = -1;
    args.read("--elevation", elevationLayerIndex);
    
    Map* map = mapNode->getMap();


    osg::ref_ptr< TileVisitor > visitor;

    // If we are given a task file, load it up and create a new TileKeyListVisitor
    if (!tileList.empty())
    {        
        TaskList tasks( mapNode->getMap()->getProfile() );
        tasks.load( tileList );

        TileKeyListVisitor* v = new TileKeyListVisitor();
        v->setKeys( tasks.getKeys() );
        visitor = v;     
        // This process is a lowly worker, and shouldn't write out the XML file.
        writeXML = false;
    }

    // If we dont' have a visitor create one.
    if (!visitor.valid())
    {
        if (args.read("--mt"))
        {
            // Create a multithreaded visitor
            MultithreadedTileVisitor* v = new MultithreadedTileVisitor();
            if (concurrency > 0)
            {
                v->setNumThreads(concurrency);
            }
            visitor = v;            
        }
        else if (args.read("--mp"))
        {
            // Create a multiprocess visitor
            MultiprocessTileVisitor* v = new MultiprocessTileVisitor();
            if (concurrency > 0)
            {
                v->setNumProcesses(concurrency);
                OE_NOTICE << "Set num processes " << concurrency << std::endl;
            }

            if (batchSize > 0)
            {            
                v->setBatchSize(batchSize);
            }


            // Try to find the earth file
            std::string earthFile;
            for(int pos=1;pos<args.argc();++pos)
            {
                if (!args.isOption(pos))
                {
                    earthFile  = args[ pos ];
                    break;
                }
            }

            v->setEarthFile( earthFile );

            visitor = v;            
        }
        else
        {
            // Create a single thread visitor
            visitor = new TileVisitor();            
        }        
    }

    osg::ref_ptr< ProgressCallback > progress = new ConsoleProgressCallback();

    if (verbose)
    {
        visitor->setProgressCallback( progress );
    }

    visitor->setMinLevel( minLevel );
    visitor->setMaxLevel( maxLevel );        


    for (unsigned int i = 0; i < bounds.size(); i++)
    {
        GeoExtent extent(mapNode->getMapSRS(), bounds[i]);
        OE_DEBUG << "Adding extent " << extent.toString() << std::endl;                
        visitor->addExtent( extent );
    }    


    // Setup a TMSPackager with all the options.
    TMSPackager packager;
    packager.setExtension(extension);
    packager.setVisitor(visitor);
    packager.setDestination(rootFolder);    
    packager.setElevationPixelDepth(elevationPixelDepth);
    packager.setWriteOptions(options);    
    packager.setOverwrite(overwrite);
    packager.setKeepEmpties(keepEmpties);


    // new map for an output earth file if necessary.
    osg::ref_ptr<Map> outMap = 0L;
    if( !outEarth.empty() )
    {
        // copy the options from the source map first
        outMap = new Map( map->getInitialMapOptions() );
    }

    std::string outEarthFile = osgDB::concatPaths( rootFolder, osgDB::getSimpleFileName( outEarth ) );
    

    // Package an individual image layer
    if (imageLayerIndex >= 0)
    {        
        ImageLayer* layer = map->getImageLayerAt(imageLayerIndex);
        if (layer)
        {
            packager.run(layer, map);
            if (writeXML)
            {
                packager.writeXML(layer, map);
            }
        }
        else
        {
            std::cout << "Failed to find an image layer at index " << imageLayerIndex << std::endl;
            return 1;
        }
    }
    // Package an individual elevation layer
    else if (elevationLayerIndex >= 0)
    {        
        ElevationLayer* layer = map->getElevationLayerAt(elevationLayerIndex);
        if (layer)
        {
            packager.run(layer, map);
            if (writeXML)
            {
                packager.writeXML(layer, map );
            }
        }
        else
        {
            std::cout << "Failed to find an elevation layer at index " << elevationLayerIndex << std::endl;
            return 1;
        }
    }
    else
    {        
        // Package all the ImageLayer's
        for (unsigned int i = 0; i < map->getNumImageLayers(); i++)
        {            
            ImageLayer* layer = map->getImageLayerAt(i);        
            OE_NOTICE << "Packaging " << layer->getName() << std::endl;
            osg::Timer_t start = osg::Timer::instance()->tick();
            packager.run(layer, map);
            osg::Timer_t end = osg::Timer::instance()->tick();
            if (verbose)
            {
                OE_NOTICE << "Completed seeding layer " << layer->getName() << " in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;
            }                

            if (writeXML)
            {
                packager.writeXML(layer, map);
            }

            // save to the output map if requested:
            if( outMap.valid() )
            {
                std::string layerFolder = toLegalFileName( packager.getLayerName() );

                // new TMS driver info:
                TMSOptions tms;
                tms.url() = URI(
                    osgDB::concatPaths( layerFolder, "tms.xml" ),
                    outEarthFile );

                ImageLayerOptions layerOptions( packager.getLayerName(), tms );
                layerOptions.mergeConfig( layer->getInitialOptions().getConfig( true ) );
                layerOptions.cachePolicy() = CachePolicy::NO_CACHE;

                outMap->addImageLayer( new ImageLayer( layerOptions ) );
            }
        }    

        // Package all the ElevationLayer's
        for (unsigned int i = 0; i < map->getNumElevationLayers(); i++)
        {            
            ElevationLayer* layer = map->getElevationLayerAt(i);        
            OE_NOTICE << "Packaging " << layer->getName() << std::endl;
            osg::Timer_t start = osg::Timer::instance()->tick();
            packager.run(layer, map);
            osg::Timer_t end = osg::Timer::instance()->tick();
            if (verbose)
            {
                OE_NOTICE << "Completed seeding layer " << layer->getName() << " in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;
            }      
            if (writeXML)
            {
                packager.writeXML(layer, map);
            }

            // save to the output map if requested:
            if( outMap.valid() )
            {
                std::string layerFolder = toLegalFileName( packager.getLayerName() );

                // new TMS driver info:
                TMSOptions tms;
                tms.url() = URI(
                    osgDB::concatPaths( layerFolder, "tms.xml" ),
                    outEarthFile );

                ElevationLayerOptions layerOptions( packager.getLayerName(), tms );
                layerOptions.mergeConfig( layer->getInitialOptions().getConfig( true ) );
                layerOptions.cachePolicy() = CachePolicy::NO_CACHE;

                outMap->addElevationLayer( new ElevationLayer( layerOptions ) );
            }
        }

    }

    // Write out an earth file if it was requested
    // Finally, write an earth file if requested:
    if( outMap.valid() )
    {
        MapNodeOptions outNodeOptions = mapNode->getMapNodeOptions();
        osg::ref_ptr<MapNode> outMapNode = new MapNode( outMap.get(), outNodeOptions );
        if( !osgDB::writeNodeFile( *outMapNode.get(), outEarthFile ) )
        {
            OE_WARN << LC << "Error writing earth file to \"" << outEarthFile << "\"" << std::endl;
        }
        else if( verbose )
        {
            OE_NOTICE << LC << "Wrote earth file to \"" << outEarthFile << "\"" << std::endl;
        }
    }

    return 0;
}
int
seed( osg::ArgumentParser& args )
{    
    osgDB::Registry::instance()->getReaderWriterForExtension("png");
    osgDB::Registry::instance()->getReaderWriterForExtension("jpg");
    osgDB::Registry::instance()->getReaderWriterForExtension("tiff");

    //Read the min level
    int minLevel = -1;
    while (args.read("--min-level", minLevel));

    //Read the max level
    int maxLevel = -1;
    while (args.read("--max-level", maxLevel));

    bool estimate = args.read("--estimate");        
    

    std::vector< Bounds > bounds;
    // restrict packaging to user-specified bounds.    
    double xmin=DBL_MAX, ymin=DBL_MAX, xmax=DBL_MIN, ymax=DBL_MIN;
    while (args.read("--bounds", xmin, ymin, xmax, ymax ))
    {        
        Bounds b;
        b.xMin() = xmin, b.yMin() = ymin, b.xMax() = xmax, b.yMax() = ymax;
        bounds.push_back( b );
    }    

    std::string tileList;
    while (args.read( "--tiles", tileList ) );

    bool verbose = args.read("--verbose");

    unsigned int batchSize = 0;
    args.read("--batchsize", batchSize);

    // Read the concurrency level
    unsigned int concurrency = 0;
    args.read("-c", concurrency);
    args.read("--concurrency", concurrency);

    int imageLayerIndex = -1;
    args.read("--image", imageLayerIndex);

    int elevationLayerIndex = -1;
    args.read("--elevation", elevationLayerIndex);


    //Read in the earth file.
    osg::ref_ptr<osg::Node> node = osgDB::readNodeFiles( args );
    if ( !node.valid() )
        return usage( "Failed to read .earth file." );

    MapNode* mapNode = MapNode::findMapNode( node.get() );
    if ( !mapNode )
        return usage( "Input file was not a .earth file" );

    // Read in an index shapefile
    std::string index;
    while (args.read("--index", index))
    {        
        //Open the feature source
        OGRFeatureOptions featureOpt;
        featureOpt.url() = index;        

        osg::ref_ptr< FeatureSource > features = FeatureSourceFactory::create( featureOpt );
        Status status = features->open();

        if (status.isOK())
        {
            osg::ref_ptr< FeatureCursor > cursor = features->createFeatureCursor(0L);
            while (cursor.valid() && cursor->hasMore())
            {
                osg::ref_ptr< Feature > feature = cursor->nextFeature();
                osgEarth::Bounds featureBounds = feature->getGeometry()->getBounds();
                GeoExtent ext( feature->getSRS(), featureBounds );
                ext = ext.transform( mapNode->getMapSRS() );
                bounds.push_back( ext.bounds() );            
            }
        }
        else
        {
            OE_WARN << status.message() << "\n";
        }
    }

    // If they requested to do an estimate then don't do the seed, just print out the estimated values.
    if (estimate)
    {        
        CacheEstimator est;
        if ( minLevel >= 0 )
            est.setMinLevel( minLevel );
        if ( maxLevel >= 0 )
            est.setMaxLevel( maxLevel );
        est.setProfile( mapNode->getMap()->getProfile() );

        for (unsigned int i = 0; i < bounds.size(); i++)
        {
            GeoExtent extent(mapNode->getMapSRS(), bounds[i]);
            OE_DEBUG << "Adding extent " << extent.toString() << std::endl;
            est.addExtent( extent );
        } 

        unsigned int numTiles = est.getNumTiles();
        double size = est.getSizeInMB();
        double time = est.getTotalTimeInSeconds();
        std::cout << "Cache Estimation " << std::endl
            << "---------------- " << std::endl
            << "Total number of tiles: " << numTiles << std::endl
            << "Size on disk:          " << osgEarth::prettyPrintSize( size ) << std::endl
            << "Total time:            " << osgEarth::prettyPrintTime( time ) << std::endl;

        return 0;
    }
    
    osg::ref_ptr< TileVisitor > visitor;


    // If we are given a task file, load it up and create a new TileKeyListVisitor
    if (!tileList.empty())
    {        
        TaskList tasks( mapNode->getMap()->getProfile() );
        tasks.load( tileList );

        TileKeyListVisitor* v = new TileKeyListVisitor();
        v->setKeys( tasks.getKeys() );
        visitor = v;        
        OE_DEBUG << "Read task list with " << tasks.getKeys().size() << " tasks" << std::endl;
    }
  

    // If we dont' have a visitor create one.
    if (!visitor.valid())
    {
        if (args.read("--mt"))
        {
            // Create a multithreaded visitor
            MultithreadedTileVisitor* v = new MultithreadedTileVisitor();
            if (concurrency > 0)
            {
                v->setNumThreads(concurrency);
            }
            visitor = v;            
        }
        else if (args.read("--mp"))
        {
            // Create a multiprocess visitor
            MultiprocessTileVisitor* v = new MultiprocessTileVisitor();
            if (concurrency > 0)
            {
                v->setNumProcesses(concurrency);
            }

            if (batchSize > 0)
            {                
                v->setBatchSize(batchSize);
            }

            // Try to find the earth file
            std::string earthFile;
            for(int pos=1;pos<args.argc();++pos)
            {
                if (!args.isOption(pos))
                {
                    earthFile  = args[ pos ];
                    break;
                }
            }
            v->setEarthFile( earthFile );            
            visitor = v;            
        }
        else
        {
            // Create a single thread visitor
            visitor = new TileVisitor();            
        }        
    }

    osg::ref_ptr< ProgressCallback > progress = new ConsoleProgressCallback();
    
    if (verbose)
    {
        visitor->setProgressCallback( progress.get() );
    }

    if ( minLevel >= 0 )
        visitor->setMinLevel( minLevel );
    if ( maxLevel >= 0 )
        visitor->setMaxLevel( maxLevel );        


    for (unsigned int i = 0; i < bounds.size(); i++)
    {
        GeoExtent extent(mapNode->getMapSRS(), bounds[i]);
        OE_DEBUG << "Adding extent " << extent.toString() << std::endl;                
        visitor->addExtent( extent );
    }    
    

    // Initialize the seeder
    CacheSeed seeder;
    seeder.setVisitor(visitor.get());

    osgEarth::Map* map = mapNode->getMap();

    // They want to seed an image layer
    if (imageLayerIndex >= 0)
    {
        osg::ref_ptr< ImageLayer > layer = map->getLayerAt<ImageLayer>( imageLayerIndex );
        if (layer)
        {
            OE_NOTICE << "Seeding single layer " << layer->getName() << std::endl;
            osg::Timer_t start = osg::Timer::instance()->tick();        
            seeder.run(layer.get(), map);
            osg::Timer_t end = osg::Timer::instance()->tick();
            if (verbose)
            {
                OE_NOTICE << "Completed seeding layer " << layer->getName() << " in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;
            }    
        }
        else
        {
            std::cout << "Failed to find an image layer at index " << imageLayerIndex << std::endl;
            return 1;
        }

    }
    // They want to seed an elevation layer
    else if (elevationLayerIndex >= 0)
    {
        osg::ref_ptr< ElevationLayer > layer = map->getLayerAt<ElevationLayer>( elevationLayerIndex );
        if (layer)
        {
            OE_NOTICE << "Seeding single layer " << layer->getName() << std::endl;
            osg::Timer_t start = osg::Timer::instance()->tick();        
            seeder.run(layer.get(), map);
            osg::Timer_t end = osg::Timer::instance()->tick();
            if (verbose)
            {
                OE_NOTICE << "Completed seeding layer " << layer->getName() << " in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;
            }    
        }
        else
        {
            std::cout << "Failed to find an elevation layer at index " << elevationLayerIndex << std::endl;
            return 1;
        }
    }
    // They want to seed the entire map
    else
    {
        TerrainLayerVector terrainLayers;
        map->getLayers(terrainLayers);

        // Seed all the map layers
        for (unsigned int i = 0; i < terrainLayers.size(); ++i)
        {            
            osg::ref_ptr< TerrainLayer > layer = terrainLayers[i].get();
            OE_NOTICE << "Seeding layer" << layer->getName() << std::endl;            
            osg::Timer_t start = osg::Timer::instance()->tick();
            seeder.run(layer.get(), map);            
            osg::Timer_t end = osg::Timer::instance()->tick();
            if (verbose)
            {
                OE_NOTICE << "Completed seeding layer " << layer->getName() << " in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;
            }                
        }

        //for (unsigned int i = 0; i < map->getNumElevationLayers(); ++i)
        //{
        //    osg::ref_ptr< ElevationLayer > layer = map->getElevationLayerAt(i);
        //    OE_NOTICE << "Seeding layer" << layer->getName() << std::endl;
        //    osg::Timer_t start = osg::Timer::instance()->tick();
        //    seeder.run(layer.get(), map);            
        //    osg::Timer_t end = osg::Timer::instance()->tick();
        //    if (verbose)
        //    {
        //        OE_NOTICE << "Completed seeding layer " << layer->getName() << " in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;
        //    }                
        //}        
    }    

    return 0;
}
示例#7
0
int
seed( osg::ArgumentParser& args )
{

    //Read the min level
    unsigned int minLevel = 0;
    while (args.read("--min-level", minLevel));

    //Read the max level
    unsigned int maxLevel = 5;
    while (args.read("--max-level", maxLevel));


    std::vector< Bounds > bounds;
    // restrict packaging to user-specified bounds.
    double xmin=DBL_MAX, ymin=DBL_MAX, xmax=DBL_MIN, ymax=DBL_MIN;
    while (args.read("--bounds", xmin, ymin, xmax, ymax ))
    {
        Bounds b;
        b.xMin() = xmin, b.yMin() = ymin, b.xMax() = xmax, b.yMax() = ymax;
        bounds.push_back( b );
    }

    //Read the cache override directory
    std::string cachePath;
    while (args.read("--cache-path", cachePath));

    //Read the cache type
    std::string cacheType;
    while (args.read("--cache-type", cacheType));

    bool verbose = args.read("--verbose");

    //Read in the earth file.
    osg::ref_ptr<osg::Node> node = osgDB::readNodeFiles( args );
    if ( !node.valid() )
        return usage( "Failed to read .earth file." );

    MapNode* mapNode = MapNode::findMapNode( node.get() );
    if ( !mapNode )
        return usage( "Input file was not a .earth file" );

    CacheSeed seeder;
    seeder.setMinLevel( minLevel );
    seeder.setMaxLevel( maxLevel );

    // Read in an index shapefile
    std::string index;
    while (args.read("--index", index))
    {
        //Open the feature source
        OGRFeatureOptions featureOpt;
        featureOpt.url() = index;

        osg::ref_ptr< FeatureSource > features = FeatureSourceFactory::create( featureOpt );
        features->initialize();
        features->getFeatureProfile();

        osg::ref_ptr< FeatureCursor > cursor = features->createFeatureCursor();
        while (cursor.valid() && cursor->hasMore())
        {
            osg::ref_ptr< Feature > feature = cursor->nextFeature();
            osgEarth::Bounds featureBounds = feature->getGeometry()->getBounds();
            GeoExtent ext( feature->getSRS(), featureBounds );
            ext = ext.transform( mapNode->getMapSRS() );
            bounds.push_back( ext.bounds() );
        }
    }

    for (unsigned int i = 0; i < bounds.size(); i++)
    {
        GeoExtent extent(mapNode->getMapSRS(), bounds[i]);
        OE_DEBUG << "Adding extent " << extent.toString() << std::endl;
        seeder.addExtent( extent );
    }
    if (verbose)
    {
        seeder.setProgressCallback(new ConsoleProgressCallback);
    }


    osg::Timer_t start = osg::Timer::instance()->tick();

    seeder.seed( mapNode->getMap() );

    osg::Timer_t end = osg::Timer::instance()->tick();

    OE_NOTICE << "Completed seeding in " << prettyPrintTime( osg::Timer::instance()->delta_s( start, end ) ) << std::endl;

    return 0;
}
示例#8
0
//
// NOTE: run this sample from the repo/tests directory.
//
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    if ( arguments.read("--help") )
        return usage( argv[0] );

    bool useRaster  = arguments.read("--rasterize");
    bool useOverlay = arguments.read("--overlay");
    bool useStencil = arguments.read("--stencil");
    bool useMem     = arguments.read("--mem");
    bool useLabels  = arguments.read("--labels");

    if ( useStencil )
        osg::DisplaySettings::instance()->setMinimumNumStencilBits( 8 );

    osgViewer::Viewer viewer(arguments);

    // Start by creating the map:
    Map* map = new Map();

    // Start with a basemap imagery layer; we'll be using the GDAL driver
    // to load a local GeoTIFF file:
    GDALOptions basemapOpt;
    basemapOpt.url() = "../data/world.tif";
    map->addImageLayer( new ImageLayer( ImageLayerOptions("basemap", basemapOpt) ) );

    // Next we add a feature layer. 
    OGRFeatureOptions featureOptions;
    if ( !useMem )
    {
        // Configures the feature driver to load the vectors from a shapefile:
        featureOptions.url() = "../data/world.shp";
    }
    else
    {
        // the --mem options tells us to just make an in-memory geometry:
        Ring* line = new Ring();
        line->push_back( osg::Vec3d(-60, 20, 0) );
        line->push_back( osg::Vec3d(-120, 20, 0) );
        line->push_back( osg::Vec3d(-120, 60, 0) );
        line->push_back( osg::Vec3d(-60, 60, 0) );
        featureOptions.geometry() = line;
    }

    // Define a style for the feature data. Since we are going to render the
    // vectors as lines, configure the line symbolizer:
    Style style;

    LineSymbol* ls = style.getOrCreateSymbol<LineSymbol>();
    ls->stroke()->color() = Color::Yellow;
    ls->stroke()->width() = 2.0f;

    // That's it, the map is ready; now create a MapNode to render the Map:
    MapNodeOptions mapNodeOptions;
    mapNodeOptions.enableLighting() = false;
    MapNode* mapNode = new MapNode( map, mapNodeOptions );

    osg::Group* root = new osg::Group();
    root->addChild( mapNode );
    viewer.setSceneData( root );
    viewer.setCameraManipulator( new EarthManipulator() );

    // Process cmdline args
    MapNodeHelper().parse(mapNode, arguments, &viewer, root, new LabelControl("Features Demo"));
   
    if (useStencil)
    {
        FeatureStencilModelOptions stencilOptions;
        stencilOptions.featureOptions() = featureOptions;
        stencilOptions.styles() = new StyleSheet();
        stencilOptions.styles()->addStyle( style );
        stencilOptions.enableLighting() = false;
        stencilOptions.depthTestEnabled() = false;
        ls->stroke()->width() = 0.1f;
        map->addModelLayer( new ModelLayer("my features", stencilOptions) );
    }
    else if (useRaster)
    {
        AGGLiteOptions rasterOptions;
        rasterOptions.featureOptions() = featureOptions;
        rasterOptions.styles() = new StyleSheet();
        rasterOptions.styles()->addStyle( style );
        map->addImageLayer( new ImageLayer("my features", rasterOptions) );
    }
    else //if (useGeom || useOverlay)
    {
        FeatureGeomModelOptions geomOptions;
        geomOptions.featureOptions() = featureOptions;
        geomOptions.styles() = new StyleSheet();
        geomOptions.styles()->addStyle( style );
        geomOptions.enableLighting() = false;

        ModelLayerOptions layerOptions( "my features", geomOptions );
        map->addModelLayer( new ModelLayer(layerOptions) );
    }

    if ( useLabels )
    {
        // set up symbology for drawing labels. We're pulling the label
        // text from the name attribute, and its draw priority from the
        // population attribute.
        Style labelStyle;

        TextSymbol* text = labelStyle.getOrCreateSymbol<TextSymbol>();
        text->content() = StringExpression( "[cntry_name]" );
        text->priority() = NumericExpression( "[pop_cntry]" );
        text->removeDuplicateLabels() = true;
        text->size() = 16.0f;
        text->alignment() = TextSymbol::ALIGN_CENTER_CENTER;
        text->fill()->color() = Color::White;
        text->halo()->color() = Color::DarkGray;

        // and configure a model layer:
        FeatureGeomModelOptions geomOptions;
        geomOptions.featureOptions() = featureOptions;
        geomOptions.styles() = new StyleSheet();
        geomOptions.styles()->addStyle( labelStyle );

        map->addModelLayer( new ModelLayer("labels", geomOptions) );
    }

    if ( !useStencil )
        viewer.getCamera()->addCullCallback( new osgEarth::Util::AutoClipPlaneCullCallback(mapNode) );

    // add some stock OSG handlers:
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

    return viewer.run();
}
示例#9
0
//
// NOTE: run this sample from the repo/tests directory.
//
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    bool useRaster  = arguments.read("--rasterize");
    bool useOverlay = arguments.read("--overlay");
    bool useStencil = arguments.read("--stencil");
    bool useMem     = arguments.read("--mem");
    bool useLabels  = arguments.read("--labels");

    osgViewer::Viewer viewer(arguments);

    // Start by creating the map:
    Map* map = new Map();

    // Start with a basemap imagery layer; we'll be using the GDAL driver
    // to load a local GeoTIFF file:
    GDALOptions basemapOpt;
    basemapOpt.url() = "../data/world.tif";
    map->addImageLayer( new ImageLayer( ImageLayerOptions("basemap", basemapOpt) ) );

    // Next we add a feature layer. First configure a feature driver to 
    // load the vectors from a shapefile:
    OGRFeatureOptions featureOpt;
    if ( !useMem )
    {
        featureOpt.url() = "../data/usa.shp";
    }
    else
    {
        Ring* line = new Ring();
        line->push_back( osg::Vec3d(-60, 20, 0) );
        line->push_back( osg::Vec3d(-120, 20, 0) );
        line->push_back( osg::Vec3d(-120, 60, 0) );
        line->push_back( osg::Vec3d(-60, 60, 0) );
        featureOpt.geometry() = line;
    }

    // Define a style for the feature data. Since we are going to render the
    // vectors as lines, configure the line symbolizer:
    Style style;

    LineSymbol* ls = style.getOrCreateSymbol<LineSymbol>();
    ls->stroke()->color() = osg::Vec4f( 1,1,0,1 ); // yellow
    ls->stroke()->width() = 2.0f;

    // Add some text labels.
    if ( useLabels )
    {
        TextSymbol* text = style.getOrCreateSymbol<TextSymbol>();
        text->provider() = "overlay";
        text->content() = StringExpression( "[name]" );
        text->priority() = NumericExpression( "[area]" );
        text->removeDuplicateLabels() = true;
        text->size() = 16.0f;
        text->fill()->color() = Color::White;
        text->halo()->color() = Color::DarkGray;
    }

    // That's it, the map is ready; now create a MapNode to render the Map:
    MapNodeOptions mapNodeOptions;
    mapNodeOptions.enableLighting() = false;

    MapNode* mapNode = new MapNode( map, mapNodeOptions );

    // Now we'll choose the AGG-Lite driver to render the features. By the way, the
    // feature data is actually polygons, so we override that to treat it as lines.
    // We apply the feature driver and set the style as well.
    if (useStencil)
    {
        FeatureStencilModelOptions worldOpt;
        worldOpt.featureOptions() = featureOpt;
        worldOpt.geometryTypeOverride() = Geometry::TYPE_LINESTRING;
        worldOpt.styles() = new StyleSheet();
        worldOpt.styles()->addStyle( style );
        worldOpt.enableLighting() = false;
        worldOpt.depthTestEnabled() = false;
        map->addModelLayer( new ModelLayer( "my features", worldOpt ) );
    }
    else if (useRaster)
    {
        AGGLiteOptions worldOpt;
        worldOpt.featureOptions() = featureOpt;
        worldOpt.geometryTypeOverride() = Geometry::TYPE_LINESTRING;
        worldOpt.styles() = new StyleSheet();
        worldOpt.styles()->addStyle( style );
        map->addImageLayer( new ImageLayer( ImageLayerOptions("world", worldOpt) ) );
    }
    else //if (useGeom || useOverlay)
    {
        FeatureGeomModelOptions worldOpt;
        worldOpt.featureOptions() = featureOpt;
        worldOpt.geometryTypeOverride() = Geometry::TYPE_LINESTRING;
        worldOpt.styles() = new StyleSheet();
        worldOpt.styles()->addStyle( style );
        worldOpt.enableLighting() = false;
        worldOpt.depthTestEnabled() = false;

        ModelLayerOptions options( "my features", worldOpt );
        options.overlay() = useOverlay;
        map->addModelLayer( new ModelLayer(options) );
    }

    viewer.setSceneData( mapNode );
    viewer.setCameraManipulator( new EarthManipulator() );

    if ( !useStencil && !useOverlay )
        viewer.addEventHandler( new osgEarth::Util::AutoClipPlaneHandler );

    // add some stock OSG handlers:
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

    return viewer.run();
}
示例#10
0
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    if (argc < 2)
    {
        return usage("");
    }
    
    //The first level
    unsigned int firstLevel = 0;
    while (arguments.read("--first-level", firstLevel));

    //The max level
    unsigned int maxLevel = 6;
    while (arguments.read("--max-level", maxLevel));

    unsigned int maxFeatures = 300;
    while (arguments.read("--max-features", maxFeatures));    

    //The destination directory
    std::string destination = "out";
    while (arguments.read("--out", destination));

    //The name of the layer
    std::string layer = "layer";
    while (arguments.read("--layer", layer));

    //The description of the layer
    std::string description = "";
    while (arguments.read("--description", description));

    std::string queryExpression = "";
    while (arguments.read("--expression", queryExpression));

    std::string queryOrderBy = "";
    while (arguments.read("--order-by", queryOrderBy));

    CropFilter::Method cropMethod = CropFilter::METHOD_CENTROID;
    if (arguments.read("--crop"))
    {
        cropMethod = CropFilter::METHOD_CROPPING;
    }

    std::string destSRS;
    while(arguments.read("--dest-srs", destSRS));

    // Custom bounding box
    Bounds bounds;
    double xmin=DBL_MAX, ymin=DBL_MAX, xmax=DBL_MIN, ymax=DBL_MIN;
    while (arguments.read("--bounds", xmin, ymin, xmax, ymax ))
    {
        bounds.xMin() = xmin;
        bounds.yMin() = ymin;
        bounds.xMax() = xmax;
        bounds.yMax() = ymax;
    }
    
    std::string filename;

    //Get the first argument that is not an option
    for(int pos=1;pos<arguments.argc();++pos)
    {
        if (!arguments.isOption(pos))
        {
            filename  = arguments[ pos ];
            break;
        }
    }

    if (filename.empty())
    {
        return usage( "Please provide a filename" );
    }

    //Open the feature source
    OGRFeatureOptions featureOpt;
    featureOpt.url() = filename;

    osg::ref_ptr< FeatureSource > features = FeatureSourceFactory::create( featureOpt );
    if (!features.valid())
    {
        OE_NOTICE << "Failed to open " << filename << std::endl;
        return 1;
    }

    features->initialize();
    const FeatureProfile* profile = features->getFeatureProfile();
    if (!profile)
    {
        OE_NOTICE << "Failed to create a valid profile for " << filename << std::endl;
        return 1;
    }

    std::string method = cropMethod == CropFilter::METHOD_CENTROID ? "Centroid" : "Cropping";

    OE_NOTICE << "Processing " << filename << std::endl
              << "  FirstLevel=" << firstLevel << std::endl
              << "  MaxLevel=" << maxLevel << std::endl
              << "  MaxFeatures=" << maxFeatures << std::endl
              << "  Destination=" << destination << std::endl
              << "  Layer=" << layer << std::endl
              << "  Description=" << description << std::endl
              << "  Expression=" << queryExpression << std::endl
              << "  OrderBy=" << queryOrderBy << std::endl
              << "  Method= " << method << std::endl
              << "  DestSRS= " << destSRS << std::endl
              << std::endl;


    Query query;
    if (!queryExpression.empty())
    {
        query.expression() = queryExpression;
    }

    if (!queryOrderBy.empty())
    {
        query.orderby() = queryOrderBy;
    }    

    osg::Timer_t startTime = osg::Timer::instance()->tick();
    //buildTFS( features.get(), firstLevel, maxLevel, maxFeatures, destination, layer, description, query, cropMethod);
    TFSPackager packager;
    packager.setFirstLevel( firstLevel );
    packager.setMaxLevel( maxLevel );
    packager.setMaxFeatures( maxFeatures );
    packager.setQuery( query );
    packager.setMethod( cropMethod );    
    packager.setDestSRS( destSRS );
    if (bounds.isValid())
    {
        packager.setLod0Extent(GeoExtent(osgEarth::SpatialReference::create( destSRS ), bounds));
    }
    packager.package( features, destination, layer, description );
    osg::Timer_t endTime = osg::Timer::instance()->tick();
    OE_NOTICE << "Completed in " << osg::Timer::instance()->delta_s( startTime, endTime ) << " s " << std::endl;

    return 0;
}