当前位置: 首页>>代码示例>>C++>>正文


C++ osg::ref_ptr类代码示例

本文整理汇总了C++中osg::ref_ptr的典型用法代码示例。如果您正苦于以下问题:C++ ref_ptr类的具体用法?C++ ref_ptr怎么用?C++ ref_ptr使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ref_ptr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: StateSet

bool
ShaderGenerator::processGeometry(const osg::StateSet*         original, 
                                 osg::ref_ptr<osg::StateSet>& replacement)
{
    // do nothing if there's no GLSL support
    if ( !_active )
        return false;
    
    // capture the active current state:
    osg::ref_ptr<osg::StateSet> current = static_cast<StateEx*>(_state.get())->capture();

    // check for a real osg::Program in the whole state stack. If it exists, bail out
    // so that OSG can use the program already in the graph. We never override a
    // full Program.
    osg::StateAttribute* program = current->getAttribute(osg::StateAttribute::PROGRAM);
    if ( dynamic_cast<osg::Program*>(program) != 0L )
        return false;

    // Copy or create a new stateset (that we may or may not use depending on
    // what we find). Never modify an existing stateset!
    osg::ref_ptr<osg::StateSet> newStateSet =
        original ? osg::clone(original, osg::CopyOp::SHALLOW_COPY) :
        new osg::StateSet();

    // likewise, create a VP that we might populate.
    osg::ref_ptr<VirtualProgram> vp = VirtualProgram::cloneOrCreate(original, newStateSet);

    // we'll set this to true if the new stateset goes into effect and
    // needs to be returned.
    bool needNewStateSet = false;
    bool needVertexFunction = false;
    bool needFragmentFunction = false;
    
    // give the VP a name if it needs one.
    if ( vp->getName().empty() )
    {
        vp->setName( _name );
    }

    // Check whether the lighting state has changed and install a mode uniform.
    // TODO: fix this
    if ( original && original->getMode(GL_LIGHTING) != osg::StateAttribute::INHERIT )
    {
        needNewStateSet = true;
        osg::StateAttribute::GLModeValue value = current->getMode(GL_LIGHTING);
        newStateSet->addUniform( Registry::shaderFactory()->createUniformForGLMode(GL_LIGHTING, value) );
    }
    
    // start generating the shader source.
    GenBuffers buf;
    buf._stateSet = newStateSet.get();

    // if the stateset changes any texture attributes, we need a new virtual program:
    if (current->getTextureAttributeList().size() > 0)
    {
        bool wroteTexelDecl = false;

        // Loop over all possible texture image units.
        int maxUnit = Registry::capabilities().getMaxGPUTextureUnits();

        for( int unit = 0; unit < maxUnit; ++unit )
        {
            if ( !wroteTexelDecl )
            {
                buf._fragBody << INDENT << MEDIUMP "vec4 texel; \n";
                wroteTexelDecl = true;
            }

            osg::Texture* tex = dynamic_cast<osg::Texture*>( current->getTextureAttribute(unit, osg::StateAttribute::TEXTURE) );

            if (accept(tex) && !ImageUtils::isFloatingPointInternalFormat(tex->getInternalFormat()))
            {
                osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(current->getTextureAttribute(unit, osg::StateAttribute::TEXGEN));
                osg::TexEnv* texenv = dynamic_cast<osg::TexEnv*>(current->getTextureAttribute(unit, osg::StateAttribute::TEXENV));
                osg::TexMat* texmat = dynamic_cast<osg::TexMat*>(current->getTextureAttribute(unit, osg::StateAttribute::TEXMAT));
                osg::PointSprite* sprite = dynamic_cast<osg::PointSprite*>(current->getTextureAttribute(unit, osg::StateAttribute::POINTSPRITE));
                
                if ( apply(tex, texgen, texenv, texmat, sprite, unit, buf) == true )
                {
                    needNewStateSet = true;
                }
            }
        }
    }

    // Process the state attributes.
    osg::StateSet::AttributeList& attrs = current->getAttributeList();
    if ( apply(attrs, buf) )
    {
        needNewStateSet = true;
    }

    if ( needNewStateSet )
    {
        std::string version = GLSL_VERSION_STR;

        std::string vertHeadSource;
        vertHeadSource = buf._vertHead.str();

        std::string vertBodySource;
//.........这里部分代码省略.........
开发者ID:rhabacker,项目名称:osgearth,代码行数:101,代码来源:ShaderGenerator.cpp

示例2: createImage


//.........这里部分代码省略.........
        // http://msdn.microsoft.com/en-us/library/ff701716.aspx

        // construct the request URI:
        std::string request = Stringify()
            << std::setprecision(12)
            << _options.imageryMetadataAPI().get()     // base REST API
            << "/"    << _options.imagerySet().get()   // imagery set to use
            << "/"    << geo.y() << "," << geo.x()     // center point in lat/long
            << "?zl=" << key.getLOD() + 1              // zoom level
            << "&o=json"                               // response format
            << "&key=" << _options.key().get();        // API key

        // check the URI cache.
        URI                  location;
        TileURICache::Record rec;

        if ( _tileURICache.get(request, rec) )
        {
            location = URI(rec.value());
            //CacheStats stats = _tileURICache.getStats();
            //OE_INFO << "Ratio = " << (stats._hitRatio*100) << "%" << std::endl;
        }
        else
        {
            unsigned c = ++_apiCount;
            if ( c % 25 == 0 )
                OE_INFO << LC << "API calls = " << c << std::endl;
            
            // fetch it:
            ReadResult metadataResult = URI(request).readString(_dbOptions, progress);

            if ( metadataResult.failed() )
            {
                // check for a REST error:
                if ( metadataResult.code() == ReadResult::RESULT_SERVER_ERROR )
                {
                    OE_WARN << LC << "REST API request error!" << std::endl;

                    Config metadata;
                    std::string content = metadataResult.getString();
                    metadata.fromJSON( content );
                    ConfigSet errors = metadata.child("errorDetails").children();
                    for(ConfigSet::const_iterator i = errors.begin(); i != errors.end(); ++i )
                    {
                        OE_WARN << LC << "REST API: " << i->value() << std::endl;
                    }
                    return 0L;
                }
                else
                {
                    OE_WARN << LC << "Request error: " << metadataResult.getResultCodeString() << std::endl;
                }
                return 0L;
            }

            // decode it:
            Config metadata;
            if ( !metadata.fromJSON(metadataResult.getString()) )
            {
                OE_WARN << LC << "Error decoding REST API response" << std::endl;
                return 0L;
            }

            // check the vintage field. If it's empty, that means we got a "no data" tile.
            Config* vintageEnd = metadata.find("vintageEnd");
            if ( !vintageEnd || vintageEnd->value().empty() )
            {
                OE_DEBUG << LC << "NO data image encountered." << std::endl;
                return 0L;
            }

            // find the tile URI:
            Config* locationConf= metadata.find("imageUrl");
            if ( !locationConf )
            {
                OE_WARN << LC << "REST API JSON parsing error (imageUrl not found)" << std::endl;
                return 0L;
            }

            location = URI( locationConf->value() );
            _tileURICache.insert( request, location.full() );
        }

        // request the actual tile
        //OE_INFO << "key = " << key.str() << ", URL = " << location->value() << std::endl;

        //osg::Image* image = location.getImage(_dbOptions.get(), progress);
        osg::Image* image = osgDB::readImageFile( location.full() );

        if ( image &&  _geom.valid() )
        {
            GeometryRasterizer rasterizer( image->s(), image->t() );
            rasterizer.draw( _geom.get(), osg::Vec4(1,1,1,1) );
            osg::ref_ptr<osg::Image> overlay = rasterizer.finalize();
            ImageUtils::PixelVisitor<AlphaBlend> blend;
            blend.accept( overlay.get(), image );
        }

        return image;
    }
开发者ID:Sylla,项目名称:osgearth,代码行数:101,代码来源:BingTileSource.cpp

示例3: getGlobalFadeText

GlobalFadeText* getGlobalFadeText()
{
    static osg::ref_ptr<GlobalFadeText> s_globalFadeText = new GlobalFadeText;
    return s_globalFadeText.get();
}
开发者ID:LaurensVoerman,项目名称:OpenSceneGraph,代码行数:5,代码来源:FadeText.cpp

示例4: AddModelNode

// Add model to scene
void ViewerQT::AddModelNode(osg::ref_ptr<osg::Node> mnode)
{
    m_rpSceneGroupRoot->addChild(mnode.get());
}
开发者ID:onism,项目名称:GTea,代码行数:5,代码来源:AdapterWidget.cpp

示例5: main

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");

    arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation [TabPlaneDragger, TabPlaneTrackballDragger, TrackballDragger, Translate1DDragger, Translate2DDragger, TranslateAxisDragger, TabBoxDragger, TranslatePlaneDragger, Scale1DDragger, Scale2DDragger, RotateCylinderDragger, RotateSphereDragger]");
    arguments.getApplicationUsage()->addCommandLineOption("--fixedDraggerSize","Fix the size of the dragger geometry in the screen space");

    bool fixedSizeInScreen = false;
    while (arguments.read("--fixedDraggerSize")) { fixedSizeInScreen = true; }


    // construct the viewer.
    osgViewer::Viewer viewer(arguments);

    // add the window size toggle handler
    viewer.addEventHandler(new osgViewer::WindowSizeHandler);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());


    if (arguments.read("--test-NodeMask"))
    {
        const osg::ref_ptr<osg::Group> group = new osg::Group();
        group->setNodeMask(0);

        const osg::ref_ptr<osgManipulator::AntiSquish> antiSquish = new osgManipulator::AntiSquish();

        group->addChild(antiSquish.get());

        const osg::ref_ptr<osg::Node> node = new osg::Node();
        node->setInitialBound(osg::BoundingSphere(osg::Vec3(0.0, 0.0, 0.0), 1.0));

        antiSquish->addChild(node.get());

        group->getBound();

        return 1;
    }



    // if user request help write it out to cout.
    bool helpAll = arguments.read("--help-all");
    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
    if (helpType)
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    std::string dragger_name = "TabBoxDragger";
    arguments.read("--dragger", dragger_name);

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

    // read the scene from the list of file specified command line args.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);

    // if no model has been successfully loaded report failure.
    bool tragger2Scene(true);
    if (!loadedModel)
    {
        //std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        //return 1;
        loadedModel = createDemoScene(fixedSizeInScreen);
        tragger2Scene=false;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
    }

    osg::Timer_t end_tick = osg::Timer::instance()->tick();
//.........这里部分代码省略.........
开发者ID:yueying,项目名称:osg,代码行数:101,代码来源:osgmanipulator.cpp

示例6: instance

 static FlexUpdater* instance()
 {
     static osg::ref_ptr<FlexUpdater> s_instance = new FlexUpdater;
     return s_instance.get();
 }
开发者ID:whztt07,项目名称:test_osg,代码行数:5,代码来源:FlexDrawable.cpp

示例7: catch

bool
Geometry::geounion( const Geometry* other, osg::ref_ptr<Geometry>& output ) const
{
#ifdef OSGEARTH_HAVE_GEOS
    bool success = false;
    output = 0L;

    GEOSContext gc;

    //Create the GEOS Geometries
    geom::Geometry* inGeom   = gc.importGeometry( this );
    geom::Geometry* otherGeom = gc.importGeometry( other );

    if ( inGeom )
    {    
        geom::Geometry* outGeom = 0L;
        try {
            outGeom = overlay::OverlayOp::overlayOp(
                inGeom,
                otherGeom,
                overlay::OverlayOp::opUNION );
        }
        catch(const geos::util::GEOSException& ex) {
            OE_NOTICE << LC << "Union(GEOS): "
                << (ex.what()? ex.what() : " no error message")
                << std::endl;
            outGeom = 0L;
        }

        if ( outGeom )
        {
            output = gc.exportGeometry( outGeom );

            if ( output.valid())
            {
                if ( output->isValid() )
                {
                    success = true;
                }
                else
                {
                    // GEOS result is invalid
                    output = 0L;
                }
            }
            else
            {
                // set output to empty geometry to indicate the (valid) empty case,
                // still returning false but allows for check.
                if (outGeom->getNumPoints() == 0)
                {
                    output = new osgEarth::Symbology::Geometry();
                }
            }

            gc.disposeGeometry( outGeom );
        }
    }

    //Destroy the geometry
    gc.disposeGeometry( otherGeom );
    gc.disposeGeometry( inGeom );

    return success;

#else // OSGEARTH_HAVE_GEOS

    OE_WARN << LC << "Union failed - GEOS not available" << std::endl;
    return false;

#endif // OSGEARTH_HAVE_GEOS
}
开发者ID:3dcl,项目名称:osgearth,代码行数:72,代码来源:Geometry.cpp

示例8: main

namespace vrc
{

static const char glsl_vp[] =
    "/*                                                                             \n"
    "* Vertex shader for rendering the player                                       \n"
    "* http://yag2002.sf.net                                                        \n"
    "* 11/28/2005                                                                   \n"
    "*/                                                                             \n"
    "varying vec4 diffuse,ambient;                                                  \n"
    "varying vec3 normal,lightDir,halfVector;                                       \n"
    "                                                                               \n"
    "void main()                                                                    \n"
    "{                                                                              \n"
    "   normal      = normalize(gl_NormalMatrix * gl_Normal);                       \n"
    "   lightDir    = normalize(vec3(gl_LightSource[0].position));                  \n"
    "   halfVector  = normalize(gl_LightSource[0].halfVector.xyz);                  \n"
    "   diffuse     = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;         \n"
    "   ambient     = gl_FrontMaterial.ambient * gl_LightSource[0].ambient;         \n"
    "   ambient     += gl_LightModel.ambient * gl_FrontMaterial.ambient;            \n"
    "   gl_Position = ftransform();                                                 \n"
    "}                                                                              \n"
;
static const char glsl_fp[] =
    "/*                                                                             \n"
    "* Fragment shader for rendering the player                                     \n"
    "* http://yag2002.sf.net                                                        \n"
    "* 11/28/2005                                                                   \n"
    "*/                                                                             \n"
    "varying vec4 diffuse,ambient;                                                  \n"
    "varying vec3 normal,lightDir,halfVector;                                       \n"
    "uniform sampler2D tex;                                                         \n"
    "                                                                               \n"
    "void main()                                                                    \n"
    "{                                                                              \n"
    "   vec3 n,halfV;                                                               \n"
    "   float NdotL,NdotHV;                                                         \n"
    "                                                                               \n"
    "   vec4 color = ambient;                                                       \n"
    "   n = normalize(normal);                                                      \n"
    "   NdotL = max(dot(n,lightDir),0.0);                                           \n"
    "    if (NdotL > 0.0) {                                                         \n"
    "       color += diffuse * NdotL;                                               \n"
    "       halfV = normalize(halfVector);                                          \n"
    "       NdotHV = max(dot(n,halfV),0.0);                                         \n"
    "       color += gl_FrontMaterial.specular *                                    \n"
    "               gl_LightSource[0].specular *                                    \n"
    "               pow(NdotHV, gl_FrontMaterial.shininess);                        \n"
    "   }                                                                           \n"
    "                                                                               \n"
    "   vec4 texcolor = texture2D(tex,gl_TexCoord[0].st);                           \n"
    "   gl_FragColor = color * texcolor;                                            \n"
    "}                                                                              \n"
;

static osg::ref_ptr< osg::Program > s_program;

//! "Implement and register the player animation entity factory
YAF3D_IMPL_ENTITYFACTORY( PlayerAnimationEntityFactory );

EnPlayerAnimation::EnPlayerAnimation() :
_anim( eIdle ),
_p_player( NULL ),
_renderingEnabled( true ),
_scale( 1.0f ),
_IdAnimIdle( -1 ),
_IdAnimWalk( -1 ),
_IdAnimRun( -1 ),
_IdAnimJump( -1 ),
_IdAnimLand( -1 ),
_IdAnimTurn( -1 )
{ 
    // register attributes
    getAttributeManager().addAttribute( "animconfig"   , _animCfgFile );
    getAttributeManager().addAttribute( "position"     , _position    );
    getAttributeManager().addAttribute( "rotation"     , _rotation    );
    getAttributeManager().addAttribute( "scale"        , _scale       );
}

EnPlayerAnimation::~EnPlayerAnimation()
{
    if ( _animNode.get() )
        _animNode = NULL; // delete the anim node
}

void EnPlayerAnimation::initialize()
{
    log_info << "  initializing player animation instance '" << getInstanceName() << "' ..." << std::endl;

    if ( !_animCfgFile.length() )
    {
        log_error << "*** missing animation config file parameter" << std::endl;
        return;
    }
    
    // setup and create a new model
    std::string file     = yaf3d::Application::get()->getMediaPath() + _animCfgFile;
    std::string rootDir  = yaf3d::extractPath( file );
    std::string configfilename = yaf3d::extractFileName( file );
    // all textures and cal3d files must be in root dir!
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:yag2002-svn,代码行数:101,代码来源:vrc_playeranim.cpp

示例9: main

int main(void){
	osg::DisplaySettings::instance()->setNumMultiSamples( 4 );
	viewer.setUpViewInWindow( 100, 50, 800, 600 );
	viewer.getCamera()->setClearColor( osg::Vec4( 0.5,0.5,0.5,1) );
	viewer.addEventHandler(new osgViewer::StatsHandler);
	
	osg::Group* scene = new osg::Group;
	
	// Création d'une boîte centrée à l'origine, de dimensions 2x3x4:
	osg::Box* boite = new osg::Box(osg::Vec3(-10, 0, 0), 2,3,4);
	osg::ShapeDrawable* boiteDrawable = new osg::ShapeDrawable(boite);
	osg::Geode* geodeBoite = new osg::Geode();
	geodeBoite->addDrawable(boiteDrawable);
	
	osg::Sphere* sphere = new osg::Sphere( osg::Vec3(10,0,0), 1.0);
	osg::ShapeDrawable* sphereDrawable = new osg::ShapeDrawable(sphere);
	osg::Geode* geodeSphere = new osg::Geode();
	geodeSphere->addDrawable(sphereDrawable);
	
	osg::Capsule* capsule = new osg::Capsule(osg::Vec3(0, 0, 0), 1.0, 3.0);
	osg::ShapeDrawable* capsuleDrawable = new osg::ShapeDrawable(capsule);
	osg::Geode* geodeCapsule = new osg::Geode();
	geodeCapsule->addDrawable(capsuleDrawable);
	
	osg::Cone* cone = new osg::Cone(osg::Vec3(0, 10, 0), 1, 2);
	osg::ShapeDrawable* coneDrawable = new osg::ShapeDrawable(cone);
	osg::Geode* geodeCone= new osg::Geode();
	geodeCone->addDrawable(coneDrawable);
	
	
	osg::Material* matBoite = new osg::Material;
	matBoite->setAmbient (osg::Material::FRONT_AND_BACK, osg::Vec4(0.5, 0.0, 0.0, 1.0));
	matBoite->setDiffuse (osg::Material::FRONT_AND_BACK, osg::Vec4(0.9, 0.0, 0.0, 1.0));
	matBoite->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.2, 0.2, 0.2, 1.0));
	matBoite->setShininess(osg::Material::FRONT_AND_BACK, 64);
	
	osg::Material* matCone = new osg::Material;
	matCone->setAmbient (osg::Material::FRONT_AND_BACK, osg::Vec4(0.5, 0.0, 0.5, 1.0));
	matCone->setDiffuse (osg::Material::FRONT_AND_BACK, osg::Vec4(0.9, 0.0, 0.9, 1.0));
	matCone->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.2, 0.2, 0.2, 1.0));
	matCone->setShininess(osg::Material::FRONT_AND_BACK, 64);
	
	osg::Node* aregne = osgDB::readNodeFile("cow_high.3ds"); 
	
	transformAregne->setPosition(osg::Vec3(5, 0, 0));
	transformAregne->setScale(osg::Vec3(0.2, 0.2, 0.2));
	transformAregne->getOrCreateStateSet()->setMode(GL_NORMALIZE,osg::StateAttribute::ON); 
	transformAregne->addChild(aregne);
	
	boiteDrawable->getOrCreateStateSet()->setAttributeAndModes(matBoite);
	coneDrawable->getOrCreateStateSet()->setAttributeAndModes(matCone);
	
	
	/*scene->addChild(geodeCapsule);
	scene->addChild(geodeCone);
	scene->addChild(geodeBoite);
	scene->addChild(geodeSphere);
	scene->addChild(transformAregne);*/
	scene->addChild(aregne);
	
	// Création d'une texture
osg::ref_ptr<osg::Texture2D> tex2D = new osg::Texture2D;
tex2D->setTextureSize(1024, 1024);
tex2D->setInternalFormat(GL_RGBA);
// Création d'une caméra qui effectuera son rendu dans la texture
osg::ref_ptr<osg::Camera> rttCamera =
 createRTTCamera(osg::Camera::COLOR_BUFFER, tex2D.get());
// On indique la partie du graphe que la caméra devra rendre, ici toute la scène :
rttCamera->addChild(scene);
// Création d'une caméra permettant d'afficher un HUD qui couvrira tout l'écran
osg::ref_ptr<osg::Camera> hudCamera = createHUDCamera();
osg::Geode* screenQuad = createScreenQuad();
hudCamera->addChild(screenQuad);
osg::StateSet* stateset = screenQuad->getOrCreateStateSet();
stateset->setTextureAttributeAndModes(0, tex2D.get());
// VOUS METTREZ ICI LE CODE DE LA QUESTION 7
// Création d'une nouvelle racine du graphe, à laquelle on rattache la caméra
// de rendu dans une texture, la caméra du HUD et la racine du graphe de la scène
osg::ref_ptr<osg::Group> root = new osg::Group;
root->addChild(rttCamera.get());
root->addChild(hudCamera.get());
root->addChild(scene);
// Indique au viewer la scène à affich
	
	trackCone->setTrackNode(geodeCone);
	trackCone->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER);
	
	
	trackBoite->setTrackNode(geodeBoite);
	trackBoite->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER);
	
	trackSphere->setTrackNode(geodeSphere);
	trackSphere->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER);
	
	transformAregne->setUpdateCallback(new Deplacement);
	
	viewer.setSceneData(scene);
	
	osg::ref_ptr<GestionEvenements> gestionnaire = new GestionEvenements();
	viewer.addEventHandler(gestionnaire.get());
//.........这里部分代码省略.........
开发者ID:ClementCvl,项目名称:CppMasterRace_50yIUT,代码行数:101,代码来源:main.cpp

示例10:

bool
HeightFieldCache::getOrCreateHeightField(const MapFrame&                 frame,
                                         const TileKey&                  key,
                                         //bool                            cummulative,
                                         const osg::HeightField*         parent_hf,
                                         osg::ref_ptr<osg::HeightField>& out_hf,
                                         bool&                           out_isFallback,
                                         ElevationSamplePolicy           samplePolicy,
                                         ElevationInterpolation          interp,
                                         ProgressCallback*               progress )
{                
    // default
    out_isFallback = false;

    // check the quick cache.
    HFKey cachekey;
    cachekey._key          = key;
    cachekey._revision     = frame.getRevision();
    cachekey._samplePolicy = samplePolicy;

    if (progress)
        progress->stats()["hfcache_try_count"] += 1;

    bool hit = false;
    LRUCache<HFKey,HFValue>::Record rec;
    if ( _cache.get(cachekey, rec) )
    {
        out_hf = rec.value()._hf.get();
        out_isFallback = rec.value()._isFallback;

        if (progress)
        {
            progress->stats()["hfcache_hit_count"] += 1;
            progress->stats()["hfcache_hit_rate"] = progress->stats()["hfcache_hit_count"]/progress->stats()["hfcache_try_count"];
        }

        return true;
    }

    // Find the parent tile and start with its heightfield.
    if ( parent_hf )
    {
        TileKey parentKey = key.createParentKey();
        
        out_hf = HeightFieldUtils::createSubSample(
            parent_hf,
            parentKey.getExtent(),
            key.getExtent(),
            interp );

        if ( !out_hf.valid() && ((int)key.getLOD())-1 > _firstLOD )
        {
            // This most likely means that a parent tile expired while we were building the child.
            // No harm done in that case as this tile will soo be discarded as well.
            OE_DEBUG << "MP HFC: Unable to find tile " << key.str() << " in the live tile registry"
                << std::endl;
            return false;
        }
    }

    if ( !out_hf.valid() )
    {
        //TODO.
        // This sets the elevation tile size; query size for all tiles.
        out_hf = HeightFieldUtils::createReferenceHeightField(
            key.getExtent(), _tileSize, _tileSize, true );
    }

    bool populated = frame.populateHeightField(
        out_hf,
        key,
        true, // convertToHAE
        samplePolicy,
        progress );

    // Treat Plate Carre specially by scaling the height values. (There is no need
    // to do this with an empty heightfield)
    const MapInfo& mapInfo = frame.getMapInfo();
    if ( mapInfo.isPlateCarre() )
    {
        HeightFieldUtils::scaleHeightFieldToDegrees( out_hf.get() );
    }

    // cache it.
    HFValue cacheval;
    cacheval._hf = out_hf.get();
    cacheval._isFallback = !populated;
    _cache.insert( cachekey, cacheval );

    out_isFallback = !populated;
    return true;
}
开发者ID:Geo12,项目名称:osgearth,代码行数:92,代码来源:HeightFieldCache.cpp

示例11:

void SpecialMatrix::MatrixViewer::exchangeNodes( osg::ref_ptr<Data::Node> srcNode, osg::ref_ptr<Data::Node> desNode )
{
	if ( srcNode->Data::AbsNode::getName().contains( 'x' ) && desNode->Data::AbsNode::getName().contains( 'y' ) ) {
		return;
	}
	if ( srcNode->Data::AbsNode::getName().contains( 'y' ) && desNode->Data::AbsNode::getName().contains( 'x' ) ) {
		return;
	}

	int separator = Util::ApplicationConfig::get()->getValue( "Viewer.Display.MatrixNodeSeparator" ).toInt();
	osg::ref_ptr<Data::Node> tempNode, foundNode;
	osg::Vec3f diffVector, finalPosVector;
	osg::Vec2f iNodeOldPos, iNodeNewPos;
	qlonglong foundNodeId;
	int srcNodePos, desNodePos, diff;

	if ( desNodePos < srcNodePos ) {
		tempNode = desNode;
		desNode = srcNode;
		srcNode = tempNode;
	}

	diff = desNodePos - srcNodePos;

	//srcNode, desNode are axisNodes
	if ( srcNode->Data::AbsNode::getName().contains( 'x' ) ) {
		srcNodePos = connections->getXAxisNodes()->indexOf( srcNode->getId() )+1;
		desNodePos = connections->getXAxisNodes()->indexOf( desNode->getId() )+1;
		connections->getXAxisNodes()->swap( srcNodePos, desNodePos );
		diffVector = osg::Vec3f( static_cast<float>( diff*separator ), 0.0f, 0.0f );
	}
	else {
		srcNodePos = connections->getYAxisNodes()->indexOf( srcNode->getId() )+1;
		desNodePos = connections->getYAxisNodes()->indexOf( desNode->getId() )+1;
		connections->getYAxisNodes()->swap( srcNodePos, desNodePos );
		diffVector = osg::Vec3f( 0.0f, static_cast<float>( diff*separator ), 0.0f );
	}

	//Src +diff
	QList<qlonglong>* connToSrcNodes = connections->getConnectedNodes()->value( srcNode->getId() );
	for ( int i=0; i<connToSrcNodes->size(); ++i ) {
		//get the nodes connected to scrNode
		tempNode = matrixGraph->findNodeById( connToSrcNodes->indexOf( i ) );
		//get the old position of the iNode, and delete from the positionArray
		iNodeOldPos.set( tempNode->getTargetPosition().x()/separator, tempNode->getTargetPosition().y()/separator );
		connections->setNodePositionsArrayField( iNodeOldPos.x(), iNodeOldPos.y(), 0 );
		//get the new position
		finalPosVector = tempNode->getTargetPosition() + diffVector;
		iNodeNewPos.set( static_cast<int>( finalPosVector.x()/separator ), static_cast<int>( finalPosVector.y()/separator ) );

		//CHECK AVAIBILITY
		foundNodeId = connections->getNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y() );
		if ( foundNodeId ) {
			foundNode = matrixGraph->findNodeById( foundNodeId );
			osg::Vec2f foundNodePos = fileParser->getAvailablePosition( connections, iNodeNewPos.x(), iNodeNewPos.y() );
			foundNode->setTargetPosition( osg::Vec3f( static_cast<float>( foundNodePos.x()*separator ), static_cast<float>( foundNodePos.y()*separator ), 0.0f ) );
			connections->setNodePositionsArrayField( foundNodePos.x(), foundNodePos.y(), foundNodeId );
		}

		tempNode->setTargetPosition( finalPosVector );
		tempNode->setRestrictedTargetPosition( tempNode->getTargetPosition() );
		connections->setNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y(), tempNode->getId() );
	}
	srcNode->setTargetPosition( srcNode->getTargetPosition() + diffVector );
	srcNode->setRestrictedTargetPosition( srcNode->getTargetPosition() );
	if ( srcNode->Data::AbsNode::getName().contains( 'x' ) ) {
		connections->setNodePositionsArrayField( desNodePos, 0, srcNode->getId() );
	}
	else {
		connections->setNodePositionsArrayField( 0, desNodePos, srcNode->getId() );
	}

	//Des -diff
	QList<qlonglong>* connToDesNodes = connections->getConnectedNodes()->value( desNode->getId() );
	for ( int i=0; i<connToDesNodes->size(); ++i ) {
		//get the nodes connected to scrNode
		tempNode = matrixGraph->findNodeById( connToDesNodes->indexOf( i ) );
		//get the old position of the iNode, and delete from the positionArray
		iNodeOldPos.set( tempNode->getTargetPosition().x()/separator, tempNode->getTargetPosition().y()/separator );
		connections->setNodePositionsArrayField( iNodeOldPos.x(), iNodeOldPos.y(), 0 );
		//get the new position
		finalPosVector = tempNode->getTargetPosition() - diffVector;
		iNodeNewPos.set( static_cast<int>( finalPosVector.x()/separator ), static_cast<float>( finalPosVector.y()/separator ) );

		//CHECK AVAIBILITY
		foundNodeId = connections->getNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y() );
		if ( foundNodeId ) {
			foundNode = matrixGraph->findNodeById( foundNodeId );
			osg::Vec2f foundNodePos = fileParser->getAvailablePosition( connections, iNodeNewPos.x(), iNodeNewPos.y() );
			foundNode->setTargetPosition( osg::Vec3f( static_cast<float>( foundNodePos.x()*separator ), static_cast<float>( foundNodePos.y()*separator ), 0.0f ) );
			connections->setNodePositionsArrayField( foundNodePos.x(), foundNodePos.y(), foundNodeId );
		}

		tempNode->setTargetPosition( finalPosVector );
		tempNode->setRestrictedTargetPosition( tempNode->getTargetPosition() );
		connections->setNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y(), tempNode->getId() );
	}
	desNode->setTargetPosition( desNode->getTargetPosition() - diffVector );
	desNode->setRestrictedTargetPosition( desNode->getTargetPosition() );
	if ( desNode->Data::AbsNode::getName().contains( 'x' ) ) {
//.........这里部分代码省略.........
开发者ID:kapecp,项目名称:3dsoftviz,代码行数:101,代码来源:MatrixViewer.cpp

示例12: StrokeRegion

TextRegion::TextRegion(TextRegionStyle* style)
    : StrokeRegion(style),
    _string(""),
    _text(NULL),
    _fontHeight(-1),
    _fontName(""),
    _boarderPadding(5.0f),
    _alignmentMode(NO_ALIGN_SET),
    _textColor(osg::Vec4(-0.1f,-0.1f,-0.1f,-1.0f)),
    _backdropType(NO_BACKDROP_SET),
    _backdropColor(osg::Vec4(-0.1f,-0.1f,-0.1f,-0.7f)),
    //callback events
    _onTextChangedEvent(new HudCallbackEvent(this, "OnTextChanged"))
{
	//create the text label to add to the button
	_text = new osgText::Text;
    _text->setUseDisplayList(false);
    _text->setUseVertexBufferObjects(true);
    //_text->setCharacterSizeMode(osgText::TextBase::OBJECT_COORDS_WITH_MAXIMU_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
    
	//add the text to a geode for drawing
	osg::Geode* textGeode = new osg::Geode();
    //geode is visible, not pickable
    textGeode->setNodeMask(hogbox::MAIN_CAMERA_CULL);
    MakeHudGeodes(textGeode, new RegionWrapper(this));
    osg::StateSet* stateset = textGeode->getOrCreateStateSet();
	stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
    
#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE
    if(!g_textQuadProgram.get()){
        g_textQuadProgram = new osg::Program; 
        g_textQuadProgram->setName("textShader"); 
        g_textQuadProgram->addShader(new osg::Shader(osg::Shader::VERTEX, textVertSource)); 
        g_textQuadProgram->addShader(new osg::Shader(osg::Shader::FRAGMENT, textFragSource)); 
    }
    stateset->setAttributeAndModes(g_textQuadProgram, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); 
    stateset->addUniform(new osg::Uniform("glyphTexture", 0));
#endif
    
	textGeode->setStateSet(stateset);
    textGeode->addDrawable(_text.get());
    
    _textScale = new osg::MatrixTransform();
    _textScale->addChild(textGeode);
    
	//use transform to orientate the text into correct plane and forward of the backdrop
	osg::MatrixTransform* oriText = new osg::MatrixTransform();
    
    //flip plane
    float temp = 0.0f;
    osg::Vec3 offset = osg::Vec3(0,0,0.1);
    osg::Matrix oriMatrix;
    switch(_args->_planeType){
        case hogbox::Quad::PLANE_XY:
            oriMatrix = osg::Matrix::translate(offset);
            break;
        case hogbox::Quad::PLANE_XZ:
            //flip x and z
            temp = offset.y();
            offset.y() = offset.z();
            offset.z() = temp;
            oriMatrix = osg::Matrix::translate(offset) * osg::Matrix::rotate(osg::DegreesToRadians(90.0f), osg::Vec3(1,0,0));
            break;
        default:break;
    }
    
	oriText->setMatrix(oriMatrix);
	oriText->addChild(_textScale.get());
	//attach the text to translate for now 
	_rotate->addChild(oriText);
    
    _text->setColor(osg::Vec4(0.1f,0.1f,0.1f,1.0f));
	this->SetFontType("Fonts/arial.ttf");
	this->SetFontHeight(18.0f);
	this->SetAlignment(CENTER_ALIGN);
	this->SetBackDropType(NO_BACKDROP);
	this->SetBackDropColor(osg::Vec4(0.1f,0.1f,0.1f,0.7f));
}
开发者ID:crycrane,项目名称:hogbox,代码行数:78,代码来源:TextRegion.cpp

示例13: handle

 virtual bool handle(const osgGA::GUIEventAdapter& ea,
                     osgGA::GUIActionAdapter&)
 {
    if (ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN)
    {
       if (ea.getKey() == 'm' || ea.getKey() == 'M')
       {
          switch (MouseWheelFocusPolicy)
          {
             case ManualFocusPolicy:
                eh_->setMouseWheelFocusPolicy(
                   OSGUIsh::FocusPolicyFactoryMason<OSGUIsh::MouseOverFocusPolicy>());
                MouseWheelFocusPolicy = MouseOverFocusPolicy;
                TextMouseWheelFocusPolicy->setText(
                   "Mouse wheel focus policy: mouse over sets focus");
                break;
             case MouseOverFocusPolicy:
                eh_->setMouseWheelFocusPolicy(
                   OSGUIsh::FocusPolicyFactoryMason<
                      OSGUIsh::MouseDownFocusPolicy>());
                MouseWheelFocusPolicy = MouseDownFocusPolicy;
                TextMouseWheelFocusPolicy->setText(
                   "Mouse wheel focus policy: mouse down sets focus");
                break;
             case MouseDownFocusPolicy:
                eh_->setMouseWheelFocusPolicy(
                   OSGUIsh::FocusPolicyFactoryMason<
                      OSGUIsh::ManualFocusPolicy>());
                TextMouseWheelFocusPolicy->setText(
                   std::string("Mouse wheel focus policy: manual focus ")
                   + "change (don't change focus)");
                MouseWheelFocusPolicy = ManualFocusPolicy;
                break;
          }
       }
       else if (ea.getKey() == 'k' || ea.getKey() == 'K')
       {
          switch (KeyboardFocusPolicy)
          {
             case ManualFocusPolicy:
                eh_->setKeyboardFocusPolicy(
                   OSGUIsh::FocusPolicyFactoryMason<
                      OSGUIsh::MouseOverFocusPolicy>());
                KeyboardFocusPolicy = MouseOverFocusPolicy;
                TextKeyboardFocusPolicy->setText(
                   "Keyboard focus policy: mouse over sets focus");
                break;
             case MouseOverFocusPolicy:
                eh_->setKeyboardFocusPolicy(
                   OSGUIsh::FocusPolicyFactoryMason<
                      OSGUIsh::MouseDownFocusPolicy>());
                KeyboardFocusPolicy = MouseDownFocusPolicy;
                TextKeyboardFocusPolicy->setText(
                   "Keyboard focus policy: mouse down sets focus");
                break;
             case MouseDownFocusPolicy:
                eh_->setKeyboardFocusPolicy(
                   OSGUIsh::FocusPolicyFactoryMason<
                      OSGUIsh::ManualFocusPolicy>());
                KeyboardFocusPolicy = ManualFocusPolicy;
                TextKeyboardFocusPolicy->setText(
                   std::string("Keyboard focus policy: manual focus ")
                   + "change (don't change focus)");
                break;
          }
       }
    }
    return false;
 }
开发者ID:lmbarros,项目名称:OSGUIsh,代码行数:69,代码来源:FocusPolicies.cpp

示例14: rotateImage

void SlideEventHandler::rotateImage(float rx,float ry)
{
    const float scale = 0.5f;
    _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f));
    _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f));
}
开发者ID:nsmoooose,项目名称:osg,代码行数:6,代码来源:osgstereoimage.cpp

示例15: HandleMouseEnter

void HandleMouseEnter(OSGUIsh::HandlerParams& params)
{
   TextMouseOver->setText("Mouse over " + params.node->getName());
}
开发者ID:lmbarros,项目名称:OSGUIsh,代码行数:4,代码来源:FocusPolicies.cpp


注:本文中的osg::ref_ptr类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。