Beispiel #1
0
Control*
MouseCoordsControlFactory::create(MapNode*         mapNode,
                                  osgViewer::View* view     ) const
{
    // readout for coordinates under the mouse   
    LabelControl* readout = new LabelControl();
    readout->setHorizAlign( Control::ALIGN_RIGHT );
    readout->setVertAlign( Control::ALIGN_BOTTOM );

    Formatter* formatter = new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES);
    MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
    mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
    view->addEventHandler( mcTool );

    return readout;
}
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    osgViewer::Viewer viewer(arguments);

    bool test1 = arguments.read("--test1");
    bool test5 = arguments.read("--test5");
    bool ok    = test1 || test5;

    if ( !ok )
    {
        return usage("");
    }

    if ( !test5 )
    {
        osg::Node* earthNode = osgDB::readNodeFiles( arguments );
        if (!earthNode)
        {
            return usage( "Unable to load earth model." );
        }

        viewer.setCameraManipulator( new osgEarth::Util::EarthManipulator() );

        LabelControl* label = new LabelControl();
        if ( !test5 )
            ControlCanvas::get(&viewer,true)->addControl(label);

        if ( test1 )
        {
            viewer.setSceneData( TEST_1::run(earthNode) );
            label->setText( "Function injection test: the map should appear hazy." );
        }
    }
    else // if ( test5 )
    {
        viewer.setSceneData( TEST_5::run() );
    }

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

    return viewer.run();
}
void
createInactiveLayerItem( Grid* grid, int gridRow, const std::string& name, const ConfigOptions& lc )
{
    int gridCol = 0;

    // the layer name
    LabelControl* nameLabel = new LabelControl( name );
    grid->setControl( gridCol, gridRow, nameLabel );
    gridCol++;
    
    LabelControl* addRemove = new LabelControl( "ADD", 14 );
    addRemove->setHorizAlign( Control::ALIGN_CENTER );
    addRemove->setBackColor( .4,.4,.4,1 );
    addRemove->setActiveColor( .8,0,0,1 );
    addRemove->addEventHandler( new AddLayerHandler(lc) );
    grid->setControl( gridCol, gridRow, addRemove );
}
void ChooseServerForm::PositionColumns() {
    ListControl *plstc = (ListControl *)GetControlPtr(kidcServerList);
    Rect rcList;
    plstc->GetRect(&rcList);
    Font *pfnt = plstc->GetFont();

    LabelControl *plblPlayers = (LabelControl *)GetControlPtr(kidcNumPlayers);
    int cxNumPlayers = pfnt->GetTextExtent(plblPlayers->GetText());
    int xNumPlayers = rcList.right - cxNumPlayers;
    LabelControl *plblStatus = (LabelControl *)GetControlPtr(kidcServerStatus);
    int cxStatus = pfnt->GetTextExtent(plblStatus->GetText());
    int xStatus = xNumPlayers - 40 - cxStatus;
    int xLocation = rcList.left + (xStatus - rcList.left) / 2;
    int xName = rcList.left;
    
    plstc->SetTabStops(xName - rcList.left, xLocation - rcList.left,
            xStatus + cxStatus / 2 - rcList.left,
            xNumPlayers + cxNumPlayers / 2 - rcList.left);
    plstc->SetTabFlags(0, 0, kfLstTabCenterOn, kfLstTabCenterOn);

    word ids[] = { kidcServerName, kidcServerLocation, kidcServerStatus,
            kidcNumPlayers };
    int ax[] = { xName, xLocation, xStatus, xNumPlayers };

    for (int i = 0; i < ARRAYSIZE(ids); i++) {
        LabelControl *plbl = (LabelControl *)GetControlPtr(ids[i]);
        Rect rcCtl;
        plbl->GetRect(&rcCtl);
        plbl->SetPosition(ax[i], rcCtl.top);
    }
}
void DownloadMissionPackForm::ShowStatus(void *ctx, const char *psz) {
    if (ctx == CTX_INDEX) {
        ListControl *plstc = (ListControl *)GetControlPtr(kidcMissionPackList);
        plstc->Clear();
        plstc->SetTabStops(0);
        plstc->SetTabFlags(0);
        plstc->Add(psz, NULL);
    }

    if (ctx == CTX_INFO) {
        LabelControl *plbl =
                (LabelControl *)GetControlPtr(kidcMissionPackInfo);
        plbl->SetText((char *)psz);
    }

    // Force the frame draw, since this gets called while the main loop
    // is "asleep".
    gpmfrmm->DrawFrame(false);
}
void DownloadMissionPackForm::HideShow() {
    ListControl *plstc = (ListControl *)GetControlPtr(kidcMissionPackList);
    LabelControl *plbl = (LabelControl *)GetControlPtr(kidcMissionPackInfo);
    ButtonControl *pbtn = (ButtonControl *)GetControlPtr(kidcOk);
    int selected = plstc->GetSelectedItemIndex();
    if (selected < 0) {
        gppim->Reset();
        plbl->SetText("");
        pbtn->Show(false);
        GetControlPtr(kidcDiscuss)->Show(false);
        return;
    }

    // Get the pack info for this pack
       
    IndexEntry *entry = (IndexEntry *)plstc->GetSelectedItemData();
    if (entry == NULL) {
        return;
    }
        
    char *psz = NULL;
    switch (gppackm->IsInstalled(&entry->packid)) {
    case 0:
        psz = "DOWNLOAD";
        break;

    case 1:
        psz = "REMOVE";
        break;

    case 2:
        psz = "UPGRADE";
        break;
    }
    if (psz != NULL) {
        pbtn->SetText(psz);
    }

    pbtn->Show(true);
    ShowInfo(true);
}
    void
    addControls(GammaColorFilter* filter, Container* container, unsigned i)
    {
        // the outer container:
        Grid* s_layerBox = container->addControl(new Grid());
        s_layerBox->setBackColor(0,0,0,0.5);
        s_layerBox->setMargin( 10 );
        s_layerBox->setPadding( 10 );
        s_layerBox->setChildSpacing( 10 );
        s_layerBox->setChildVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setAbsorbEvents( true );
        s_layerBox->setVertAlign( Control::ALIGN_TOP );

        // Title:
        s_layerBox->setControl( 0, 0, new LabelControl(Stringify()<<"Layer "<<i, Color::Yellow) );
        
        // Gamma:
        LabelControl* gLabel = new LabelControl( "Gamma" );      
        gLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 1, gLabel );

        HSliderControl* gAdjust = new HSliderControl( 0.1f, 3.0f, 1.0f, new GAMMA::Set(filter) );
        gAdjust->setWidth( 125 );
        gAdjust->setHeight( 12 );
        gAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 1, gAdjust );
        s_layerBox->setControl( 2, 1, new LabelControl(gAdjust) );

        // Reset button
        LabelControl* resetButton = new LabelControl( "Reset" );
        resetButton->setBackColor( Color::Gray );
        resetButton->setActiveColor( Color::Blue );
        resetButton->addEventHandler( new Reset(gAdjust) );
        s_layerBox->setControl( 1, 3, resetButton );
    }
    void
    addControls(BrightnessContrastColorFilter* filter, Container* container, unsigned i)
    {
        // the outer container:
        Grid* s_layerBox = container->addControl(new Grid());
        s_layerBox->setBackColor(0,0,0,0.5);
        s_layerBox->setMargin( 10 );
        s_layerBox->setPadding( 10 );
        s_layerBox->setChildSpacing( 10 );
        s_layerBox->setChildVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setAbsorbEvents( true );
        s_layerBox->setVertAlign( Control::ALIGN_TOP );

        // Title:
        s_layerBox->setControl( 0, 0, new LabelControl(Stringify()<<"Layer "<<i, Color::Yellow) );
        
        // Brightness:
        LabelControl* bLabel = new LabelControl( "Brightness" );      
        bLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 1, bLabel );

        HSliderControl* bAdjust = new HSliderControl( 0.0f, 5.0f, 1.0f, new BC::Set(filter,0) );
        bAdjust->setWidth( 125 );
        bAdjust->setHeight( 12 );
        bAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 1, bAdjust );
        s_layerBox->setControl( 2, 1, new LabelControl(bAdjust) );

        // Contrast:
        LabelControl* cLabel = new LabelControl( "Contrast" );      
        cLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 2, cLabel );

        HSliderControl* cAdjust = new HSliderControl( 0.0f, 5.0f, 1.0f, new BC::Set(filter,1) );
        cAdjust->setWidth( 125 );
        cAdjust->setHeight( 12 );
        cAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 2, cAdjust );
        s_layerBox->setControl( 2, 2, new LabelControl(cAdjust) );

        // Reset button
        LabelControl* resetButton = new LabelControl( "Reset" );
        resetButton->setBackColor( Color::Gray );
        resetButton->setActiveColor( Color::Blue );
        resetButton->addEventHandler( new Reset(bAdjust, cAdjust) );
        s_layerBox->setControl( 1, 3, resetButton );
    }
bool DownloadMissionPackForm::Init(FormMgr *pfrmm, IniReader *pini, word idf) {
	if (!ShellForm::Init(pfrmm, pini, idf)) {
		return false;
    }

    // Start downloading the mission pack index

    if (!idxl_.Start(CTX_INDEX, this)) {
        return false;
    }

    // No operation is available until a mission is selected

    GetControlPtr(kidcOk)->Show(false);
    GetControlPtr(kidcDiscuss)->Show(false);

    // Show status

    ShowStatus(CTX_INDEX, "Contacting Server...");

    // Position Column labels
    
    PositionColumns();

    // Set info label to use ellipsis

    LabelControl *plbl = (LabelControl *)GetControlPtr(kidcMissionPackInfo);
    plbl->SetFlags(plbl->GetFlags() | kfLblEllipsis);

    // No sorting yet

    idSortIndicator_ = 0;
    sort_ = HttpIndexLoader::SORT_UNSORTED;

    return true;
}
bool ChooseServerForm::DoModal(int *pnResult) {
    // Hide Connect button until there is something to connect to
    LabelControl *plbl = (LabelControl *)GetControlPtr(kidcOk);
    plbl->Show(false);

    // Position the columns
    PositionColumns();
    Refresh(false);

    // If there is a single entry this client can connect to, use it without
    // presenting UI
    if (infos_.size() == 1) {
        Control *pctl = GetControlPtr(kidcOk);
        if (pctl->GetFlags() & kfCtlVisible) {
            const ServerInfo& info = infos_[0];
            if (Connect(info) == knTransportOpenResultSuccess) {
                *pnResult = kidcOk;
                return true;
            }
        }
    }

    return ShellForm::DoModal(pnResult); 
}
void CreateGameForm::UpdateLabels() {
    // Update Game Speed label
    
    char szT[80];
    GetSpeedMultiplierString(szT, m_tGameSpeed);
    LabelControl *plbl = (LabelControl *)GetControlPtr(kidcGameSpeedLabel);
    plbl->SetText(szT);
    
    // Update Mission Pack Info label
    
    plbl = (LabelControl *)GetControlPtr(kidcMissionPackInfo);
    ListControl *plstc = m_aplstc[IndexFromMissionType(m_mt)];
    if (plstc->GetSelectedItemIndex() == -1) {
        plbl->SetText("");
        return;
    }
    int i = (int)plstc->GetSelectedItemData();
    MissionIdentifier miid;
    if (!m_pml->GetMissionIdentifier(i, &miid)) {
        plbl->SetText("");
        return;
    }
    json::JsonMap *map = gppim->GetInfoMap(&miid.packid);
    if (map == NULL) {
        MissionDescription md;
        if (!m_pml->GetMissionDescription(i, &md)) {
            plbl->SetText("");
            return;
        }
        const char *s;
        if (miid.packid.id == PACKID_MAIN) {
            s = base::Format::ToString("%s by Spiffcode, Inc.",
                                       md.szPackName);
        } else {
            s = md.szPackName;
        }
        plbl->SetText((char *)s);
        return;
    }
    const char *szAuthor = GetString(map, "a");
    const char *szTitle = GetString(map, "t");
    const char *s = base::Format::ToString("%s by %s", szTitle, szAuthor);
    plbl->SetText((char *)s);
    delete map;
}
    void
    addControls(CMYKColorFilter* filter, Container* container, unsigned i)
    {
        // the outer container:
        Grid* s_layerBox = container->addControl(new Grid());
        s_layerBox->setBackColor(0,0,0,0.5);
        s_layerBox->setMargin( 10 );
        s_layerBox->setPadding( 10 );
        s_layerBox->setChildSpacing( 10 );
        s_layerBox->setChildVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setAbsorbEvents( true );
        s_layerBox->setVertAlign( Control::ALIGN_TOP );

        // Title:
        s_layerBox->setControl( 0, 0, new LabelControl(Stringify()<<"Layer "<<i, Color::Yellow) );
        
        // Cyan:
        LabelControl* cLabel = new LabelControl( "Cyan" );      
        cLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 1, cLabel );

        HSliderControl* cAdjust = new HSliderControl( -1.0f, 1.0f, 0.0f, new CMYK::Set(filter,0) );
        cAdjust->setWidth( 125 );
        cAdjust->setHeight( 12 );
        cAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 1, cAdjust );
        s_layerBox->setControl( 2, 1, new LabelControl(cAdjust) );

        // Magenta:
        LabelControl* mLabel = new LabelControl( "Magenta" );      
        mLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 2, mLabel );

        HSliderControl* mAdjust = new HSliderControl( -1.0f, 1.0f, 0.0f, new CMYK::Set(filter,1) );
        mAdjust->setWidth( 125 );
        mAdjust->setHeight( 12 );
        mAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 2, mAdjust );
        s_layerBox->setControl( 2, 2, new LabelControl(mAdjust) );

        // Yellow
        LabelControl* yLabel = new LabelControl( "Yellow" );      
        yLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 3, yLabel );

        HSliderControl* yAdjust = new HSliderControl( -1.0f, 1.0f, 0.0f, new CMYK::Set(filter,2) );
        yAdjust->setWidth( 125 );
        yAdjust->setHeight( 12 );
        yAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 3, yAdjust );
        s_layerBox->setControl( 2, 3, new LabelControl(yAdjust) );

        // Black
        LabelControl* kLabel = new LabelControl( "Black" );      
        kLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 4, kLabel );

        HSliderControl* kAdjust = new HSliderControl( -1.0f, 1.0f, 0.0f, new CMYK::Set(filter,3) );
        kAdjust->setWidth( 125 );
        kAdjust->setHeight( 12 );
        kAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 4, kAdjust );
        s_layerBox->setControl( 2, 4, new LabelControl(kAdjust) );

        // Reset button
        LabelControl* resetButton = new LabelControl( "Reset" );
        resetButton->setBackColor( Color::Gray );
        resetButton->setActiveColor( Color::Blue );
        resetButton->addEventHandler( new Reset(cAdjust, mAdjust, yAdjust, kAdjust) );
        s_layerBox->setControl( 1, 5, resetButton );
    }
Beispiel #13
0
void
MapNodeHelper::parse(MapNode*             mapNode,
                     osg::ArgumentParser& args,
                     osgViewer::View*     view,
                     osg::Group*          root,
                     Container*           userContainer ) const
{
    if ( !root )
        root = mapNode;

    // options to use for the load
    osg::ref_ptr<osgDB::Options> dbOptions = Registry::instance()->cloneOrCreateOptions();

    // parse out custom example arguments first:
    bool useMGRS       = args.read("--mgrs");
    bool useDMS        = args.read("--dms");
    bool useDD         = args.read("--dd");
    bool useCoords     = args.read("--coords") || useMGRS || useDMS || useDD;

    bool useAutoClip   = args.read("--autoclip");
    bool animateSky    = args.read("--animate-sky");
    bool showActivity  = args.read("--activity");
    bool useLogDepth   = args.read("--logdepth");
    bool useLogDepth2  = args.read("--logdepth2");
    bool kmlUI         = args.read("--kmlui");

    if (args.read("--verbose"))
        osgEarth::setNotifyLevel(osg::INFO);
    
    if (args.read("--quiet"))
        osgEarth::setNotifyLevel(osg::FATAL);

    float ambientBrightness = 0.2f;
    args.read("--ambientBrightness", ambientBrightness);

    std::string kmlFile;
    args.read( "--kml", kmlFile );

    std::string imageFolder;
    args.read( "--images", imageFolder );

    std::string imageExtensions;
    args.read("--image-extensions", imageExtensions);
    
    // animation path:
    std::string animpath;
    if ( args.read("--path", animpath) )
    {
        view->setCameraManipulator( new osgGA::AnimationPathManipulator(animpath) );
    }

    // Install a new Canvas for our UI controls, or use one that already exists.
    ControlCanvas* canvas = ControlCanvas::getOrCreate( view );

    Container* mainContainer;
    if ( userContainer )
    {
        mainContainer = userContainer;
    }
    else
    {
        mainContainer = new VBox();
        mainContainer->setAbsorbEvents( true );
        mainContainer->setBackColor( Color(Color::Black, 0.8) );
        mainContainer->setHorizAlign( Control::ALIGN_LEFT );
        mainContainer->setVertAlign( Control::ALIGN_BOTTOM );
    }
    canvas->addControl( mainContainer );

    // Add an event handler to toggle the canvas with a key press;
    view->addEventHandler(new ToggleCanvasEventHandler(canvas) );




    // look for external data in the map node:
    const Config& externals = mapNode->externalConfig();

    //const Config& screenSpaceLayoutConf = 
    //    externals.hasChild("screen_space_layout") ? externals.child("screen_space_layout") :
    //    externals.child("decluttering"); // backwards-compatibility


    // some terrain effects.
    // TODO: Most of these are likely to move into extensions.
    const Config& lodBlendingConf = externals.child("lod_blending");
    const Config& vertScaleConf   = externals.child("vertical_scale");

    // Shadowing.
    if (args.read("--shadows"))
    {
        int unit;
        if ( mapNode->getTerrainEngine()->getResources()->reserveTextureImageUnit(unit, "ShadowCaster") )
        {
            ShadowCaster* caster = new ShadowCaster();
            caster->setTextureImageUnit( unit );
            caster->setLight( view->getLight() );
            caster->getShadowCastingGroup()->addChild( mapNode );
            if ( mapNode->getNumParents() > 0 )
            {
                insertGroup(caster, mapNode->getParent(0));
            }
            else
            {
                caster->addChild(mapNode);
                root = caster;
            }
        }
    }

    // Loading KML from the command line:
    if ( !kmlFile.empty() )
    {
        KMLOptions kml_options;
        kml_options.declutter() = true;

        // set up a default icon for point placemarks:
        IconSymbol* defaultIcon = new IconSymbol();
        defaultIcon->url()->setLiteral(KML_PUSHPIN_URL);
        kml_options.defaultIconSymbol() = defaultIcon;

        TextSymbol* defaultText = new TextSymbol();
        defaultText->halo() = Stroke(0.3,0.3,0.3,1.0);
        kml_options.defaultTextSymbol() = defaultText;

        osg::Node* kml = KML::load( URI(kmlFile), mapNode, kml_options );
        if ( kml )
        {
            if (kmlUI)
            {
                Control* c = AnnotationGraphControlFactory().create(kml, view);
                if ( c )
                {
                    c->setVertAlign( Control::ALIGN_TOP );
                    canvas->addControl( c );
                }
            }
            root->addChild( kml );
        }
        else
        {
            OE_NOTICE << "Failed to load " << kmlFile << std::endl;
        }
    }

    //// Configure the de-cluttering engine for labels and annotations:
    //if ( !screenSpaceLayoutConf.empty() )
    //{
    //    ScreenSpaceLayout::setOptions( ScreenSpaceLayoutOptions(screenSpaceLayoutConf) );
    //}

    // Configure the mouse coordinate readout:
    if ( useCoords )
    { 
        LabelControl* readout = new LabelControl();
        readout->setBackColor( Color(Color::Black, 0.8) );
        readout->setHorizAlign( Control::ALIGN_RIGHT );
        readout->setVertAlign( Control::ALIGN_BOTTOM );

        Formatter* formatter = 
            useMGRS ? (Formatter*)new MGRSFormatter(MGRSFormatter::PRECISION_1M, 0L, MGRSFormatter::USE_SPACES) :
            useDMS  ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DEGREES_MINUTES_SECONDS) :
            useDD   ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES) :
            0L;

        MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
        mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
        view->addEventHandler( mcTool );

        canvas->addControl( readout );
    }

    // Configure for an ortho camera:
    if ( args.read("--ortho") )
    {
        view->getCamera()->setProjectionMatrixAsOrtho(-1, 1, -1, 1, 0, 1);
    }

    // activity monitor (debugging)
    if ( showActivity )
    {
        VBox* vbox = new VBox();
        vbox->setBackColor( Color(Color::Black, 0.8) );
        vbox->setHorizAlign( Control::ALIGN_RIGHT );
        vbox->setVertAlign( Control::ALIGN_BOTTOM );
        view->addEventHandler( new ActivityMonitorTool(vbox) );
        canvas->addControl( vbox );
    }

    // Install an auto clip plane clamper
    if ( useAutoClip )
    {
        mapNode->addCullCallback( new AutoClipPlaneCullCallback(mapNode) );
    }

    // Install logarithmic depth buffer on main camera
    if ( useLogDepth )
    {
        OE_INFO << LC << "Activating logarithmic depth buffer (vertex-only) on main camera" << std::endl;
        osgEarth::Util::LogarithmicDepthBuffer logDepth;
        logDepth.setUseFragDepth( false );
        logDepth.install( view->getCamera() );
    }

    else if ( useLogDepth2 )
    {
        OE_INFO << LC << "Activating logarithmic depth buffer (precise) on main camera" << std::endl;
        osgEarth::Util::LogarithmicDepthBuffer logDepth;
        logDepth.setUseFragDepth( true );
        logDepth.install( view->getCamera() );
    }

    // Scan for images if necessary.
    if ( !imageFolder.empty() )
    {
        std::vector<std::string> extensions;
        if ( !imageExtensions.empty() )
            StringTokenizer( imageExtensions, extensions, ",;", "", false, true );
        if ( extensions.empty() )
            extensions.push_back( "tif" );

        OE_INFO << LC << "Loading images from " << imageFolder << "..." << std::endl;
        ImageLayerVector imageLayers;
        DataScanner scanner;
        scanner.findImageLayers( imageFolder, extensions, imageLayers );

        if ( imageLayers.size() > 0 )
        {
            mapNode->getMap()->beginUpdate();
            for( ImageLayerVector::iterator i = imageLayers.begin(); i != imageLayers.end(); ++i )
            {
                mapNode->getMap()->addImageLayer( i->get() );
            }
            mapNode->getMap()->endUpdate();
        }
        OE_INFO << LC << "...found " << imageLayers.size() << " image layers." << std::endl;
    }

    // Install elevation morphing
    if ( !lodBlendingConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new LODBlending(lodBlendingConf) );
    }

    // Install vertical scaler
    if ( !vertScaleConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new VerticalScale(vertScaleConf) );
    }

    // Install a contour map effect.
    if (args.read("--contourmap"))
    {
        mapNode->addExtension(Extension::create("contourmap", ConfigOptions()));

        // with the cmdline switch, hids all the image layer so we can see the contour map.
        for (unsigned i = 0; i < mapNode->getMap()->getNumImageLayers(); ++i) {
            mapNode->getMap()->getImageLayerAt(i)->setVisible(false);
        }
    }

    // Generic named value uniform with min/max.
    VBox* uniformBox = 0L;
    while( args.find( "--uniform" ) >= 0 )
    {
        std::string name;
        float minval, maxval;
        if ( args.read( "--uniform", name, minval, maxval ) )
        {
            if ( uniformBox == 0L )
            {
                uniformBox = new VBox();
                uniformBox->setBackColor(0,0,0,0.5);
                uniformBox->setAbsorbEvents( true );
                canvas->addControl( uniformBox );
            }
            osg::Uniform* uniform = new osg::Uniform(osg::Uniform::FLOAT, name);
            uniform->set( minval );
            root->getOrCreateStateSet()->addUniform( uniform, osg::StateAttribute::OVERRIDE );
            HBox* box = new HBox();
            box->addControl( new LabelControl(name) );
            HSliderControl* hs = box->addControl( new HSliderControl(minval, maxval, minval, new ApplyValueUniform(uniform)));
            hs->setHorizFill(true, 200);
            box->addControl( new LabelControl(hs) );
            uniformBox->addControl( box );
            OE_INFO << LC << "Installed uniform controller for " << name << std::endl;
        }
    }

    // Map inspector:
    if (args.read("--inspect"))
    {
        mapNode->addExtension( Extension::create("mapinspector", ConfigOptions()) );
    }

    // Memory monitor:
    if (args.read("--monitor"))
    {
        mapNode->addExtension(Extension::create("monitor", ConfigOptions()) );
    }

    // Simple sky model:
    if (args.read("--sky"))
    {
        mapNode->addExtension(Extension::create("sky_simple", ConfigOptions()) );
    }

    // Simple ocean model:
    if (args.read("--ocean"))
    {
        mapNode->addExtension(Extension::create("ocean_simple", ConfigOptions()));
    }
    

    // Hook up the extensions!
    for(std::vector<osg::ref_ptr<Extension> >::const_iterator eiter = mapNode->getExtensions().begin();
        eiter != mapNode->getExtensions().end();
        ++eiter)
    {
        Extension* e = eiter->get();

        // Check for a View interface:
        ExtensionInterface<osg::View>* viewIF = ExtensionInterface<osg::View>::get( e );
        if ( viewIF )
            viewIF->connect( view );

        // Check for a Control interface:
        ExtensionInterface<Control>* controlIF = ExtensionInterface<Control>::get( e );
        if ( controlIF )
            controlIF->connect( mainContainer );
    }

    root->addChild( canvas );
}
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    osgViewer::Viewer viewer(arguments);

    bool test1 = arguments.read("--test1");
    bool test2 = arguments.read("--test2");
    bool test3 = arguments.read("--test3");
    bool test4 = arguments.read("--test4");
    bool test5 = arguments.read("--test5");
    bool ok    = test1 || test2 || test3 || test4 || test5; 

    if ( !ok )
    {
        return usage("");
    }

    osg::Group* root = new osg::Group();
    viewer.setSceneData( root );

    // add a canvas:
    ControlCanvas* canvas = new ControlCanvas();
    root->addChild( canvas );

    // and a label:
    LabelControl* label = new LabelControl();
    canvas->addControl(label);

    if ( !test5 )
    {
        osg::Node* earthNode = osgDB::readNodeFile( "http://osgearth.org/demo.earth" );
        if (!earthNode)
        {
            return usage( "Unable to load earth model." );
        }

        if ( test1 )
        {
            root->addChild( TEST_1::run(earthNode) );
            label->setText( "Function injection test: the map appears hazy at high altitude." );
        }
        else if ( test2 )
        {
            root->addChild( TEST_2::run(earthNode) );
            label->setText( "Accept callback test: the map turns red when viewport width > 1000" );
        }
        else if ( test3 )
        {
            root->addChild( TEST_3::run(earthNode) );
            label->setText( "Shader LOD test: the map turns red between 500K and 1M meters altitude" );
        }
        else if ( test4 )
        {
            root->addChild( TEST_4::run(earthNode) );
            label->setText("Memory management test; monitor memory for stability");
        }
        
        viewer.setCameraManipulator( new osgEarth::Util::EarthManipulator() );
    }
    else // if ( test5 )
    {
        root->addChild( TEST_5::run() );
        label->setText( "Leakage test: red tri on the left, blue on the right." );
    }

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

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

    osgViewer::Viewer viewer(arguments);
    s_viewer = &viewer;

    // Start by creating the map:
    s_mapNode = MapNode::load(arguments);
    if ( !s_mapNode )
    {
        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) ) );

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

        s_mapNode = new MapNode( map, mapNodeOptions );
    }
    s_mapNode->setNodeMask( 0x01 );

        
    // Define a style for the feature data. Since we are going to render the
    // vectors as lines, configure the line symbolizer:
    StyleSheet* styleSheet = buildStyleSheet( Color::Yellow, 2.0f );

    s_source = new FeatureListSource();

    LineString* line = new LineString();
    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) );
    Feature *feature = new Feature(line, s_mapNode->getMapSRS(), Style(), s_fid++);
    s_source->insertFeature( feature );
    s_activeFeature = feature;
  
    s_root = new osg::Group;
    s_root->addChild( s_mapNode.get() );

    Session* session = new Session(s_mapNode->getMap(), styleSheet, s_source.get());

    FeatureModelGraph* graph = new FeatureModelGraph( 
        session,
        FeatureModelSourceOptions(), 
        new GeomFeatureNodeFactory() );

    graph->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    graph->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);

    s_root->addChild( graph );

    //Setup the controls
    ControlCanvas* canvas = ControlCanvas::get( &viewer );
    s_root->addChild( canvas );
    Grid *toolbar = createToolBar( );
    canvas->addControl( toolbar );
    canvas->setNodeMask( 0x1 << 1 );



    int col = 0;
    LabelControl* addVerts = new LabelControl("Add Verts");
    toolbar->setControl(col++, 0, addVerts );    
    addVerts->addEventHandler( new AddVertsModeHandler( graph ));
    
    LabelControl* edit = new LabelControl("Edit");
    toolbar->setControl(col++, 0, edit );    
    edit->addEventHandler(new EditModeHandler( graph ));

    unsigned int row = 0;
    Grid *styleBar = createToolBar( );
    styleBar->setPosition(0, 50);
    canvas->addControl( styleBar );
    
    //Make a list of styles
    styleBar->setControl(0, row++, new LabelControl("Styles") );    

    unsigned int numStyles = 8;
    for (unsigned int i = 0; i < numStyles; ++i)
    {
        float w = 50;
        osg::Vec4 color = randomColor();

        float widths[3] = {2, 4, 8};

        unsigned int r = row++;
        for (unsigned int j = 0; j < 3; j++) 
        {
            Control* l = new Control();            
            l->setBackColor( color );
            l->addEventHandler(new ChangeStyleHandler(graph, buildStyleSheet( color, widths[j] ) ));
            l->setSize(w,5 * widths[j]);
            styleBar->setControl(j, r, l);
        }
    }
   
    
    viewer.setSceneData( s_root.get() );
    viewer.setCameraManipulator( new EarthManipulator() );

    if ( s_mapNode )
        viewer.getCamera()->addCullCallback( new osgEarth::Util::AutoClipPlaneCullCallback(s_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();
}
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    osgViewer::Viewer viewer(arguments);

    bool test1 = arguments.read("--test1");
    bool test2 = arguments.read("--test2");
    bool test3 = arguments.read("--test3");
    bool test4 = arguments.read("--test4");
    bool test5 = arguments.read("--test5");
    bool test6 = arguments.read("--test6");
    bool test7 = arguments.read("--test7");
    bool test8 = arguments.read("--test8");
    bool test9 = arguments.read("--test9");
    bool ok    = test1 || test2 || test3 || test4 || test5 || test6 || test7 || test8||test9;

    bool ui = !arguments.read("--noui");

    if ( !ok )
    {
        return usage("");
    }

    osg::Group* root = new osg::Group();
    viewer.setSceneData( root );
    
    LabelControl* label = new LabelControl();
    if ( ui )
    {
        // add a canvas:
        ControlCanvas* canvas = new ControlCanvas();
        root->addChild( canvas );

        // and a label:
        canvas->addControl(label);
    }

    if ( test1 || test2 || test3 || test4 || test6 )
    {
        osg::Node* earthNode = osgDB::readNodeFile( "gdal_tiff.earth" );
        if (!earthNode)
        {
            return usage( "Unable to load earth model." );
        }

        if ( test1 )
        {
            root->addChild( TEST_1::run(earthNode) );
            if (ui) label->setText( "Function injection test: the map appears hazy at high altitude." );
        }
        else if ( test2 )
        {
            root->addChild( TEST_2::run(earthNode) );
            if (ui) label->setText( "Accept callback test: the map turns red when viewport width > 1000" );
        }
        else if ( test3 )
        {
            root->addChild( TEST_3::run(earthNode) );
            if (ui) label->setText( "Shader LOD test: the map turns red between 500K and 1M meters altitude" );
        }
        else if ( test4 )
        {
            root->addChild( TEST_4::run(earthNode) );
            if (ui) label->setText("Memory management test; monitor memory for stability");
        }
        else if ( test6 )
        {
            root->addChild( TEST_6::run(earthNode) );
            if (ui) label->setText("State Memory Stack test; top row, both=blue. bottom left=red, bottom right=normal.");
        }
        
        viewer.setCameraManipulator( new osgEarth::Util::EarthManipulator() );
    }
    else if ( test5 )
    {
        osgEarth::Registry::instance()->getCapabilities();
        root->addChild( TEST_5::run() );
        if (ui) label->setText( "Leakage test: red tri on the left, blue on the right." );
    }
    else if ( test7 )
    {
        root->addChild( TEST_7::run( osgDB::readNodeFiles(arguments) ) );
        if (ui) label->setText("Geometry Shader Injection Test.");
    }
    else if (test8)
    {
        root->addChild( TEST_8::run() );
        if (ui) label->setText("Serialization test");
    }
    else if (test9)
    {
        osg::Node* earthNode = osgDB::readNodeFile( "readymap.earth" );
        if (!earthNode)
        {
            return usage( "Unable to load earth model." );
        }
        
        root->addChild(TEST_9::run(earthNode));
        if (ui) label->setText("DP Shader Test - see code comments");
        viewer.setCameraManipulator( new osgEarth::Util::EarthManipulator() );
    }


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

    return viewer.run();
}
int
main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    osg::DisplaySettings::instance()->setMinimumNumStencilBits( 8 );


    std::vector< std::string > imageFiles;
    std::vector< Bounds > imageBounds;

    //Read in the image files
    std::string filename;
    Bounds bounds;
    while (arguments.read("--image", filename, bounds.xMin(), bounds.yMin(), bounds.xMax(), bounds.yMax()))
    {
        imageFiles.push_back( filename );
        imageBounds.push_back( bounds );
    }

    if (imageFiles.empty())
    {
      imageFiles.push_back("../data/osgearth.gif");
      imageBounds.push_back( Bounds(-100, 30, -90, 40) );
    }
 

    bool moveVert = arguments.read("--vert");

    // load the .earth file from the command line.
    osg::Node* earthNode = osgDB::readNodeFiles( arguments );
    if (!earthNode)
        return usage( "Unable to load earth model." );

    osgViewer::Viewer viewer(arguments);
    
    EarthManipulator* manip = new EarthManipulator();
    viewer.setCameraManipulator( manip );

    osg::Group* root = new osg::Group();
    root->addChild( earthNode );

    //Create the control panel
    root->addChild( createControlPanel(&viewer) );

    viewer.setSceneData( root );
    
    osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode( earthNode );
    if ( mapNode )
    {

        for (unsigned int i = 0; i < imageFiles.size(); i++)
        {
            std::string imageFile = imageFiles[i];
            //Read the image file and play it if it's a movie
            osg::Image* image = osgDB::readImageFile(imageFile);
            if (image)
            {
                osg::ImageStream* is = dynamic_cast<osg::ImageStream*>(image);
                if (is)
                {
                    is->play();
                }
            }

            //Create a new ImageOverlay and set it's bounds
            //ImageOverlay* overlay = new ImageOverlay(mapNode->getMap()->getProfile()->getSRS()->getEllipsoid(), image);        
            ImageOverlay* overlay = new ImageOverlay(mapNode);
            overlay->setImage( image );
            overlay->setBounds(imageBounds[i]);

            root->addChild( overlay );


            //Create a new ImageOverlayEditor and set it's node mask to 0 to hide it initially
#if OSG_MIN_VERSION_REQUIRED(2,9,6)
            osg::Node* editor = new ImageOverlayEditor( overlay);
#else
            //Just make an empty group for pre-2.9.6
            osg::Node* editor = new osg::Group;
#endif
            editor->setNodeMask( 0 );
            root->addChild( editor );      
            
            // Add an image preview
            ImageControl* imageCon = new ImageControl( image );
            imageCon->setSize( 64, 64 );
            imageCon->setVertAlign( Control::ALIGN_CENTER );
            s_layerBox->setControl( 0, i, imageCon );            


            //Add some controls        
            CheckBoxControl* enabled = new CheckBoxControl( true );
            enabled->addEventHandler( new EnabledHandler(overlay) );
            enabled->setVertAlign( Control::ALIGN_CENTER );
            s_layerBox->setControl( 1, i, enabled );

            //The overlay name
            LabelControl* name = new LabelControl( osgDB::getSimpleFileName( imageFile) );      
            name->setVertAlign( Control::ALIGN_CENTER );
            s_layerBox->setControl( 2, i, name );

            // an opacity slider
            HSliderControl* opacity = new HSliderControl( 0.0f, 1.0f, overlay->getAlpha() );
            opacity->setWidth( 125 );
            opacity->setHeight( 12 );
            opacity->setVertAlign( Control::ALIGN_CENTER );
            opacity->addEventHandler( new OpacityHandler(overlay) );
            s_layerBox->setControl( 3, i, opacity );

            // Add a text label:
            LabelControl* edit = new LabelControl( "Edit" );        
            edit->setVertAlign( Control::ALIGN_CENTER );
            edit->addEventHandler(new EditHandler(overlay, &viewer, editor));
            s_layerBox->setControl(4, i, edit );
        }        
    }

    // osgEarth benefits from pre-compilation of GL objects in the pager. In newer versions of
    // OSG, this activates OSG's IncrementalCompileOpeartion in order to avoid frame breaks.
    viewer.getDatabasePager()->setDoPreCompile( true );

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

    return viewer.run();
}
Beispiel #18
0
void
createControls( ControlCanvas* cs )
{
    // a container centered on the screen, containing an image and a text label.
    {
        VBox* center = new VBox();
        center->setFrame( new RoundedFrame() );
        center->getFrame()->setBackColor( 1,1,1,0.5 );
        center->setPadding( 10 );
        center->setHorizAlign( Control::ALIGN_CENTER );
        center->setVertAlign( Control::ALIGN_CENTER );

        // Add an image:
        osg::Image* image = osgDB::readImageFile( "http://osgearth.org/chrome/site/osgearth.gif" );
        if ( image ) {
            ImageControl* imageCon = new ImageControl( image );
            imageCon->setHorizAlign( Control::ALIGN_CENTER );
            imageCon->setFixSizeForRotation( true );
            imageCon->addEventHandler( new ImageRotationHandler );
            center->addControl( imageCon );
            center->setHorizAlign( Control::ALIGN_CENTER );
        }

        // Add a text label:
        LabelControl* label = new LabelControl( "osgEarth Controls Toolkit" );
        label->setFont( osgText::readFontFile( "arialbd.ttf" ) );
        label->setFontSize( 24.0f );
        label->setHorizAlign( Control::ALIGN_CENTER );
        label->setMargin( 5 );
        center->addControl( label );

        // Add another
        LabelControl* label2 = new LabelControl( "(Click the osgEarth logo to rotate it)" );
        label2->setHorizAlign( Control::ALIGN_CENTER );
        center->addControl( label2 );

        cs->addControl( center );
    }

    // a simple vbox with absolute positioning in the upper left with two text labels.
    {
        VBox* ul = new VBox();
        ul->setFrame( new Frame() );
        ul->setPosition( 20, 20 );
        ul->setPadding( 10 );
        {
            LabelControl* title = new LabelControl( "Upper left control", 22, osg::Vec4f(1,1,0,1) );
            ul->addControl( title );

            LabelControl* content = new LabelControl( "Here is some text in the upper left control" );
            ul->addControl( content );

            HBox* c2 = new HBox();
            c2->setSpacing( 10 );
            {
                HSliderControl* slider = new HSliderControl( 0, 100 );
                slider->setBackColor( .6,0,0,1 );
                slider->setHeight( 25 );
                slider->setWidth( 300 );
                slider->addEventHandler( new MySliderHandler() );
                c2->addControl( slider );

                s_sliderLabel = new LabelControl();
                s_sliderLabel->setVertAlign( Control::ALIGN_CENTER );
                c2->addControl( s_sliderLabel );        
            }
            ul->addControl( c2 );

            HBox* c3 = new HBox();
            c3->setHorizAlign( Control::ALIGN_CENTER );
            c3->setSpacing( 10 );
            {
                HBox* c4 = new HBox();
                c4->setSpacing( 5 );
                {
                    c4->addControl( new CheckBoxControl( true ) );
                    c4->addControl( new LabelControl( "Checkbox 1" ) );
                }
                c3->addControl( c4 );

                HBox* c5 = new HBox();
                c5->setSpacing( 5 );
                {
                    c5->addControl( new CheckBoxControl( false ) );
                    c5->addControl( new LabelControl( "Checkbox 2" ) );
                }
                c3->addControl( c5 );
            }
            ul->addControl( c3 );
        }
        cs->addControl( ul );

        ul->addEventHandler( new MyClickHandler );
    }

    // a centered hbox container along the bottom on the screen.
    {
        HBox* bottom = new HBox();
        bottom->setFrame( new RoundedFrame() );
        bottom->getFrame()->setBackColor(0,0,0,0.5);
        bottom->setMargin( 10 );
        bottom->setSpacing( 145 );
        bottom->setVertAlign( Control::ALIGN_BOTTOM );
        bottom->setHorizAlign( Control::ALIGN_CENTER );

        for( int i=0; i<4; ++i )
        {
            LabelControl* label = new LabelControl();
            std::stringstream buf;
            buf << "Label_" << i;
            label->setText( buf.str() );
            label->setMargin( 10 );
            label->setBackColor( 1,1,1,0.4 );
            bottom->addControl( label );

            label->setActiveColor(1,.3,.3,1);
            label->addEventHandler( new MyClickHandler );
        }

        cs->addControl( bottom );
    }
}
void GesichtertauschApp::update() {
    double mDeltaTime = getElapsedSeconds() - mTime;
    mTime = getElapsedSeconds();
    
    /* heartbeat */
    heartbeat(mDeltaTime);

    {
        stringstream mStr;
        mStr << "FPS: " << getAverageFps();
        mFPSOut->setText(mStr.str());
    }
    setFrameRate( FRAME_RATE );
        

    /* get new faces */
    vector<Rectf> mFaces;
    mFaceDetection->update(mCameraTexture, mFaces);

    {
        stringstream mStr;
        mStr << "FACES: " << mEntities.size();
        mFaceOut->setText(mStr.str());   
    }

    /* rescale from capture to window width */
    Vec2f mScale = Vec2f(float(CAMERA_WIDTH) / float(DETECTION_WIDTH), 
                         float(CAMERA_HEIGHT) / float(DETECTION_HEIGHT));
    mScale.x *= float(WINDOW_WIDTH) / float(CAMERA_WIDTH);
    mScale.y *= float(WINDOW_HEIGHT) / float (CAMERA_HEIGHT);
    for( vector<Rectf>::iterator faceIter = mFaces.begin(); faceIter != mFaces.end(); ++faceIter ) {
        Rectf * mFace = &(*faceIter);
        mFace->x1 *= mScale.x;
        mFace->x2 *= mScale.x;
        mFace->y1 *= mScale.y;
        mFace->y2 *= mScale.y;
    }
    
    /* set all existing entities to dead and invisble*/
    for( vector<FaceEntity>::iterator mIter = mEntities.begin(); mIter != mEntities.end(); ++mIter) {
        FaceEntity* mEntity = &(*mIter);
        mEntity->alive = false;
    }

    /* map new faces to existing entities */
    for( vector<FaceEntity>::iterator mIter = mEntities.begin(); mIter != mEntities.end(); ++mIter) {
        FaceEntity* mEntity = &(*mIter);
        /* test against all new faces */
        for( vector<Rectf>::iterator faceIter = mFaces.begin(); faceIter != mFaces.end(); ) {
            Rectf mFace = *faceIter;
            float mDistance = mFace.getCenter().distance(mEntity->border.getCenter());
            if (mDistance < MIN_TRACKING_DISTANCE) {
//                console() << "### found ID again. (" << mEntity->ID << ")" << mEntity->lifetime << endl;
                // TODO maybe interpolate in a more stable way …
                Vec2f mAveragedP1 = Vec2f(mFace.x1, mFace.y1);
                Vec2f mAveragedP2 = Vec2f(mFace.x2, mFace.y2);
                mAveragedP1 += Vec2f(mEntity->border.x1, mEntity->border.y1);
                mAveragedP2 += Vec2f(mEntity->border.x2, mEntity->border.y2);
                mAveragedP1 *= 0.5;
                mAveragedP2 *= 0.5;
                mEntity->border.set(mAveragedP1.x, mAveragedP1.y,
                                    mAveragedP2.x, mAveragedP2.y);
                mEntity->alive = true;
                mEntity->idletime = 0.0;
                mEntity->lifetime += mDeltaTime;
                mFaces.erase(faceIter);
                break;
            } else {
                ++faceIter;
            }
        }
    }
    
    /* create new entities from left-over faces */
    for( vector<Rectf>::iterator faceIter = mFaces.begin(); faceIter != mFaces.end(); ++faceIter) {
        FaceEntity mNewEntity = FaceEntity();
        mNewEntity.ID = mSerialID++;
//        console() << "### found new face. ID (" << mNewEntity.ID << ")" << endl;
        Rectf mFace = *faceIter;
        mNewEntity.border = mFace;
        mNewEntity.lifetime = 0.0;
        mNewEntity.idletime = 0.0;
        mNewEntity.visible = false;
        mNewEntity.alive = true;
        mEntities.push_back(mNewEntity);
    }
    mFaces.clear();

    /* grant dead entities some extra time */
    for( vector<FaceEntity>::iterator mIter = mEntities.begin(); mIter != mEntities.end(); ++mIter) {
        FaceEntity* mEntity = &(*mIter);
        if (!mEntity->alive) {
            /* if an entity disappeard we ll grant it some seconds before it gets removed */
            if (mEntity->idletime < TIME_BEFOR_IDLE_DEATH) {
                /* start immediately no matter how long entity already lived */
//                if (mEntity->idletime == 0.0) {
//                    console() << "### started dying (" << mEntity->ID << ")" << endl;
//                }
                mEntity->idletime += mDeltaTime;
                mEntity->lifetime += mDeltaTime; /* do we want to count abscence as lifetime? */
                mEntity->alive = true;
            }
        }
    }    
    
    /* erase all dead entities */
    for( vector<FaceEntity>::iterator mIter = mEntities.begin(); mIter != mEntities.end();) {
        FaceEntity mEntity = *mIter;
        if (mEntity.alive) {
            ++mIter;
        } else {
            mEntities.erase(mIter);
        }
    }

    /* set all 'stable' entities to visible */
    for( vector<FaceEntity>::iterator mIter = mEntities.begin(); mIter != mEntities.end(); ++mIter) {
        FaceEntity * mEntity = &(*mIter);
        if (mEntity->lifetime > MIN_LIFETIME_TO_VIEW) {
            mEntity->visible = true;
        } else {
            mEntity->visible = false;
        }
    }

    /* update slice */
    for( vector<FaceEntity>::iterator mIter = mEntities.begin(); mIter != mEntities.end(); ++mIter) {
        FaceEntity * mEntity = &(*mIter);
        mEntity->slice.set(mEntity->border.x1, mEntity->border.y1, mEntity->border.x2, mEntity->border.y2);
    }
}
void DownloadMissionPackForm::Sort(word id) {
    word aidColumns[] = {
        kidcStatus, kidcTitle, kidcNumPlayers, kidcNumMissions
    };

    int iCol;
    for (iCol = 0; iCol < ARRAYSIZE(aidColumns); iCol++) {
        if (id == aidColumns[iCol]) {
            break;
        }
    }
    if (iCol >= ARRAYSIZE(aidColumns)) {
        return;
    }

    HttpIndexLoader::SortType asortFlip[] = {
        HttpIndexLoader::SORT_UNSORTED,
        HttpIndexLoader::SORT_INSTALLEDDESCENDING,
        HttpIndexLoader::SORT_INSTALLEDASCENDING,
        HttpIndexLoader::SORT_TITLEDESCENDING,
        HttpIndexLoader::SORT_TITLEASCENDING,
        HttpIndexLoader::SORT_PLAYERSDESCENDING,
        HttpIndexLoader::SORT_PLAYERSASCENDING,
        HttpIndexLoader::SORT_MISSIONSDESCENDING,
        HttpIndexLoader::SORT_MISSIONSASCENDING
    };

    // If this is already the sort column, flip the sort
    if (id == idSortIndicator_) {
        sort_ = asortFlip[sort_];
        idxl_.Sort(sort_);
        ShowIndex();
        return;
    }

    // Take sort indicator off
    char szT[32];
    if (idSortIndicator_ != 0) {
        LabelControl *plbl = (LabelControl *)GetControlPtr(idSortIndicator_);
        strncpyz(szT, plbl->GetText(), sizeof(szT));
        int cch = (int)strlen(szT);
        if (szT[cch - 1] == '*') {
            szT[cch - 1] = 0;
            plbl->SetText(szT);
        }
        UpdateLabelRects(plbl);
    }

    // Put on new column
    idSortIndicator_ = id;
    LabelControl *plbl = (LabelControl *)GetControlPtr(idSortIndicator_);
    strncpyz(szT, plbl->GetText(), sizeof(szT));
    int cch = (int)strlen(szT);
    if (szT[cch - 1] != '*') {
        szT[cch] = '*';
        szT[cch + 1] = 0;
        plbl->SetText(szT);
        UpdateLabelRects(plbl);
    }

    // Force this before the sort occurs, for immediate visual feedback

    gpmfrmm->DrawFrame(false);

    // Perform default sort for this column
    HttpIndexLoader::SortType asortDefault[] = {
        HttpIndexLoader::SORT_INSTALLEDDESCENDING,
        HttpIndexLoader::SORT_TITLEASCENDING,
        HttpIndexLoader::SORT_PLAYERSASCENDING,
        HttpIndexLoader::SORT_MISSIONSDESCENDING
    };

    sort_ = asortDefault[iCol];
    idxl_.Sort(sort_);
    ShowIndex();
}
void DownloadMissionPackForm::PositionColumns() {
    // Calc tab stops in the list
    // S  Title # Players Downloads
    // S is + for installed, or ! for upgrade
    // Title is the title. Make this as wide as possible
    // # Players is as close to Downloads as is reasonable
    // # Missions is right aligned

    ListControl *plstc = (ListControl *)GetControlPtr(kidcMissionPackList);
    Font *pfnt = plstc->GetFont();
    LabelControl *plbl = (LabelControl *)GetControlPtr(kidcStatus);
#if 1
    plbl->SetText("");
    int cxPlus = pfnt->GetTextExtent("+");
#else
    int cxPlus = pfnt->GetTextExtent(plbl->GetText());
#endif
    plbl = (LabelControl *)GetControlPtr(kidcTitle);
    int cxTitle = pfnt->GetTextExtent(plbl->GetText());
    plbl = (LabelControl *)GetControlPtr(kidcNumPlayers);
    int cxNumPlayers = pfnt->GetTextExtent(plbl->GetText());
    int cxAsterisk = pfnt->GetTextExtent("*");
    plbl = (LabelControl *)GetControlPtr(kidcNumMissions);
    int cxNumMissions = pfnt->GetTextExtent(plbl->GetText());

    Rect rcList;
    plstc->GetRect(&rcList);

    int xStatus = 2;
    int xTitle = (rcList.Width() / 4 - cxTitle) / 2;
    int xNumMissions = rcList.Width() - cxAsterisk - cxNumMissions;
    int xNumPlayers = xNumMissions - 10 - cxNumPlayers; 
    // Calc the top of the list (past the arrow) for better column
    // label hittesting
    Size sizArrow;
    ListControl::s_ptbmScrollUpUp->GetSize(&sizArrow);
    int yListTop = rcList.top + sizArrow.cy;

    // Set the label positions
    // Enable the labels for hittesting

    Rect rc;
    plbl = (LabelControl *)GetControlPtr(kidcStatus);
    plbl->GetRect(&rc);
    rc.left = rcList.left + xStatus;
    rc.right = xTitle;
    rc.bottom += (yListTop - rc.bottom) / 2;
    plbl->SetRect(&rc);
    plbl->SetFlags(plbl->GetFlags() | kfLblHitTest);
    rcStatus_ = rc;

    plbl = (LabelControl *)GetControlPtr(kidcTitle);
    plbl->GetRect(&rc);
    rc.Offset(rcList.left + xTitle - rc.left, 0);
    rc.right += rc.Width();
    rc.bottom += (yListTop - rc.bottom) / 2;
    plbl->SetRect(&rc);
    plbl->SetFlags(plbl->GetFlags() | kfLblHitTest);
    rcTitle_ = rc;
    
    plbl = (LabelControl *)GetControlPtr(kidcNumPlayers);
    plbl->GetRect(&rc);
    rc.Offset(rcList.left + xNumPlayers - rc.left, 0);
    rc.bottom += (yListTop - rc.bottom) / 2;
    plbl->SetRect(&rc);
    plbl->SetFlags(plbl->GetFlags() | kfLblHitTest);
    rcNumPlayers_ = rc;

    plbl = (LabelControl *)GetControlPtr(kidcNumMissions);
    plbl->GetRect(&rc);
    rc.Offset(rcList.left + xNumMissions - rc.left, 0);
    rc.bottom += (yListTop - rc.bottom) / 2;
    plbl->SetRect(&rc);
    plbl->SetFlags(plbl->GetFlags() | kfLblHitTest);
    rcNumMissions_ = rc;

    // Remember the tab settings for later use

    x0_ = 0;
    x1_ = cxPlus + 4;
    x2_ = xNumPlayers + cxNumPlayers / 2;
    x3_ = xNumMissions + cxNumMissions / 2;
}
Beispiel #22
0
 void onValueChanged( Control* c, float value ) {
     _param = value;
     _label->setText( Stringify() << std::fixed << std::setprecision(1) << value );
     ScreenSpaceLayout::setOptions( g_dcOptions );
 }
    void
    addControls(ChromaKeyColorFilter* filter, Container* container, unsigned i)
    {
        // the outer container:
        Grid* s_layerBox = container->addControl(new Grid());
        s_layerBox->setBackColor(0,0,0,0.5);
        s_layerBox->setMargin( 10 );
        s_layerBox->setPadding( 10 );
        s_layerBox->setChildSpacing( 10 );
        s_layerBox->setChildVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setAbsorbEvents( true );
        s_layerBox->setVertAlign( Control::ALIGN_TOP );

        // Title:
        s_layerBox->setControl( 0, 0, new LabelControl(Stringify()<<"Layer "<<i, Color::Yellow) );
        
        // Red:
        LabelControl* rLabel = new LabelControl( "Red" );      
        rLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 1, rLabel );

        HSliderControl* rAdjust = new HSliderControl( 0.0f, 1.0f, 0.0f, new CHROMAKEY::SetColor(filter,0) );
        rAdjust->setWidth( 125 );
        rAdjust->setHeight( 12 );
        rAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 1, rAdjust );
        s_layerBox->setControl( 2, 1, new LabelControl(rAdjust) );

        // Green:
        LabelControl* gLabel = new LabelControl( "Green" );      
        gLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 2, gLabel );

        HSliderControl* gAdjust = new HSliderControl( 0.0f, 1.0f, 0.0f, new CHROMAKEY::SetColor(filter,1) );
        gAdjust->setWidth( 125 );
        gAdjust->setHeight( 12 );
        gAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 2, gAdjust );
        s_layerBox->setControl( 2, 2, new LabelControl(gAdjust) );

        // Blue
        LabelControl* bLabel = new LabelControl( "Blue" );      
        bLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 3, bLabel );

        HSliderControl* bAdjust = new HSliderControl( 0.0f, 1.0f, 0.0f, new CHROMAKEY::SetColor(filter,2) );
        bAdjust->setWidth( 125 );
        bAdjust->setHeight( 12 );
        bAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 3, bAdjust );
        s_layerBox->setControl( 2, 3, new LabelControl(bAdjust) );

        // Distance
        LabelControl* distLabel = new LabelControl( "Distance" );      
        distLabel->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 0, 4, distLabel );

        HSliderControl* distAdjust = new HSliderControl( 0.0f, 2.0f, 0.0f, new CHROMAKEY::SetDistance(filter) );
        distAdjust->setWidth( 125 );
        distAdjust->setHeight( 12 );
        distAdjust->setVertAlign( Control::ALIGN_CENTER );
        s_layerBox->setControl( 1, 4, distAdjust );
        s_layerBox->setControl( 2, 4, new LabelControl(distAdjust) );

        // Reset button
        LabelControl* resetButton = new LabelControl( "Reset" );
        resetButton->setBackColor( Color::Gray );
        resetButton->setActiveColor( Color::Blue );
        resetButton->addEventHandler( new Reset(rAdjust, gAdjust, bAdjust, distAdjust) );
        s_layerBox->setControl( 1, 5, resetButton );
    }
Beispiel #24
0
void
MapNodeHelper::parse(MapNode*             mapNode,
                     osg::ArgumentParser& args,
                     osgViewer::View*     view,
                     osg::Group*          root,
                     Control*             userControl ) const
{
    // this is a dubious move.
    if ( !root )
        root = mapNode;

    // options to use for the load
    osg::ref_ptr<osgDB::Options> dbOptions = Registry::instance()->cloneOrCreateOptions();

    // parse out custom example arguments first:

    bool useSky        = args.read("--sky");
    bool useOcean      = args.read("--ocean");
    bool useMGRS       = args.read("--mgrs");
    bool useDMS        = args.read("--dms");
    bool useDD         = args.read("--dd");
    bool useCoords     = args.read("--coords") || useMGRS || useDMS || useDD;
    bool useOrtho      = args.read("--ortho");
    bool useAutoClip   = args.read("--autoclip");

    float ambientBrightness = 0.4f;
    args.read("--ambientBrightness", ambientBrightness);

    std::string kmlFile;
    args.read( "--kml", kmlFile );

    // install a canvas for any UI controls we plan to create:
    ControlCanvas* canvas = ControlCanvas::get(view, false);

    Container* mainContainer = canvas->addControl( new VBox() );
    mainContainer->setBackColor( Color(Color::Black, 0.8) );
    mainContainer->setHorizAlign( Control::ALIGN_LEFT );
    mainContainer->setVertAlign( Control::ALIGN_BOTTOM );

    // install the user control:
    if ( userControl )
        mainContainer->addControl( userControl );

    // look for external data in the map node:
    const Config& externals = mapNode->externalConfig();

    const Config& skyConf         = externals.child("sky");
    const Config& oceanConf       = externals.child("ocean");
    const Config& annoConf        = externals.child("annotations");
    const Config& declutterConf   = externals.child("decluttering");
    Config        viewpointsConf  = externals.child("viewpoints");

    // backwards-compatibility: read viewpoints at the top level:
    const ConfigSet& old_viewpoints = externals.children("viewpoint");
    for( ConfigSet::const_iterator i = old_viewpoints.begin(); i != old_viewpoints.end(); ++i )
        viewpointsConf.add( *i );

    // Loading a viewpoint list from the earth file:
    if ( !viewpointsConf.empty() )
    {
        std::vector<Viewpoint> viewpoints;

        const ConfigSet& children = viewpointsConf.children();
        if ( children.size() > 0 )
        {
            for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i )
            {
                viewpoints.push_back( Viewpoint(*i) );
            }
        }

        if ( viewpoints.size() > 0 )
        {
            Control* c = ViewpointControlFactory().create(viewpoints, view);
            if ( c )
                mainContainer->addControl( c );
        }
    }

    // Adding a sky model:
    if ( useSky || !skyConf.empty() )
    {
        double hours = skyConf.value( "hours", 12.0 );
        SkyNode* sky = new SkyNode( mapNode->getMap() );
        sky->setAmbientBrightness( ambientBrightness );
        sky->setDateTime( 2011, 3, 6, hours );
        sky->attach( view );
        root->addChild( sky );
        Control* c = SkyControlFactory().create(sky, view);
        if ( c )
            mainContainer->addControl( c );
    }

    // Adding an ocean model:
    if ( useOcean || !oceanConf.empty() )
    {
        OceanSurfaceNode* ocean = new OceanSurfaceNode( mapNode, oceanConf );
        if ( ocean )
        {
            root->addChild( ocean );
            Control* c = OceanControlFactory().create(ocean, view);
            if ( c )
                mainContainer->addControl(c);
        }
    }

    // Loading KML from the command line:
    if ( !kmlFile.empty() )
    {
        KMLOptions kml_options;
        kml_options.declutter() = true;

        // set up a default icon for point placemarks:
        IconSymbol* defaultIcon = new IconSymbol();
        defaultIcon->url()->setLiteral(KML_PUSHPIN_URL);
        kml_options.defaultIconSymbol() = defaultIcon;

        osg::Node* kml = KML::load( URI(kmlFile), mapNode, kml_options );
        if ( kml )
        {
            Control* c = AnnotationGraphControlFactory().create(kml, view);
            if ( c )
            {
                c->setVertAlign( Control::ALIGN_TOP );
                canvas->addControl( c );
            }
            root->addChild( kml );
        }
    }

    // Annotations in the map node externals:
    if ( !annoConf.empty() )
    {
        osg::Group* annotations = 0L;
        AnnotationRegistry::instance()->create( mapNode, annoConf, dbOptions.get(), annotations );
        if ( annotations )
        {
            root->addChild( annotations );
        }
    }

    // Configure the de-cluttering engine for labels and annotations:
    if ( !declutterConf.empty() )
    {
        Decluttering::setOptions( DeclutteringOptions(declutterConf) );
    }

    // Configure the mouse coordinate readout:
    if ( useCoords )
    { 
        LabelControl* readout = new LabelControl();
        readout->setBackColor( Color(Color::Black, 0.8) );
        readout->setHorizAlign( Control::ALIGN_RIGHT );
        readout->setVertAlign( Control::ALIGN_BOTTOM );

        Formatter* formatter = 
            useMGRS ? (Formatter*)new MGRSFormatter(MGRSFormatter::PRECISION_1M, 0L, MGRSFormatter::USE_SPACES) :
            useDMS  ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DEGREES_MINUTES_SECONDS) :
            useDD   ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES) :
            0L;

        MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
        mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
        view->addEventHandler( mcTool );

        canvas->addControl( readout );
    }

    // Configure for an ortho camera:
    if ( useOrtho )
    {
        EarthManipulator* manip = dynamic_cast<EarthManipulator*>(view->getCameraManipulator());
        if ( manip )
        {
            manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC );
        }
    }

    // Install an auto clip plane clamper
    if ( useAutoClip )
    {
#if 0
        HorizonClipNode* hcn = new HorizonClipNode( mapNode );
        if ( mapNode->getNumParents() == 1 )
        {
            osg::Group* parent = mapNode->getParent(0);
            hcn->addChild( mapNode );
            parent->replaceChild( mapNode, hcn );
        }
#else
        mapNode->addCullCallback( new AutoClipPlaneCullCallback(mapNode) );
#endif
    }

    root->addChild( canvas );
}
Beispiel #25
0
void
MapNodeHelper::parse(MapNode*             mapNode,
                     osg::ArgumentParser& args,
                     osgViewer::View*     view,
                     osg::Group*          root,
                     Control*             userControl ) const
{
    // this is a dubious move.
    if ( !root )
        root = mapNode;

    // options to use for the load
    osg::ref_ptr<osgDB::Options> dbOptions = Registry::instance()->cloneOrCreateOptions();

    // parse out custom example arguments first:
    bool useSky        = args.read("--sky");
    bool useOcean      = args.read("--ocean");
    bool useMGRS       = args.read("--mgrs");
    bool useDMS        = args.read("--dms");
    bool useDD         = args.read("--dd");
    bool useCoords     = args.read("--coords") || useMGRS || useDMS || useDD;
    bool useOrtho      = args.read("--ortho");
    bool useAutoClip   = args.read("--autoclip");

    float ambientBrightness = 0.2f;
    args.read("--ambientBrightness", ambientBrightness);

    std::string kmlFile;
    args.read( "--kml", kmlFile );

    std::string imageFolder;
    args.read( "--images", imageFolder );

    std::string imageExtensions;
    args.read("--image-extensions", imageExtensions);

    // install a canvas for any UI controls we plan to create:
    ControlCanvas* canvas = ControlCanvas::get(view, false);

    Container* mainContainer = canvas->addControl( new VBox() );
    mainContainer->setAbsorbEvents( true );
    mainContainer->setBackColor( Color(Color::Black, 0.8) );
    mainContainer->setHorizAlign( Control::ALIGN_LEFT );
    mainContainer->setVertAlign( Control::ALIGN_BOTTOM );

    // install the user control:
    if ( userControl )
        mainContainer->addControl( userControl );

    // look for external data in the map node:
    const Config& externals = mapNode->externalConfig();

    const Config& skyConf         = externals.child("sky");
    const Config& oceanConf       = externals.child("ocean");
    const Config& annoConf        = externals.child("annotations");
    const Config& declutterConf   = externals.child("decluttering");
    Config        viewpointsConf  = externals.child("viewpoints");

    // some terrain effects.
    const Config& normalMapConf   = externals.child("normal_map");
    const Config& detailTexConf   = externals.child("detail_texture");
    const Config& lodBlendingConf = externals.child("lod_blending");
    const Config& vertScaleConf   = externals.child("vertical_scale");
    const Config& contourMapConf  = externals.child("contour_map");

    // backwards-compatibility: read viewpoints at the top level:
    const ConfigSet& old_viewpoints = externals.children("viewpoint");
    for( ConfigSet::const_iterator i = old_viewpoints.begin(); i != old_viewpoints.end(); ++i )
        viewpointsConf.add( *i );

    // Loading a viewpoint list from the earth file:
    if ( !viewpointsConf.empty() )
    {
        std::vector<Viewpoint> viewpoints;

        const ConfigSet& children = viewpointsConf.children();
        if ( children.size() > 0 )
        {
            for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i )
            {
                viewpoints.push_back( Viewpoint(*i) );
            }
        }

        if ( viewpoints.size() > 0 )
        {
            Control* c = ViewpointControlFactory().create(viewpoints, view);
            if ( c )
                mainContainer->addControl( c );
        }
    }

    // Adding a sky model:
    if ( useSky || !skyConf.empty() )
    {
        double hours = skyConf.value( "hours", 12.0 );
        SkyNode* sky = new SkyNode( mapNode->getMap() );
        sky->setAmbientBrightness( ambientBrightness );
        sky->setDateTime( DateTime(2011, 3, 6, hours) );
        sky->attach( view );
        root->addChild( sky );
        Control* c = SkyControlFactory().create(sky, view);
        if ( c )
            mainContainer->addControl( c );
    }

    // Adding an ocean model:
    if ( useOcean || !oceanConf.empty() )
    {
        OceanSurfaceNode* ocean = new OceanSurfaceNode( mapNode, oceanConf );
        if ( ocean )
        {
            root->addChild( ocean );
            Control* c = OceanControlFactory().create(ocean, view);
            if ( c )
                mainContainer->addControl(c);
        }
    }

    // Loading KML from the command line:
    if ( !kmlFile.empty() )
    {
        KMLOptions kml_options;
        kml_options.declutter() = true;

        // set up a default icon for point placemarks:
        IconSymbol* defaultIcon = new IconSymbol();
        defaultIcon->url()->setLiteral(KML_PUSHPIN_URL);
        kml_options.defaultIconSymbol() = defaultIcon;

        osg::Node* kml = KML::load( URI(kmlFile), mapNode, kml_options );
        if ( kml )
        {
            Control* c = AnnotationGraphControlFactory().create(kml, view);
            if ( c )
            {
                c->setVertAlign( Control::ALIGN_TOP );
                canvas->addControl( c );
            }
            root->addChild( kml );
        }
    }

    // Annotations in the map node externals:
    if ( !annoConf.empty() )
    {
        osg::Group* annotations = 0L;
        AnnotationRegistry::instance()->create( mapNode, annoConf, dbOptions.get(), annotations );
        if ( annotations )
        {
            root->addChild( annotations );
        }
    }

    // Configure the de-cluttering engine for labels and annotations:
    if ( !declutterConf.empty() )
    {
        Decluttering::setOptions( DeclutteringOptions(declutterConf) );
    }

    // Configure the mouse coordinate readout:
    if ( useCoords )
    { 
        LabelControl* readout = new LabelControl();
        readout->setBackColor( Color(Color::Black, 0.8) );
        readout->setHorizAlign( Control::ALIGN_RIGHT );
        readout->setVertAlign( Control::ALIGN_BOTTOM );

        Formatter* formatter = 
            useMGRS ? (Formatter*)new MGRSFormatter(MGRSFormatter::PRECISION_1M, 0L, MGRSFormatter::USE_SPACES) :
            useDMS  ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DEGREES_MINUTES_SECONDS) :
            useDD   ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES) :
            0L;

        MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
        mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
        view->addEventHandler( mcTool );

        canvas->addControl( readout );
    }

    // Configure for an ortho camera:
    if ( useOrtho )
    {
        EarthManipulator* manip = dynamic_cast<EarthManipulator*>(view->getCameraManipulator());
        if ( manip )
        {
            manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC );
        }
    }

    // Install an auto clip plane clamper
    if ( useAutoClip )
    {
        mapNode->addCullCallback( new AutoClipPlaneCullCallback(mapNode) );
    }

    // Scan for images if necessary.
    if ( !imageFolder.empty() )
    {
        std::vector<std::string> extensions;
        if ( !imageExtensions.empty() )
            StringTokenizer( imageExtensions, extensions, ",;", "", false, true );
        if ( extensions.empty() )
            extensions.push_back( "tif" );

        OE_INFO << LC << "Loading images from " << imageFolder << "..." << std::endl;
        ImageLayerVector imageLayers;
        DataScanner scanner;
        scanner.findImageLayers( imageFolder, extensions, imageLayers );

        if ( imageLayers.size() > 0 )
        {
            mapNode->getMap()->beginUpdate();
            for( ImageLayerVector::iterator i = imageLayers.begin(); i != imageLayers.end(); ++i )
            {
                mapNode->getMap()->addImageLayer( i->get() );
            }
            mapNode->getMap()->endUpdate();
        }
        OE_INFO << LC << "...found " << imageLayers.size() << " image layers." << std::endl;
    }

    // Install a normal map layer.
    if ( !normalMapConf.empty() )
    {
        osg::ref_ptr<NormalMap> effect = new NormalMap(normalMapConf, mapNode->getMap());
        if ( effect->getNormalMapLayer() )
        {
            mapNode->getTerrainEngine()->addEffect( effect.get() );
        }
    }

    // Install a detail texturer
    if ( !detailTexConf.empty() )
    {
        osg::ref_ptr<DetailTexture> effect = new DetailTexture(detailTexConf);
        if ( effect->getImage() )
        {
            mapNode->getTerrainEngine()->addEffect( effect.get() );
        }
    }

    // Install elevation morphing
    if ( !lodBlendingConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new LODBlending(lodBlendingConf) );
    }

    // Install vertical scaler
    if ( !vertScaleConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new VerticalScale(vertScaleConf) );
    }

    // Install a contour map effect.
    if ( !contourMapConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new ContourMap(contourMapConf) );
    }

    // Generic named value uniform with min/max.
    VBox* uniformBox = 0L;
    while( args.find( "--uniform" ) >= 0 )
    {
        std::string name;
        float minval, maxval;
        if ( args.read( "--uniform", name, minval, maxval ) )
        {
            if ( uniformBox == 0L )
            {
                uniformBox = new VBox();
                uniformBox->setBackColor(0,0,0,0.5);
                uniformBox->setAbsorbEvents( true );
                canvas->addControl( uniformBox );
            }
            osg::Uniform* uniform = new osg::Uniform(osg::Uniform::FLOAT, name);
            uniform->set( minval );
            root->getOrCreateStateSet()->addUniform( uniform, osg::StateAttribute::OVERRIDE );
            HBox* box = new HBox();
            box->addControl( new LabelControl(name) );
            HSliderControl* hs = box->addControl( new HSliderControl(minval, maxval, minval, new ApplyValueUniform(uniform)));
            hs->setHorizFill(true, 200);
            box->addControl( new LabelControl(hs) );
            uniformBox->addControl( box );
            OE_INFO << LC << "Installed uniform controller for " << name << std::endl;
        }
    }

    root->addChild( canvas );
}
Beispiel #26
0
int
main(int argc, char** argv)
{
    osg::Group* root = new osg::Group();

    // try to load an earth file.
    osg::ArgumentParser arguments(&argc,argv);

    osgViewer::Viewer viewer(arguments);
    viewer.setCameraManipulator( new EarthManipulator() );

    // load an earth file and parse demo arguments
    osg::Node* node = MapNodeHelper().load(arguments, &viewer);
    if ( !node )
        return usage(argv);

    root->addChild( node );

    // find the map node that we loaded.
    MapNode* mapNode = MapNode::findMapNode(node);
    if ( !mapNode )
        return usage(argv);

    // Group to hold all our annotation elements.
    osg::Group* annoGroup = new osg::Group();
    root->addChild( annoGroup );

    //A group for all the editors
    osg::Group* editorGroup = new osg::Group;
    root->addChild( editorGroup );
    editorGroup->setNodeMask( 0 );

    HBox* box = ControlCanvas::getOrCreate(&viewer)->addControl( new HBox() );
    box->setChildSpacing( 5 );
    //Add a toggle button to toggle editing
    CheckBoxControl* editCheckbox = new CheckBoxControl( false );
    editCheckbox->addEventHandler( new ToggleNodeHandler( editorGroup ) );
    box->addControl( editCheckbox );
    LabelControl* labelControl = new LabelControl( "Edit Annotations" );
    labelControl->setFontSize( 24.0f );
    box->addControl( labelControl  );


    // Make a group for 2D items, and activate the decluttering engine. Decluttering
    // will migitate overlap between elements that occupy the same screen real estate.
    osg::Group* labelGroup = new osg::Group();
    Decluttering::setEnabled( labelGroup->getOrCreateStateSet(), true );
    annoGroup->addChild( labelGroup );

    // Style our labels:
    Style labelStyle;
    labelStyle.getOrCreate<TextSymbol>()->alignment() = TextSymbol::ALIGN_CENTER_CENTER;
    labelStyle.getOrCreate<TextSymbol>()->fill()->color() = Color::Yellow;

    // A lat/long SRS for specifying points.
    const SpatialReference* geoSRS = mapNode->getMapSRS()->getGeographicSRS();

    //--------------------------------------------------------------------

    // A series of place nodes (an icon with a text label)
    {
        Style pin;
        pin.getOrCreate<IconSymbol>()->url()->setLiteral( "../data/placemark32.png" );

        // bunch of pins:
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, -74.00, 40.71), "New York"      , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, -77.04, 38.85), "Washington, DC", pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS,-118.40, 33.93), "Los Angeles"   , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, -71.03, 42.37), "Boston"        , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS,-157.93, 21.35), "Honolulu"      , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, 139.75, 35.68), "Tokyo"         , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, -90.25, 29.98), "New Orleans"   , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, -80.28, 25.82), "Miami"         , pin));
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS,-117.17, 32.72), "San Diego"     , pin));

        // test with an LOD:
        osg::LOD* lod = new osg::LOD();
        lod->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, 14.68, 50.0), "Prague", pin), 0.0, 1e6);
        labelGroup->addChild( lod );

        // absolute altitude:
        labelGroup->addChild( new PlaceNode(mapNode, GeoPoint(geoSRS, -87.65, 41.90, 1000, ALTMODE_ABSOLUTE), "Chicago"       , pin));
    }

    //--------------------------------------------------------------------

    // a box that follows lines of latitude (rhumb line interpolation, the default)
    {
        Geometry* geom = new Polygon();
        geom->push_back( osg::Vec3d(0,   40, 0) );
        geom->push_back( osg::Vec3d(-60, 40, 0) );
        geom->push_back( osg::Vec3d(-60, 60, 0) );
        geom->push_back( osg::Vec3d(0,   60, 0) );
        Style geomStyle;
        geomStyle.getOrCreate<LineSymbol>()->stroke()->color() = Color::Cyan;
        geomStyle.getOrCreate<LineSymbol>()->stroke()->width() = 5.0f;
        geomStyle.getOrCreate<AltitudeSymbol>()->clamping() = AltitudeSymbol::CLAMP_TO_TERRAIN;
        geomStyle.getOrCreate<AltitudeSymbol>()->technique() = AltitudeSymbol::TECHNIQUE_GPU;
        FeatureNode* gnode = new FeatureNode(mapNode, new Feature(geom, geoSRS, geomStyle));
        annoGroup->addChild( gnode );

        labelGroup->addChild( new LabelNode(mapNode, GeoPoint(geoSRS,-30, 50), "Rhumb line polygon", labelStyle) );
    }

    //--------------------------------------------------------------------

    // another rhumb box that crosses the antimeridian
    {
        Geometry* geom = new Polygon();
        geom->push_back( -160., -30. );
        geom->push_back(  150., -20. );
        geom->push_back(  160., -45. );
        geom->push_back( -150., -40. );
        Style geomStyle;
        geomStyle.getOrCreate<LineSymbol>()->stroke()->color() = Color::Lime;
        geomStyle.getOrCreate<LineSymbol>()->stroke()->width() = 3.0f;
        geomStyle.getOrCreate<AltitudeSymbol>()->clamping() = AltitudeSymbol::CLAMP_TO_TERRAIN;
        geomStyle.getOrCreate<AltitudeSymbol>()->technique() = AltitudeSymbol::TECHNIQUE_GPU;
        FeatureNode* gnode = new FeatureNode(mapNode, new Feature(geom, geoSRS, geomStyle));
        annoGroup->addChild( gnode );

        labelGroup->addChild( new LabelNode(mapNode, GeoPoint(geoSRS, -175, -35), "Antimeridian polygon", labelStyle) );
    }

    //--------------------------------------------------------------------

    // A path using great-circle interpolation.
    {
        Geometry* path = new LineString();
        path->push_back( osg::Vec3d(-74, 40.714, 0) );   // New York
        path->push_back( osg::Vec3d(139.75, 35.68, 0) ); // Tokyo

        Style pathStyle;
        pathStyle.getOrCreate<LineSymbol>()->stroke()->color() = Color::Red;
        pathStyle.getOrCreate<LineSymbol>()->stroke()->width() = 3.0f;
        pathStyle.getOrCreate<AltitudeSymbol>()->clamping() = AltitudeSymbol::CLAMP_TO_TERRAIN;
        pathStyle.getOrCreate<AltitudeSymbol>()->technique() = AltitudeSymbol::TECHNIQUE_GPU;

        Feature* pathFeature = new Feature(path, geoSRS, pathStyle);
        pathFeature->geoInterp() = GEOINTERP_GREAT_CIRCLE;

        //OE_INFO << "Path extent = " << pathFeature->getExtent().toString() << std::endl;

        FeatureNode* pathNode = new FeatureNode(mapNode, pathFeature);
        annoGroup->addChild( pathNode );

        labelGroup->addChild( new LabelNode(mapNode, GeoPoint(geoSRS,-170, 61.2), "Great circle path", labelStyle) );
    }

    //--------------------------------------------------------------------

    // Two circle segments around New Orleans.
    {
        Style circleStyle;
        circleStyle.getOrCreate<PolygonSymbol>()->fill()->color() = Color(Color::Cyan, 0.5);
        circleStyle.getOrCreate<AltitudeSymbol>()->clamping() = AltitudeSymbol::CLAMP_TO_TERRAIN;
        circleStyle.getOrCreate<AltitudeSymbol>()->technique() = AltitudeSymbol::TECHNIQUE_DRAPE;

        CircleNode* circle = new CircleNode(
            mapNode,
            GeoPoint(geoSRS, -90.25, 29.98, 1000., ALTMODE_RELATIVE),
            Distance(300, Units::KILOMETERS),
            circleStyle, Angle(-45.0, Units::DEGREES), Angle(45.0, Units::DEGREES), true);
        annoGroup->addChild( circle );

        editorGroup->addChild( new CircleNodeEditor( circle ) );
    }

	{
		Style circleStyle;
		circleStyle.getOrCreate<PolygonSymbol>()->fill()->color() = Color(Color::Red, 0.5);
		circleStyle.getOrCreate<AltitudeSymbol>()->clamping() = AltitudeSymbol::CLAMP_TO_TERRAIN;
		circleStyle.getOrCreate<AltitudeSymbol>()->technique() = AltitudeSymbol::TECHNIQUE_DRAPE;

		CircleNode* circle = new CircleNode(
			mapNode,
			GeoPoint(geoSRS, -90.25, 29.98, 1000., ALTMODE_RELATIVE),
			Distance(300, Units::KILOMETERS),
			circleStyle, Angle(45.0, Units::DEGREES), Angle(360.0 - 45.0, Units::DEGREES), true);
		annoGroup->addChild( circle );

		editorGroup->addChild( new CircleNodeEditor( circle ) );
	}

    //--------------------------------------------------------------------

    // An extruded ellipse around Miami.
    {
        Style ellipseStyle;
        ellipseStyle.getOrCreate<PolygonSymbol>()->fill()->color() = Color(Color::Orange, 0.75);
        ellipseStyle.getOrCreate<ExtrusionSymbol>()->height() = 250000.0; // meters MSL
        EllipseNode* ellipse = new EllipseNode(
            mapNode, 
            GeoPoint(geoSRS, -80.28, 25.82, 0.0, ALTMODE_RELATIVE),
            Distance(250, Units::MILES),
            Distance(100, Units::MILES),
            Angle   (0, Units::DEGREES),
            ellipseStyle,
            Angle(45.0, Units::DEGREES),
            Angle(360.0 - 45.0, Units::DEGREES), 
            true);
        annoGroup->addChild( ellipse );
        editorGroup->addChild( new EllipseNodeEditor( ellipse ) );
    }
	{
		Style ellipseStyle;
		ellipseStyle.getOrCreate<PolygonSymbol>()->fill()->color() = Color(Color::Blue, 0.75);
		ellipseStyle.getOrCreate<ExtrusionSymbol>()->height() = 250000.0; // meters MSL
		EllipseNode* ellipse = new EllipseNode(
			mapNode, 
			GeoPoint(geoSRS, -80.28, 25.82, 0.0, ALTMODE_RELATIVE),
			Distance(250, Units::MILES),
			Distance(100, Units::MILES),
			Angle   (0, Units::DEGREES),
			ellipseStyle, 
            Angle(-40.0, Units::DEGREES), 
            Angle(40.0, Units::DEGREES), 
            true);
		annoGroup->addChild( ellipse );
		editorGroup->addChild( new EllipseNodeEditor( ellipse ) );
	}
    
    //--------------------------------------------------------------------

    {
        // A rectangle around San Diego
        Style rectStyle;
        rectStyle.getOrCreate<PolygonSymbol>()->fill()->color() = Color(Color::Green, 0.5);
        rectStyle.getOrCreate<AltitudeSymbol>()->clamping() = AltitudeSymbol::CLAMP_TO_TERRAIN;
        rectStyle.getOrCreate<AltitudeSymbol>()->technique() = AltitudeSymbol::TECHNIQUE_DRAPE;
        RectangleNode* rect = new RectangleNode(
            mapNode, 
            GeoPoint(geoSRS, -117.172, 32.721),
            Distance(300, Units::KILOMETERS ),
            Distance(600, Units::KILOMETERS ),
            rectStyle);
        annoGroup->addChild( rect );

        editorGroup->addChild( new RectangleNodeEditor( rect ) );
    }    

    //--------------------------------------------------------------------

    // An extruded polygon roughly the shape of Utah. Here we demonstrate the
    // FeatureNode, where you create a geographic geometry and use it as an
    // annotation.
    {
        Geometry* utah = new Polygon();
        utah->push_back( -114.052, 37.0   );
        utah->push_back( -109.054, 37.0   );
        utah->push_back( -109.054, 41.0   );
        utah->push_back( -111.040, 41.0   );
        utah->push_back( -111.080, 42.059 );
        utah->push_back( -114.080, 42.024 );

        Style utahStyle;
        utahStyle.getOrCreate<ExtrusionSymbol>()->height() = 250000.0; // meters MSL
        utahStyle.getOrCreate<PolygonSymbol>()->fill()->color() = Color(Color::White, 0.8);

        Feature*     utahFeature = new Feature(utah, geoSRS, utahStyle);
        FeatureNode* featureNode = new FeatureNode(mapNode, utahFeature);
        annoGroup->addChild( featureNode );
    }

    //--------------------------------------------------------------------

    // an image overlay.
    {
        ImageOverlay* imageOverlay = 0L;
        osg::Image* image = osgDB::readImageFile( "../data/USFLAG.TGA" );
        if ( image )
        {
            imageOverlay = new ImageOverlay(mapNode, image);
            imageOverlay->setBounds( Bounds( -100.0, 35.0, -90.0, 40.0) );
            annoGroup->addChild( imageOverlay );

            editorGroup->addChild( new ImageOverlayEditor( imageOverlay ) );
        }
    }
    
    //--------------------------------------------------------------------

    // install decoration. These change the appearance of an Annotation
    // based on some user action.

    // highlight annotation upon hover by default:
    
    DecorationInstaller highlightInstaller("hover", new HighlightDecoration());
    annoGroup->accept( highlightInstaller );

    // scale labels when hovering:
    DecorationInstaller scaleInstaller("hover", new ScaleDecoration(1.1f));
    labelGroup->accept( scaleInstaller );

    // install an event handler for picking and hovering.
    AnnotationEventCallback* cb = new AnnotationEventCallback();
    cb->addHandler( new MyAnnoEventHandler() );

    annoGroup->addEventCallback( cb );

    //--------------------------------------------------------------------

    // initialize the viewer:    
    viewer.setSceneData( root );

    viewer.getCamera()->addCullCallback( new AutoClipPlaneCullCallback(mapNode) );
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

    return viewer.run();
}
void
MapNodeHelper::parse(MapNode*             mapNode,
                     osg::ArgumentParser& args,
                     osgViewer::View*     view,
                     osg::Group*          root,
                     Control*             userControl ) const
{
    if ( !root )
        root = mapNode;

    // options to use for the load
    osg::ref_ptr<osgDB::Options> dbOptions = Registry::instance()->cloneOrCreateOptions();

    // parse out custom example arguments first:
    bool useSky        = args.read("--sky");
    bool useOcean      = args.read("--ocean");
    bool useMGRS       = args.read("--mgrs");
    bool useDMS        = args.read("--dms");
    bool useDD         = args.read("--dd");
    bool useCoords     = args.read("--coords") || useMGRS || useDMS || useDD;
    bool useOrtho      = args.read("--ortho");
    bool useAutoClip   = args.read("--autoclip");
    bool useShadows    = args.read("--shadows");
    bool animateSky    = args.read("--animate-sky");
    bool showActivity  = args.read("--activity");
    bool useLogDepth   = args.read("--logdepth");
    bool useLogDepth2  = args.read("--logdepth2");
    bool kmlUI         = args.read("--kmlui");

    if (args.read("--verbose"))
        osgEarth::setNotifyLevel(osg::INFO);
    
    if (args.read("--quiet"))
        osgEarth::setNotifyLevel(osg::FATAL);

    float ambientBrightness = 0.2f;
    args.read("--ambientBrightness", ambientBrightness);

    std::string kmlFile;
    args.read( "--kml", kmlFile );

    std::string imageFolder;
    args.read( "--images", imageFolder );

    std::string imageExtensions;
    args.read("--image-extensions", imageExtensions);
    
    // animation path:
    std::string animpath;
    if ( args.read("--path", animpath) )
    {
        view->setCameraManipulator( new osgGA::AnimationPathManipulator(animpath) );
    }

    // Install a new Canvas for our UI controls, or use one that already exists.
    ControlCanvas* canvas = ControlCanvas::getOrCreate( view );

    Container* mainContainer = canvas->addControl( new VBox() );
    mainContainer->setAbsorbEvents( true );
    mainContainer->setBackColor( Color(Color::Black, 0.8) );
    mainContainer->setHorizAlign( Control::ALIGN_LEFT );
    mainContainer->setVertAlign( Control::ALIGN_BOTTOM );

    // install the user control:
    if ( userControl )
        mainContainer->addControl( userControl );

    // look for external data in the map node:
    const Config& externals = mapNode->externalConfig();

    const Config& skyConf         = externals.child("sky");
    const Config& oceanConf       = externals.child("ocean");
    const Config& annoConf        = externals.child("annotations");
    const Config& declutterConf   = externals.child("decluttering");

    // some terrain effects.
    // TODO: Most of these are likely to move into extensions.
    const Config& lodBlendingConf = externals.child("lod_blending");
    const Config& vertScaleConf   = externals.child("vertical_scale");
    const Config& contourMapConf  = externals.child("contour_map");

    // Adding a sky model:
    if ( useSky || !skyConf.empty() )
    {
        SkyOptions options(skyConf);
        if ( options.getDriver().empty() )
        {
            if ( mapNode->getMapSRS()->isGeographic() )
                options.setDriver("simple");
            else
                options.setDriver("gl");
        }

        SkyNode* sky = SkyNode::create(options, mapNode);
        if ( sky )
        {
            sky->attach( view, 0 );
            if ( mapNode->getNumParents() > 0 )
            {
                osgEarth::insertGroup(sky, mapNode->getParent(0));
            }
            else
            {
                sky->addChild( mapNode );
                root = sky;
            }
                
            Control* c = SkyControlFactory().create(sky, view);
            if ( c )
                mainContainer->addControl( c );

            if (animateSky)
            {
                sky->setUpdateCallback( new AnimateSkyUpdateCallback() );
            }

        }
    }

    // Adding an ocean model:
    if ( useOcean || !oceanConf.empty() )
    {
        OceanNode* ocean = OceanNode::create(OceanOptions(oceanConf), mapNode);
        if ( ocean )
        {
            // if there's a sky, we want to ocean under it
            osg::Group* parent = osgEarth::findTopMostNodeOfType<SkyNode>(root);
            if ( !parent ) parent = root;
            parent->addChild( ocean );

            Control* c = OceanControlFactory().create(ocean);
            if ( c )
                mainContainer->addControl(c);
        }
    }

    // Shadowing.
    if ( useShadows )
    {
        ShadowCaster* caster = new ShadowCaster();
        caster->setLight( view->getLight() );
        caster->getShadowCastingGroup()->addChild( mapNode->getModelLayerGroup() );
        if ( mapNode->getNumParents() > 0 )
        {
            insertGroup(caster, mapNode->getParent(0));
        }
        else
        {
            caster->addChild(mapNode);
            root = caster;
        }
    }

    // Loading KML from the command line:
    if ( !kmlFile.empty() )
    {
        KMLOptions kml_options;
        kml_options.declutter() = true;

        // set up a default icon for point placemarks:
        IconSymbol* defaultIcon = new IconSymbol();
        defaultIcon->url()->setLiteral(KML_PUSHPIN_URL);
        kml_options.defaultIconSymbol() = defaultIcon;

        osg::Node* kml = KML::load( URI(kmlFile), mapNode, kml_options );
        if ( kml )
        {
            if (kmlUI)
            {
                Control* c = AnnotationGraphControlFactory().create(kml, view);
                if ( c )
                {
                    c->setVertAlign( Control::ALIGN_TOP );
                    canvas->addControl( c );
                }
            }
            root->addChild( kml );
        }
        else
        {
            OE_NOTICE << "Failed to load " << kmlFile << std::endl;
        }
    }

    // Annotations in the map node externals:
    if ( !annoConf.empty() )
    {
        osg::Group* annotations = 0L;
        AnnotationRegistry::instance()->create( mapNode, annoConf, dbOptions.get(), annotations );
        if ( annotations )
        {
            root->addChild( annotations );
        }
    }

    // Configure the de-cluttering engine for labels and annotations:
    if ( !declutterConf.empty() )
    {
        Decluttering::setOptions( DeclutteringOptions(declutterConf) );
    }

    // Configure the mouse coordinate readout:
    if ( useCoords )
    { 
        LabelControl* readout = new LabelControl();
        readout->setBackColor( Color(Color::Black, 0.8) );
        readout->setHorizAlign( Control::ALIGN_RIGHT );
        readout->setVertAlign( Control::ALIGN_BOTTOM );

        Formatter* formatter = 
            useMGRS ? (Formatter*)new MGRSFormatter(MGRSFormatter::PRECISION_1M, 0L, MGRSFormatter::USE_SPACES) :
            useDMS  ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DEGREES_MINUTES_SECONDS) :
            useDD   ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES) :
            0L;

        MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
        mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
        view->addEventHandler( mcTool );

        canvas->addControl( readout );
    }

    // Configure for an ortho camera:
    if ( useOrtho )
    {
        EarthManipulator* manip = dynamic_cast<EarthManipulator*>(view->getCameraManipulator());
        if ( manip )
        {
            manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC );
        }
    }

    // activity monitor (debugging)
    if ( showActivity )
    {
        VBox* vbox = new VBox();
        vbox->setBackColor( Color(Color::Black, 0.8) );
        vbox->setHorizAlign( Control::ALIGN_RIGHT );
        vbox->setVertAlign( Control::ALIGN_BOTTOM );
        view->addEventHandler( new ActivityMonitorTool(vbox) );
        canvas->addControl( vbox );
    }

    // Install an auto clip plane clamper
    if ( useAutoClip )
    {
        mapNode->addCullCallback( new AutoClipPlaneCullCallback(mapNode) );
    }

    // Install logarithmic depth buffer on main camera
    if ( useLogDepth )
    {
        OE_INFO << LC << "Activating logarithmic depth buffer on main camera" << std::endl;
        osgEarth::Util::LogarithmicDepthBuffer logDepth;
        logDepth.setUseFragDepth( true );
        logDepth.install( view->getCamera() );
    }

    else if ( useLogDepth2 )
    {
        OE_INFO << LC << "Activating logarithmic depth buffer (vertex-only) on main camera" << std::endl;
        osgEarth::Util::LogarithmicDepthBuffer logDepth;
        logDepth.setUseFragDepth( false );
        logDepth.install( view->getCamera() );
    }

    // Scan for images if necessary.
    if ( !imageFolder.empty() )
    {
        std::vector<std::string> extensions;
        if ( !imageExtensions.empty() )
            StringTokenizer( imageExtensions, extensions, ",;", "", false, true );
        if ( extensions.empty() )
            extensions.push_back( "tif" );

        OE_INFO << LC << "Loading images from " << imageFolder << "..." << std::endl;
        ImageLayerVector imageLayers;
        DataScanner scanner;
        scanner.findImageLayers( imageFolder, extensions, imageLayers );

        if ( imageLayers.size() > 0 )
        {
            mapNode->getMap()->beginUpdate();
            for( ImageLayerVector::iterator i = imageLayers.begin(); i != imageLayers.end(); ++i )
            {
                mapNode->getMap()->addImageLayer( i->get() );
            }
            mapNode->getMap()->endUpdate();
        }
        OE_INFO << LC << "...found " << imageLayers.size() << " image layers." << std::endl;
    }

    // Install elevation morphing
    if ( !lodBlendingConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new LODBlending(lodBlendingConf) );
    }

    // Install vertical scaler
    if ( !vertScaleConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new VerticalScale(vertScaleConf) );
    }

    // Install a contour map effect.
    if ( !contourMapConf.empty() )
    {
        mapNode->getTerrainEngine()->addEffect( new ContourMap(contourMapConf) );
    }

    // Generic named value uniform with min/max.
    VBox* uniformBox = 0L;
    while( args.find( "--uniform" ) >= 0 )
    {
        std::string name;
        float minval, maxval;
        if ( args.read( "--uniform", name, minval, maxval ) )
        {
            if ( uniformBox == 0L )
            {
                uniformBox = new VBox();
                uniformBox->setBackColor(0,0,0,0.5);
                uniformBox->setAbsorbEvents( true );
                canvas->addControl( uniformBox );
            }
            osg::Uniform* uniform = new osg::Uniform(osg::Uniform::FLOAT, name);
            uniform->set( minval );
            root->getOrCreateStateSet()->addUniform( uniform, osg::StateAttribute::OVERRIDE );
            HBox* box = new HBox();
            box->addControl( new LabelControl(name) );
            HSliderControl* hs = box->addControl( new HSliderControl(minval, maxval, minval, new ApplyValueUniform(uniform)));
            hs->setHorizFill(true, 200);
            box->addControl( new LabelControl(hs) );
            uniformBox->addControl( box );
            OE_INFO << LC << "Installed uniform controller for " << name << std::endl;
        }
    }
    

    // Process extensions.
    for(std::vector<osg::ref_ptr<Extension> >::const_iterator eiter = mapNode->getExtensions().begin();
        eiter != mapNode->getExtensions().end();
        ++eiter)
    {
        Extension* e = eiter->get();

        // Check for a View interface:
        ExtensionInterface<osg::View>* viewIF = ExtensionInterface<osg::View>::get( e );
        if ( viewIF )
            viewIF->connect( view );

        // Check for a Control interface:
        ExtensionInterface<Control>* controlIF = ExtensionInterface<Control>::get( e );
        if ( controlIF )
            controlIF->connect( mainContainer );
    }

    root->addChild( canvas );
}
Beispiel #28
0
TechTreeWindow *TechTreeWindow::Constructor(Window *underlyingWindow, int unknownGameAndPlayerData, int selectedCivId)
{
	// Needed for window management and proper cleanup in other places
	base::Constructor("One Button Tech Tree Screen");

	// Save underlying window
	_underlyingWindow = underlyingWindow;

	// Save game data
	_unknownGameAndPlayerData = unknownGameAndPlayerData;

	// Set virtual function table address
	_VTable = reinterpret_cast<ControlVTable *>(0x00645118);

	// Cast virtual function table to be able to access all functions
	PanelVTable *vTable = static_cast<PanelVTable *>(_VTable);

	// Get design data
	_designData = _staticNewTechTreeDataObject->GetDesignData();

	// Load style file
	DirectDrawBufferData *backBuffer = underlyingWindow->_VTable->GetBackBufferData(underlyingWindow);
	if(!PrepareParentWindowAndLoadStyleData(backBuffer, "scr6", 50007, 1))
		_initializationError = 1;

	// Start with top left corner
	_horizontalScrollOffset = 0;
	_verticalScrollOffset = 0;
	_lastScrollActionTime = 0;

	// Create vanilla style tech tree renderer
	// TODO: May be changed to allow various renderers using completely different layout approaches
	_renderer = new VanillaTechTreeRenderer((*_staticGameObjectPointer)->GetGameDataHandler(), Size(_width1, _height1), unknownGameAndPlayerData);

	// Get the renderer's age count
	_ageCount = _renderer->GetAgeCount();

	// Create close button and its buffer
	static_cast<PanelVTable *>(_VTable)->CreateButtonWithOneFontWithTextFromDll(this, this, &_closeButton, 20101, 0, _width1 - _designData->_closeButtonRelativeRectangle.X, _height1 - _designData->_closeButtonRelativeRectangle.Y, _designData->_closeButtonRelativeRectangle.Width, _designData->_closeButtonRelativeRectangle.Height, 9, 0, 0);
	_closeButton->_VTable->InvalidateAndRedrawControl1(_closeButton, 1);
	_closeButton->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_closeButton->SetHotKey(VK_ESCAPE, 0, 0, 0);
	_closeButtonDrawBuffer = new DirectDrawBufferData("TechTree Close Button Buffer", 1);
	_closeButtonDrawBuffer->InsertIntoBufferListAndCreateSurfaceAndDoUnknownStuff(_backBufferData->GetDirectDrawHandler(), _designData->_closeButtonRelativeRectangle.Width, _designData->_closeButtonRelativeRectangle.Height, 0, 0);
	_closeButtonDrawBuffer->sub_5A30A0(0, 0, _designData->_closeButtonRelativeRectangle.Width, _designData->_closeButtonRelativeRectangle.Height);
	UpdateSelectedSubControl(_closeButton);

	// Create scroll buttons and their buffers
	static_cast<PanelVTable *>(_VTable)->CreateButton(this, this, &_scrollLeftButton, "<-", 0, _width1 - _designData->_scrollLeftButtonRelativeRectangle.X, _height1 - _designData->_scrollLeftButtonRelativeRectangle.Y, _designData->_scrollLeftButtonRelativeRectangle.Width, _designData->_scrollLeftButtonRelativeRectangle.Height, 9, 0, 0);
	_scrollLeftButton->_VTable->InvalidateAndRedrawControl1(_scrollLeftButton, 1);
	_scrollLeftButton->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_scrollLeftButtonDrawBuffer = new DirectDrawBufferData("TechTree ScrollLeft Button Buffer", 1);
	_scrollLeftButtonDrawBuffer->InsertIntoBufferListAndCreateSurfaceAndDoUnknownStuff(_backBufferData->GetDirectDrawHandler(), _designData->_scrollLeftButtonRelativeRectangle.Width, _designData->_scrollLeftButtonRelativeRectangle.Height, 0, 0);
	_scrollLeftButtonDrawBuffer->sub_5A30A0(0, 0, _designData->_scrollLeftButtonRelativeRectangle.Width, _designData->_scrollLeftButtonRelativeRectangle.Height);
	static_cast<PanelVTable *>(_VTable)->CreateButton(this, this, &_scrollRightButton, "->", 0, _width1 - _designData->_scrollRightButtonRelativeRectangle.X, _height1 - _designData->_scrollRightButtonRelativeRectangle.Y, _designData->_scrollRightButtonRelativeRectangle.Width, _designData->_scrollRightButtonRelativeRectangle.Height, 9, 0, 0);
	_scrollRightButton->_VTable->InvalidateAndRedrawControl1(_scrollRightButton, 1);
	_scrollRightButton->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_scrollRightButtonDrawBuffer = new DirectDrawBufferData("TechTree ScrollRight Button Buffer", 1);
	_scrollRightButtonDrawBuffer->InsertIntoBufferListAndCreateSurfaceAndDoUnknownStuff(_backBufferData->GetDirectDrawHandler(), _designData->_scrollRightButtonRelativeRectangle.Width, _designData->_scrollRightButtonRelativeRectangle.Height, 0, 0);
	_scrollRightButtonDrawBuffer->sub_5A30A0(0, 0, _designData->_scrollRightButtonRelativeRectangle.Width, _designData->_scrollRightButtonRelativeRectangle.Height);

	// Load arrow SLP for scroll buttons and assign frames to them
	_arrowSlp = new SlpFileElement(_designData->_scrollSlpFileName, _designData->_scrollSlpId);
	_scrollLeftButton->SetBackgroundSlpAtIndex(0, _arrowSlp, 1);
	_scrollLeftButton->SetDisplayMode(9);
	_scrollLeftButton->AssignLabelString(0, "");
	_scrollRightButton->SetBackgroundSlpAtIndex(0, _arrowSlp, 0);
	_scrollRightButton->SetDisplayMode(9);
	_scrollRightButton->AssignLabelString(0, "");

	// Create civ bonus label
	/*static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, &_civBonusLabel, 0, 2, 20, 100, 20, 10, 0, 0, 1);
	_civBonusLabel->_VTable->InvalidateAndRedrawControl1(_civBonusLabel, 0);
	_civBonusLabel->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_civBonusLabel->SetStyleText2Colors(0, 0);
	_civBonusLabel->sub_545D70(0);*/
	FontData *civBonusLabelBaseFont = (*_staticGameObjectPointer)->GetFontWithIndex(10);
	HFONT civBonusLabelFonts[4];
	civBonusLabelFonts[0] = civBonusLabelBaseFont->GetFontHandle();
	civBonusLabelFonts[1] = (*_staticGameObjectPointer)->GetFontWithIndex(17)->GetFontHandle();
	civBonusLabelFonts[2] = (*_staticGameObjectPointer)->GetFontWithIndex(18)->GetFontHandle();
	civBonusLabelFonts[3] = (*_staticGameObjectPointer)->GetFontWithIndex(19)->GetFontHandle();
	_civBonusLabel = new LabelControl();
	_civBonusLabel->sub_5444B0(_backBufferData, this, 2, 20, 100, 20, civBonusLabelFonts, civBonusLabelBaseFont->GetAverageCharWidth(), civBonusLabelBaseFont->GetCharHeightWithRowSpace(), nullptr, 0, 0, 0, 0, 0, nullptr);
	_civBonusLabel->SetTextAlignment(3, 1);
	_civBonusLabel->sub_545D50(1);
	_civBonusLabel->sub_545D70(0);
	_civBonusLabel->SetStyleText2Colors(0x000000, 0x00E7E7);

	// Create civ selection combo box
	static_cast<PanelVTable *>(_VTable)->CreateComboBox(this, this, &_civSelectionComboBox, 230, 0, 2, 20, 200, 25, 10);
	_civSelectionComboBox->_VTable->InvalidateAndRedrawControl1(_civSelectionComboBox, 1);
	_civSelectionComboBox->SetDropDownListSortingMode(1);
	_civSelectionComboBox->AssignIdToControlAndMoveInParentChildrenList(1, 1);
	_civSelectionComboBox->SetStyleText2Colors(0, 0);
	_civSelectionComboBox->GetDropDownScrollBar()->SetFillBackground(-1);
	_civSelectionComboBox->GetValueLabel()->SetBackgroundSlp("tech_tile.slp", 50343);
	_civSelectionComboBox->GetDropDownList()->SetBackgroundSlp("tech_tile.slp", 50343);

	// Create "game civs" label
	static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, &_gameCivsLabel, 0, 2, 20, 200, 25, 10, 0, 0, 1);
	_gameCivsLabel->_VTable->InvalidateAndRedrawControl1(_gameCivsLabel, 0);
	_gameCivsLabel->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_gameCivsLabel->SetStyleText2Colors(0, 0);
	_gameCivsLabel->sub_545D70(0);
	static_cast<LabelControlVTable *>(_gameCivsLabel->_VTable)->AssignTextFromLanguageDlls(_gameCivsLabel, 20125);

	// Create "Not researched" label
	static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, &_legendNotResearchedLabel, 0, 2, 2, 160, 25, 13, 0, 0, 0);
	_legendNotResearchedLabel->_VTable->InvalidateAndRedrawControl1(_legendNotResearchedLabel, 0);
	_legendNotResearchedLabel->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_legendNotResearchedLabel->SetStyleText2Colors(0, 0);
	_legendNotResearchedLabel->sub_545D70(0);
	static_cast<LabelControlVTable *>(_legendNotResearchedLabel->_VTable)->AssignTextFromLanguageDlls(_legendNotResearchedLabel, 20124);

	// Create "Researched" label
	static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, &_legendResearchedLabel, 0, 2, 2, 160, 25, 13, 0, 0, 0);
	_legendResearchedLabel->_VTable->InvalidateAndRedrawControl1(_legendResearchedLabel, 0);
	_legendResearchedLabel->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_legendResearchedLabel->SetStyleText2Colors(0, 0);
	_legendResearchedLabel->sub_545D70(0);
	static_cast<LabelControlVTable *>(_legendResearchedLabel->_VTable)->AssignTextFromLanguageDlls(_legendResearchedLabel, 20128);

	// Create node type labels
	_legendNodeTypeLabels = new std::vector<LabelControl *>();
	int nodeTypeLabelCount = _renderer->GetLegendNodeTypeCount();
	for(int i = 0; i < nodeTypeLabelCount; ++i)
	{
		// Create label
		LabelControl *legendNodeTypeLabel;
		static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, &legendNodeTypeLabel, 0, 2, 2, 160, 25, 13, 0, 0, 0);
		legendNodeTypeLabel->_VTable->InvalidateAndRedrawControl1(legendNodeTypeLabel, 0);
		legendNodeTypeLabel->AssignIdToControlAndMoveInParentChildrenList(1, 0);
		legendNodeTypeLabel->SetStyleText2Colors(0, 0);
		legendNodeTypeLabel->sub_545D70(0);
		static_cast<LabelControlVTable *>(legendNodeTypeLabel->_VTable)->AssignTextFromLanguageDlls(legendNodeTypeLabel, _renderer->GetLegendNodeTypeLabelDllId(i));
		_legendNodeTypeLabels->push_back(legendNodeTypeLabel);
	}

	// Create "Disabled" label
	static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, &_legendDisabledLabel, 0, 2, 2, 160, 25, 13, 0, 0, 0);
	_legendDisabledLabel->_VTable->InvalidateAndRedrawControl1(_legendDisabledLabel, 0);
	_legendDisabledLabel->AssignIdToControlAndMoveInParentChildrenList(1, 0);
	_legendDisabledLabel->SetStyleText2Colors(0, 0);
	_legendDisabledLabel->sub_545D70(0);
	static_cast<LabelControlVTable *>(_legendDisabledLabel->_VTable)->AssignTextFromLanguageDlls(_legendDisabledLabel, 20119);

	// Fill civ selection combo box
	int civCount = (*_staticGameObjectPointer)->GetGameDataHandler()->_civCount;
	char civNameBuffer[128];
	char civNameSuffixBuffer[128];
	char civNameMergedBuffer[256];
	for(int c = 1; c < civCount; ++c)
	{
		// Clear strings
		civNameBuffer[0] = '\0';
		civNameSuffixBuffer[0] = '\0';
		civNameMergedBuffer[0] = '\0';

		// Load civ name
		(*_staticGameObjectPointer)->GetIndexedDllString(105, c, 0, civNameBuffer, sizeof(civNameBuffer));

		// Load civ suffix " (Player)" or " (Ally)", if neccessary
		if(_unknownGameAndPlayerData != 0)
			if(reinterpret_cast<char *>(_unknownGameAndPlayerData)[349] == c) // Check player
				(*_staticGameObjectPointer)->GetStringFromLanguageDllsWithBuffer(20126, civNameSuffixBuffer, sizeof(civNameSuffixBuffer));
			else
			{
				// Check allies
				GameDataHandler *gdh = (*_staticGameObjectPointer)->GetGameDataHandler();
				for(int p = 1; p < 9; ++p)
					if(reinterpret_cast<char *>(_unknownGameAndPlayerData + 6458)[p] == 4 && reinterpret_cast<char *>(gdh->_dword4C[p])[349] == c)
					{
						// Get suffix and break
						(*_staticGameObjectPointer)->GetStringFromLanguageDllsWithBuffer(20127, civNameSuffixBuffer, sizeof(civNameSuffixBuffer));
						break;
					}
			}

		// Merge civ name and suffix
		sprintf(civNameMergedBuffer, "%s%s", civNameBuffer, civNameSuffixBuffer);

		// Add civ to list
		_civSelectionComboBox->AddItem(civNameMergedBuffer, c);
	}
	_civSelectionComboBox->SetSelectedIndex(0);

	// Create age labels
	_ageLabels = new LabelControl*[_ageCount][2][2];
	for(int i = 0; i < _ageCount; ++i)
	{
		// Create 4 labels for this age
		for(int j = 0; j < 4; ++j)
		{
			// Create and initialize label
			LabelControl **currAgeLabelPointer = &_ageLabels[i][j >> 1][j & 1];
			static_cast<PanelVTable *>(_VTable)->CreateLabelWithOneFontWithTextFromDll(this, this, currAgeLabelPointer, 0, 2, 2, 150, 25, 11, 1, 0, 1);
			(*currAgeLabelPointer)->_VTable->InvalidateAndRedrawControl1(*currAgeLabelPointer, 0);
			(*currAgeLabelPointer)->AssignIdToControlAndMoveInParentChildrenList(1, 0);
			(*currAgeLabelPointer)->SetStyleText2Colors(0, 0);
			(*currAgeLabelPointer)->sub_545D70(0);
		}

		// Set label texts
		static_cast<LabelControlVTable *>(_ageLabels[i][0][0]->_VTable)->AssignTextFromLanguageDlls(_ageLabels[i][0][0], _designData->_firstLineBaseDllId + i);
		static_cast<LabelControlVTable *>(_ageLabels[i][0][1]->_VTable)->AssignTextFromLanguageDlls(_ageLabels[i][0][1], _designData->_secondLineDllId + (_designData->_incrementSecondLineDllId ? i : 0));
		static_cast<LabelControlVTable *>(_ageLabels[i][1][0]->_VTable)->AssignTextFromLanguageDlls(_ageLabels[i][1][0], _designData->_firstLineBaseDllId + i);
		static_cast<LabelControlVTable *>(_ageLabels[i][1][1]->_VTable)->AssignTextFromLanguageDlls(_ageLabels[i][1][1], _designData->_secondLineDllId + (_designData->_incrementSecondLineDllId ? i : 0));
	}

	// Create popup label
	_popupLabelBaseFont = (*_staticGameObjectPointer)->GetFontWithIndex(10);
	HFONT popupLabelFonts[4];
	popupLabelFonts[0] = _popupLabelBaseFont->GetFontHandle();
	popupLabelFonts[1] = (*_staticGameObjectPointer)->GetFontWithIndex(17)->GetFontHandle();
	popupLabelFonts[2] = (*_staticGameObjectPointer)->GetFontWithIndex(18)->GetFontHandle();
	popupLabelFonts[3] = (*_staticGameObjectPointer)->GetFontWithIndex(19)->GetFontHandle();
	_popupLabel = new LabelControl();
	_popupLabel->sub_5444B0(_backBufferData, this, 0, 0, _designData->_popupLabelWidth, 50, popupLabelFonts, _popupLabelBaseFont->GetAverageCharWidth(), _popupLabelBaseFont->GetCharHeightWithRowSpace(), nullptr, 0, 0, 0, 0, 0, nullptr);
	_popupLabel->SetTextAlignment(3, 1);
	_popupLabel->sub_545D50(1);
	_popupLabel->sub_545D70(0);
	_popupLabel->SetStyleText2Colors(0x000000, 0x00E7E7);

	// Set current civ
	if(unknownGameAndPlayerData != 0)
		selectedCivId = reinterpret_cast<char *>(unknownGameAndPlayerData)[349];
	if(selectedCivId < 1)
		selectedCivId = 1;
	_civSelectionComboBox->SetSelectedItemId(selectedCivId);
	SetCurrentCiv(selectedCivId);

	// No element is selected
	_selectedElement = nullptr;
	_drawPopupLabelBox = false;
	_selectedElementChangedTime = 0;

	// Issue redraw
	_VTable->InvalidateAndRedrawControl2(this, 2);

	// Return reference to self
	return this;
}
void
createControls( ControlCanvas* cs )
{
    // a container centered on the screen, containing an image and a text label.
    {
        VBox* center = new VBox();
        center->setFrame( new RoundedFrame() );
        center->getFrame()->setBackColor( 1,1,1,0.5 );
        center->setPadding( 10 );
        center->setHorizAlign( Control::ALIGN_CENTER );
        center->setVertAlign( Control::ALIGN_CENTER );

        // Add an image:
        osg::ref_ptr<osg::Image> image = osgDB::readImageFile("http://demo.pelicanmapping.com/rmweb/readymap_logo.png");
        if ( image.valid() )
        {
            s_imageControl = new ImageControl( image.get() );
            s_imageControl->setHorizAlign( Control::ALIGN_CENTER );
            s_imageControl->setFixSizeForRotation( true );
            //imageCon->addEventHandler( new ImageRotationHandler );
            center->addControl( s_imageControl );
            center->setHorizAlign( Control::ALIGN_CENTER );
        }

        // Add a text label:
        LabelControl* label = new LabelControl( "osgEarth Controls Toolkit" );
        label->setFont( osgEarth::Registry::instance()->getDefaultFont() );
        label->setFontSize( 24.0f );
        label->setHorizAlign( Control::ALIGN_CENTER );
        label->setMargin( 5 );
        center->addControl( label );

        // Rotation slider
        HBox* rotateBox = new HBox();
        rotateBox->setChildVertAlign( Control::ALIGN_CENTER );
        rotateBox->setHorizFill( true );
        rotateBox->setBackColor( Color::Blue );
        {
            rotateBox->addControl( new LabelControl("Rotate: ") );

            HSliderControl* rotateSlider = new HSliderControl( -180.0, 180.0, 0.0 );
            rotateSlider->addEventHandler( new RotateImage() );
            rotateSlider->setHeight( 8.0f );
            rotateSlider->setHorizFill( true );
            rotateBox->addControl( rotateSlider );
        }
        center->addControl( rotateBox );

        cs->addControl( center );
    }

    // a simple vbox with absolute positioning in the upper left with two text labels.
    {
        VBox* ul = new VBox();
        ul->setPosition( 20, 20 );
        ul->setPadding( 10 );
        {
            LabelControl* title = new LabelControl( "Upper left control", 22, osg::Vec4f(1,1,0,1) );
            ul->addControl( title );

            LabelControl* content = new LabelControl( "Here is some text in the upper left control" );
            ul->addControl( content );

            HBox* c2 = new HBox();
            c2->setChildSpacing( 10 );
            {
                HSliderControl* slider = new HSliderControl( 0, 100 );
                slider->setBackColor( .6,0,0,1 );
                slider->setHeight( 25 );
                slider->setWidth( 300 );
                slider->addEventHandler( new MySliderHandler() );
                c2->addControl( slider );

                s_sliderLabel = new LabelControl();
                s_sliderLabel->setVertAlign( Control::ALIGN_CENTER );
                c2->addControl( s_sliderLabel );        
            }
            ul->addControl( c2 );

            HBox* c3 = new HBox();
            c3->setHorizAlign( Control::ALIGN_CENTER );
            c3->setChildSpacing( 10 );
            {
                HBox* c4 = new HBox();
                c4->setChildSpacing( 5 );
                {
                    c4->addControl( new CheckBoxControl( true ) );
                    c4->addControl( new LabelControl( "Checkbox 1" ) );
                }
                c3->addControl( c4 );

                HBox* c5 = new HBox();
                c5->setChildSpacing( 5 );
                {
                    c5->addControl( new CheckBoxControl( false ) );
                    c5->addControl( new LabelControl( "Checkbox 2" ) );
                }
                c3->addControl( c5 );
            }
            ul->addControl( c3 );
        }
        cs->addControl( ul );

        ul->addEventHandler( new MyClickHandler );
    }

    // a centered hbox container along the bottom on the screen.
    {
        HBox* bottom = new HBox();
        bottom->setFrame( new RoundedFrame() );
        bottom->getFrame()->setBackColor(0,0,0,0.5);
        bottom->setMargin( 10 );
        bottom->setChildSpacing( 145 );
        bottom->setVertAlign( Control::ALIGN_BOTTOM );
        bottom->setHorizAlign( Control::ALIGN_CENTER );

        for( int i=0; i<4; ++i )
        {
            LabelControl* label = new LabelControl();
            std::stringstream buf;
            buf << "Label_" << i;
            std::string str;
            str = buf.str();
            label->setText( str );
            label->setMargin( 10 );
            label->setBackColor( 1,1,1,0.4 );
            bottom->addControl( label );

            label->setActiveColor(1,.3,.3,1);
            label->addEventHandler( new MyClickHandler );
        }

        cs->addControl( bottom );
    }
}
Beispiel #30
0
void
createLayerItem( Grid* grid, int gridRow, int layerIndex, int numLayers, TerrainLayer* layer, bool isActive )
{
    int gridCol = 0;

    // a checkbox to enable/disable the layer:
    CheckBoxControl* enabled = new CheckBoxControl( layer->getVisible() );
    enabled->addEventHandler( new LayerVisibleHandler(layer) );
    grid->setControl( gridCol++, gridRow, enabled );

    // the layer name
    LabelControl* name = new LabelControl( layer->getName() );
    grid->setControl( gridCol, gridRow, name );
    gridCol++;

    ImageLayer* imageLayer = dynamic_cast< ImageLayer* > (layer );
    if (imageLayer)
    {
        // an opacity slider
        HSliderControl* opacity = new HSliderControl( 0.0f, 1.0f, imageLayer->getOpacity() );
        opacity->setWidth( 125 );
        opacity->setHeight( 12 );
        opacity->addEventHandler( new LayerOpacityHandler(imageLayer) );
        grid->setControl( gridCol, gridRow, opacity );
    }
    gridCol++;

    // status indicator
    LabelControl* statusLabel = layer->getStatus().isOK()
        ? new LabelControl("[ok]", osg::Vec4(0,1,0,1))
        : new LabelControl("[error]", osg::Vec4(1,0,0,1));
    grid->setControl( gridCol, gridRow, statusLabel );
    gridCol++;

    // move buttons
    if ( layerIndex < numLayers-1 && isActive )
    {
        LabelControl* upButton = new LabelControl( "UP", 14 );
        upButton->setBackColor( .4,.4,.4,1 );
        upButton->setActiveColor( .8,0,0,1 );
        upButton->addEventHandler( new MoveLayerHandler( layer, layerIndex+1 ) );
        grid->setControl( gridCol, gridRow, upButton );
    }
    gridCol++;

    if ( layerIndex > 0 && isActive)
    {
        LabelControl* upButton = new LabelControl( "DOWN", 14 );
        upButton->setBackColor( .4,.4,.4,1 );
        upButton->setActiveColor( .8,0,0,1 );
        upButton->addEventHandler( new MoveLayerHandler( layer, layerIndex-1 ) );
        grid->setControl( gridCol, gridRow, upButton );
    }
    gridCol++;

    // add/remove button:
    LabelControl* addRemove = new LabelControl( isActive? "REMOVE" : "ADD", 14 );
    addRemove->setHorizAlign( Control::ALIGN_CENTER );
    addRemove->setBackColor( .4,.4,.4,1 );
    addRemove->setActiveColor( .8,0,0,1 );
    if ( isActive )
        addRemove->addEventHandler( new RemoveLayerHandler(layer) );
    else
        addRemove->addEventHandler( new AddLayerHandler(layer) );
    grid->setControl( gridCol, gridRow, addRemove );
    gridCol++;
}