Exemple #1
0
void ScribusQApp::parseCommandLine()
{
	showSplash=!neverSplashExists();
	QString arg("");
	bool usage=false;
	bool header=false;
	bool availlangs=false;
	bool version=false;
	bool runUpgradeCheck=false;
#ifdef WITH_TESTS
	bool runtests = false;
	char** testargsv;
	int testargsc;
#endif
	showFontInfo=false;
	showProfileInfo=false;	
	bool neversplash = false;

	//Parse for command line options
	// Qt5 port: do this in a Qt compatible manner
	QStringList args = arguments();
	int argsc = args.count();

	//Init translations
	initLang();
	
	useGUI = true;
	int argi = 1;
	for( ; argi < argsc; argi++) { //handle options (not positional parameters)
		arg = args[argi];

		if (arg == ARG_SCRIPTARG || arg == ARG_SCRIPTARG_SHORT) { //needs to be first to give precedence to script argument name over scribus' options
			if (++argi < argsc && (args[argi] != CMD_OPTIONS_END)) {
				pythonScriptArgs.append(args[argi]); // script argument
			} else {
				std::cout << tr("Invalid argument use: '%1' requires to be followed by <argument> [value]").arg(arg).toLocal8Bit().data() << std::endl;
				showUsage();
				std::exit(EXIT_FAILURE);
			}
			if (++argi < argsc && !args[argi].startsWith("-")) {   // arg value
				pythonScriptArgs.append( QFile::decodeName(args[argi].toLocal8Bit()) );
			}
		}
		else if ((arg == ARG_LANG || arg == ARG_LANG_SHORT) && (++argi < argsc)) {
			lang = args[argi];
		}
		else if (arg == ARG_VERSION || arg == ARG_VERSION_SHORT) {
			header=true;
			version=true;
		} else if (arg == ARG_HELP || arg == ARG_HELP_SHORT) {
			header=true;
			usage=true;
		}
#ifdef WITH_TESTS
		else if (arg == ARG_TESTS || arg == ARG_TESTS_SHORT) {
			header=true;
			runtests=true;
			testargsc = argc() - argi;
			testargsv = argv() + argi;
			break;
		}
#endif
		else if (arg == ARG_AVAILLANG || arg == ARG_AVAILLANG_SHORT) {
			header=true;
			availlangs=true;
		} else if (arg == ARG_UPGRADECHECK || arg == ARG_UPGRADECHECK_SHORT) {
			header=true;
			runUpgradeCheck=true;
		}
		else if ((arg == ARG_LANG || arg == ARG_LANG_SHORT) && (++argi < argsc)) {
			continue;
		} 
		else if ( arg == ARG_CONSOLE || arg == ARG_CONSOLE_SHORT ) {
			continue;
		} else if (arg == ARG_NOSPLASH || arg == ARG_NOSPLASH_SHORT) {
			showSplash = false;
		}
		else if (arg == ARG_NEVERSPLASH || arg == ARG_NEVERSPLASH_SHORT) {
			showSplash = false;
			neversplash = true;
		} else if (arg == ARG_NOGUI || arg == ARG_NOGUI_SHORT) {
			useGUI=false;
		} else if (arg == ARG_FONTINFO || arg == ARG_FONTINFO_SHORT) {
			showFontInfo=true;
		} else if (arg == ARG_PROFILEINFO || arg == ARG_PROFILEINFO_SHORT) {
			showProfileInfo=true;
		} else if ((arg == ARG_DISPLAY || arg==ARG_DISPLAY_SHORT || arg==ARG_DISPLAY_QT) && ++argi < argsc) {
			// allow setting of display, QT expect the option -display <display_name> so we discard the
			// last argument. FIXME: Qt only understands -display not --display and -d , we need to work
			// around this.
		} else if (arg == ARG_PREFS || arg == ARG_PREFS_SHORT) {
			prefsUserFile = QFile::decodeName(args[argi + 1].toLocal8Bit());
			if (!QFileInfo(prefsUserFile).exists()) {
				showError(prefsUserFile);
				std::exit(EXIT_FAILURE);
			} else {
				++argi;
			}
		} else if (strncmp(arg.toLocal8Bit().data(),"-psn_",4) == 0)
		{
			// Andreas Vox: Qt/Mac has -psn_blah flags that must be accepted.
		} else if (arg == ARG_PYTHONSCRIPT || arg == ARG_PYTHONSCRIPT_SHORT) {
			pythonScript = QFile::decodeName(args[argi + 1].toLocal8Bit());
			if (!QFileInfo(pythonScript).exists()) {
				showError(pythonScript);
				std::exit(EXIT_FAILURE);
			} else {
				++argi;
			}
		} else if (arg == CMD_OPTIONS_END) { //double dash, indicates end of command line options, see http://unix.stackexchange.com/questions/11376/what-does-double-dash-mean-also-known-as-bare-double-dash
			argi++;
			break;
		} else { //argument is not a known option, but either positional parameter or invalid.
			break;
		}
	}
	// parse for remaining (positional) arguments, if any
	for ( ; argi<argsc; argi++) {
		fileName = QFile::decodeName(args[argi].toLocal8Bit());
		if (!QFileInfo(fileName).exists()) {
			showError(fileName);
			std::exit(EXIT_FAILURE);
		} else {
			filesToLoad.append(fileName);
		}
	}

	
	//Show command line info
	if (header) {
		useGUI = false;
		showHeader();
	}
	if (version)
		showVersion();
	if (availlangs)
		showAvailLangs();
	if (usage)
		showUsage();
#ifdef WITH_TESTS
	if (runtests)
		RunTests::runTests(testargsc, testargsv);
#endif
	if (runUpgradeCheck)
	{
		UpgradeChecker uc;
		uc.fetch();
	}
	//Dont run the GUI init process called from main.cpp, and return
	if (header) {		
		std::exit(EXIT_SUCCESS);
	}
	//proceed
	if(neversplash) {
		neverSplash(true);
	}
	
}
Exemple #2
0
int main( int argc, char *argv[] )
{
	static int  nlen[M];	
	static char name[M][B], **seq;
	static char **mseq1, **mseq2;
	static char **aseq;
	static char **bseq;
	static double *eff;
	static double *equiv;
	char **strfiles;
	char **chainids;
	int i;
	FILE *infp;
	char c;
	int alloclen;

	arguments( argc, argv );

	if( equivthreshold < 1 || 9 < equivthreshold )
	{
		fprintf( stderr, "-t n, n must be 1..9\n" );
		exit( 1 );
	}

	if( ( equivwinsize + 1 ) % 2 != 0 )
	{
		fprintf( stderr, "equivwinsize = %d\n", equivwinsize );
		fprintf( stderr, "It must be an odd number.\n" );
		exit( 1 );
	}

	if( inputfile )
	{
		infp = fopen( inputfile, "r" );
		if( !infp )
		{
			fprintf( stderr, "Cannot open %s\n", inputfile );
			exit( 1 );
		}
	}
	else
		infp = stdin;

	nlenmax = 10000; // tekitou

	if( alg == 'R' )
		prepareash( infp, &strfiles, &chainids, &seq, &mseq1, &mseq2, &equiv, &alloclen );
	else if( alg == 'T' )
		preparetmalign( infp, &strfiles, &chainids, &seq, &mseq1, &mseq2, &equiv, &alloclen );

	fclose( infp );

	aseq = AllocateCharMtx( njob, nlenmax*2+1 );
	bseq = AllocateCharMtx( njob, nlenmax*2+1 );
	eff = AllocateDoubleVec( njob );

	for( i=0; i<njob; i++ )
	{
		fprintf( stderr, "str%d = %s-%s\n", i, strfiles[i], chainids[i] );
	}

	if( njob < 1 )
	{
		fprintf( stderr, "No structure found.\n" ); 
		exit( 1 );
	}
	if( njob < 2 )
	{
		fprintf( stderr, "Only %d structure found.\n", njob ); 
		exit( 0 );
	}
	if( njob > M )
	{
		fprintf( stderr, "The number of structures must be < %d\n", M );
		fprintf( stderr, "Please try sequence-based methods for such large data.\n" );
		exit( 1 );
	}



#if 0
	readData( infp, name, nlen, seq );
#endif

	constants( njob, seq );

#if 0
	fprintf( stderr, "params = %d, %d, %d\n", penalty, penalty_ex, offset );
#endif

	initSignalSM();

	initFiles();

	WriteOptions( trap_g );

	c = seqcheck( seq );
	if( c )
	{
		fprintf( stderr, "Illegal character %c\n", c );
		exit( 1 );
	}

//	writePre( njob, name, nlen, seq, 0 );

	for( i=0; i<njob; i++ ) eff[i] = 1.0;


	for( i=0; i<njob; i++ ) gappick0( bseq[i], seq[i] );

	pairalign( name, nlen, bseq, aseq, mseq1, mseq2, equiv, eff, strfiles, chainids, alloclen );

	fprintf( trap_g, "done.\n" );
#if DEBUG
	fprintf( stderr, "closing trap_g\n" );
#endif
	fclose( trap_g );

//	writePre( njob, name, nlen, aseq, !contin );
#if 0
	writeData( stdout, njob, name, nlen, aseq );
#endif
#if IODEBUG
	fprintf( stderr, "OSHIMAI\n" );
#endif
	SHOWVERSION;
	return( 0 );
}
Exemple #3
0
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()->setDescription(arguments.getApplicationName()+" is the example which demonstrates how to approach implementation of clustering.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-m","Set viewer to MASTER mode, sending view via packets.");
    arguments.getApplicationUsage()->addCommandLineOption("-s","Set viewer to SLAVE mode, receiving view via packets.");
    arguments.getApplicationUsage()->addCommandLineOption("-n <int>","Socket number to transmit packets");
    arguments.getApplicationUsage()->addCommandLineOption("-f <float>","Field of view of camera");
    arguments.getApplicationUsage()->addCommandLineOption("-o <float>","Offset angle of camera");

    // construct the viewer.
    osgViewer::Viewer viewer;


    // read up the osgcluster specific arguments.
    ViewerMode viewerMode = STAND_ALONE;
    while (arguments.read("-m")) viewerMode = MASTER;
    while (arguments.read("-s")) viewerMode = SLAVE;

    int socketNumber=8100;
    while (arguments.read("-n",socketNumber)) ;

    float camera_fov=-1.0f;
    while (arguments.read("-f",camera_fov))
    {
    }

    float camera_offset=45.0f;
    while (arguments.read("-o",camera_offset)) ;


    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

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

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

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // load model.
    osg::ref_ptr<osg::Node> rootnode = osgDB::readRefNodeFiles(arguments);

    // set the scene to render
    viewer.setSceneData(rootnode.get());

    if (camera_fov>0.0f)
    {
        double fovy, aspectRatio, zNear, zFar;
        viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio,zNear, zFar);

        double original_fov = atan(tan(osg::DegreesToRadians(fovy)*0.5)*aspectRatio)*2.0;
        std::cout << "setting lens perspective : original "<<original_fov<<"  "<<fovy<<std::endl;

        fovy = atan(tan(osg::DegreesToRadians(camera_fov)*0.5)/aspectRatio)*2.0;
        viewer.getCamera()->setProjectionMatrixAsPerspective(fovy, aspectRatio,zNear, zFar);

        viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio,zNear, zFar);
        original_fov = atan(tan(osg::DegreesToRadians(fovy)*0.5)*aspectRatio)*2.0;
        std::cout << "setting lens perspective : new "<<original_fov<<"  "<<fovy<<std::endl;
    }

    viewer.setCameraManipulator(new osgGA::TrackballManipulator());

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );


    // create the windows and run the threads.
    viewer.realize();


    CameraPacket *cp = new CameraPacket;

    // objects for managing the broadcasting and recieving of camera packets.
    Broadcaster     bc;
    Receiver        rc;

    bc.setPort(static_cast<short int>(socketNumber));
    rc.setPort(static_cast<short int>(socketNumber));

    bool masterKilled = false;

    DataConverter scratchPad(1024);

    while( !viewer.done() && !masterKilled )
    {
        osg::Timer_t startTick = osg::Timer::instance()->tick();

        viewer.advance();

        // special handling for working as a cluster.
        switch (viewerMode)
        {
        case(MASTER):
            {

                // take camera zero as the guide.
                osg::Matrix modelview(viewer.getCamera()->getViewMatrix());

                cp->setPacket(modelview,viewer.getFrameStamp());

                cp->readEventQueue(viewer);

                scratchPad.reset();
                scratchPad.write(*cp);

                scratchPad.reset();
                scratchPad.read(*cp);

                bc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);

                std::cout << "bc.sync()"<<scratchPad._numBytes<<std::endl;

                bc.sync();

            }
            break;
        case(SLAVE):
            {

                rc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);

                rc.sync();

                scratchPad.reset();
                scratchPad.read(*cp);

                cp->writeEventQueue(viewer);

                if (cp->getMasterKilled())
                {
                    std::cout << "Received master killed."<<std::endl;
                    // break out of while (!done) loop since we've now want to shut down.
                    masterKilled = true;
                }
            }
            break;
        default:
            // no need to anything here, just a normal interactive viewer.
            break;
        }

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

        osg::notify(osg::INFO)<<"Time to do cluster sync "<<osg::Timer::instance()->delta_m(startTick,endTick)<<std::endl;

        // update the scene by traversing it with the update visitor which will
        // call all node update callbacks and animations.
        viewer.eventTraversal();
        viewer.updateTraversal();

        if (viewerMode==SLAVE)
        {
            osg::Matrix modelview;
            cp->getModelView(modelview,camera_offset);

            viewer.getCamera()->setViewMatrix(modelview);
        }

        // fire off the cull and draw traversals of the scene.
        if(!masterKilled)
            viewer.renderingTraversals();

    }

    // if we are master clean up by telling all slaves that we're going down.
    if (viewerMode==MASTER)
    {
        // need to broadcast my death.
        cp->setPacket(osg::Matrix::identity(),viewer.getFrameStamp());
        cp->setMasterKilled(true);

        scratchPad.reset();
        scratchPad.write(*cp);

        bc.setBuffer(scratchPad._startPtr, scratchPad._numBytes);
        bc.sync();

        std::cout << "Broadcasting death."<<std::endl;

    }

    return 0;
}
Exemple #4
0
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()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use node masks to create stereo images.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time delay in seconds between the display of successive image pairs when in auto advance mode.");
    arguments.getApplicationUsage()->addCommandLineOption("-a","Enter auto advance of image pairs on start up.");
    arguments.getApplicationUsage()->addCommandLineOption("-x <float>","Horizontal offset of left and right images.");
    arguments.getApplicationUsage()->addCommandLineOption("-y <float>","Vertical offset of left and right images.");
    arguments.getApplicationUsage()->addCommandLineOption("--disk","Keep images on disk");
    arguments.getApplicationUsage()->addCommandLineOption("-files <filename>","Load filenames from a file");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--SingleThreaded","Select SingleThreaded threading model for viewer.");
    arguments.getApplicationUsage()->addCommandLineOption("--CullDrawThreadPerContext","Select CullDrawThreadPerContext threading model for viewer.");
    arguments.getApplicationUsage()->addCommandLineOption("--DrawThreadPerContext","Select DrawThreadPerContext threading model for viewer.");
    arguments.getApplicationUsage()->addCommandLineOption("--CullThreadPerCameraDrawThreadPerContext","Select CullThreadPerCameraDrawThreadPerContext threading model for viewer.");
    

    // construct the viewer.
    osgViewer::Viewer viewer;

    // register the handler to add keyboard and mouse handling.
    SlideEventHandler* seh = new SlideEventHandler();
    viewer.addEventHandler(seh);

    // read any time delay argument.
    float timeDelayBetweenSlides = 5.0f;
    while (arguments.read("-d",timeDelayBetweenSlides)) {}

    bool autoSteppingActive = false;
    while (arguments.read("-a")) autoSteppingActive = true;

    float offsetX=0.0f;
    while (arguments.read("-x",offsetX)) {}

    float offsetY=0.0f;
    while (arguments.read("-y",offsetY)) {}

    bool onDisk=false;
    while (arguments.read("--disk")) { onDisk=true;}

    std::string filename="";
    FileList fileList;
    // extract the filenames from the a file, one filename per line.
    while (arguments.read("-files",filename)) {
        std::ifstream is(filename.c_str());
        if (is) {
                std::string line;
                while (std::getline(is,line,'\n')) fileList.push_back(line);
                is.close();
            }
    
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    osgViewer::Viewer::ThreadingModel threading = osgViewer::Viewer::SingleThreaded;
    while (arguments.read("--SingleThreaded")) threading = osgViewer::Viewer::SingleThreaded;
    while (arguments.read("--CullDrawThreadPerContext")) threading = osgViewer::Viewer::CullDrawThreadPerContext;
    while (arguments.read("--DrawThreadPerContext")) threading = osgViewer::Viewer::DrawThreadPerContext;
    while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) threading = osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext;

    viewer.setThreadingModel(threading);

    // 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);
        return 1;
    }
    
    // extract the filenames from the arguments list.
    for(int pos=1;pos<arguments.argc();++pos)
    {
        if (arguments.isString(pos)) fileList.push_back(arguments[pos]);
    }

    if (fileList.empty())
    {
        fileList.push_back("Images/dog_left_eye.jpg");
         fileList.push_back("Images/dog_right_eye.jpg");
    }
    else if (fileList.size()<2)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // now the windows have been realized we switch off the cursor to prevent it
    // distracting the people seeing the stereo images.
    double fovy, aspectRatio, zNear, zFar;
    viewer.getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);

    float radius = 1.0f;
    float height = 2*radius*tan(osg::DegreesToRadians(fovy)*0.5f);
    float length = osg::PI*radius;  // half a cylinder.

    // use a texture matrix to control the placement of the image.
    osg::TexMat* texmatLeft = new osg::TexMat;
    osg::TexMat* texmatRight = new osg::TexMat;

    // creat the scene from the file list.
    osg::ref_ptr<osg::Switch> rootNode;
    if (!onDisk)  rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length);
    else rootNode=new osg::Switch();

    //osgDB::writeNodeFile(*rootNode,"test.osg");


    viewer.getCamera()->setCullMask(0xffffffff);
    viewer.getCamera()->setCullMaskLeft(0x00000001);
    viewer.getCamera()->setCullMaskRight(0x00000002);

    // set up the use of stereo by default.
    osg::DisplaySettings::instance()->setStereo(true);

    // set the scene to render
    viewer.setSceneData(rootNode.get());


    // create the windows and run the threads.
    viewer.realize();


    // switch off the cursor
    osgViewer::Viewer::Windows windows;
    viewer.getWindows(windows);
    for(osgViewer::Viewer::Windows::iterator itr = windows.begin();
        itr != windows.end();
        ++itr)
    {
        (*itr)->useCursor(false);
    }

    viewer.setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius);

    // set up the SlideEventHandler.
    if (onDisk) seh->set(fileList,rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,radius,height,length,timeDelayBetweenSlides,autoSteppingActive);
    else seh->set(rootNode.get(),offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive);
    
    osg::Matrix homePosition;
    homePosition.makeLookAt(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(0.0f,1.0f,0.0f),osg::Vec3(0.0f,0.0f,1.0f));
        
    while( !viewer.done() )
    {
        viewer.getCamera()->setViewMatrix(homePosition);

        // fire off the cull and draw traversals of the scene.
        viewer.frame();
        
    }
    
    return 0;
}
bool Application::initialize( int argc, char **argv )
{
    // this is used when hunting for memory leaks
#ifdef YAF3D_ENABLE_HEAPCHECK
    // trigger debugger
    //__asm int 3;
#endif

    std::string arg_levelname;
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments( &argc,argv );
    osg::ArgumentParser::Parameter levelparam( arg_levelname );
    arguments.read( "-level", arg_levelname ); // read the level file if one given

    int   argpos;
    // set proper game mode
    GameState::get()->setMode( GameState::Standalone );
    if ( ( argpos = arguments.find( "-server" ) ) != 0 )
    {
        GameState::get()->setMode( GameState::Server );
        arguments.remove( argpos );
    }
    else if ( ( argpos = arguments.find( "-client" ) ) != 0 )
    {
        GameState::get()->setMode( GameState::Client );
        arguments.remove( argpos );
    }

    // note: before beginning to initialize the framework modules the media path must be set,
    //  other modules need it for loading resources etc.
    //-------------------
    std::vector< std::string > path;
    std::string dir;
    {
        char* p_env = getenv( YAF3D_ENV_MEDIA_DIR );
        if ( p_env )
        {
            _mediaPath = p_env;
        }
        else
        {
            dir = getCurrentWorkingDirectory();
            dir = cleanPath( dir );
            dir += "/";
            path.clear();
            explode( dir, "/", &path );
#ifdef LINUX
            dir = "/";
#endif
#ifdef WIN32
            dir = "";
#endif
            for ( size_t cnt = 0; cnt < path.size() - 2; ++cnt )
                dir += path[ cnt ] + "/";

            dir.erase( dir.size() -1 );
            _mediaPath = dir;
            _mediaPath += YAF3D_MEDIA_PATH;
        }
    }

    //-------------------
    // set the ful binary path of application
    _fulBinaryPath = arguments.getApplicationName();
    _fulBinaryPath = cleanPath( _fulBinaryPath );
    _fulBinaryPath = _fulBinaryPath.substr( 0, _fulBinaryPath.rfind( '/' ) );
    //-------------------

    // load the standard configuration before changing to 'Initializing' state
    Configuration::get()->load();

    // set game state
    _p_gameState->setState( GameState::Initializing );

    // setup log system
    {
        std::string loglevel;
        Log::Level  level = Log::L_ERROR;

        // get the log level from configuration
        Configuration::get()->getSettingValue( YAF3D_GS_LOG_LEVEL, loglevel );

        // check if we have to report an invalid log level in configuration
        if ( loglevel == "error" )
            level = Log::L_ERROR;
        else if ( loglevel == "warning" )
            level = Log::L_WARNING;
        else if ( loglevel == "debug" )
            level = Log::L_DEBUG;
        else if ( loglevel == "info" )
            level = Log::L_INFO;
        else if ( loglevel == "verbose" )
            level = Log::L_VERBOSE;
        else
            log_warning << "Application: configuration contains an invalid log level, possible values are: error, warning, debug, info, verbose. set to error." << std::endl;

        // create log sinks with configured log level
        if ( GameState::get()->getMode() != GameState::Server )
            log.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME ), level );
        else
            log.addSink( "file", getMediaPath() + std::string( LOG_FILE_NAME_SERVER ), level );

        // only the server needs an console stdout
#ifdef YAF3D_HAS_CONSOLE
        log.addSink( "stdout", std::cout, level );
#endif

    }

    log.enableSeverityLevelPrinting( false );
    log_info << std::endl;
    log << " *******************************************"    << std::endl;
    log << " * yaf3d -- Yet another Framework 3D       *"    << std::endl;
    log << " * version: " << std::string( YAF3D_VERSION ) << "                          *"  << std::endl;
    log << " * project: Yag2002                        *"    << std::endl;
    log << " * site:    http://yag2002.sourceforge.net *"    << std::endl;
    log << " * contact: [email protected]               *"    << std::endl;
    log << " *******************************************"    << std::endl;
    log << "" << std::endl;
    log.enableSeverityLevelPrinting( true );

    log << "Application: time " << yaf3d::getTimeStamp();

    // print cpu info
    {
        std::stringstream cpuinfo;
        cpuinfo << "Application: CPU supports ";
        if ( SDL_HasRDTSC() )
            cpuinfo << "RDTSC ";
        if ( SDL_HasMMX() )
            cpuinfo << "MMX ";
        if ( SDL_HasMMXExt() )
            cpuinfo << "MMXExt ";
        if ( SDL_Has3DNow() )
            cpuinfo << "3DNow ";
        if ( SDL_Has3DNowExt() )
            cpuinfo << "3DNowExt ";
        if ( SDL_HasSSE() )
            cpuinfo << "SSE ";
        if ( SDL_HasSSE2() )
            cpuinfo << "SSE2 ";
        if ( SDL_HasAltiVec() )
            cpuinfo << "AltiVec ";

        log << cpuinfo.str() << std::endl;
    }

    log << "Application: initializing viewer" << std::endl;
    log << "Application: using media path: " << _mediaPath << std::endl;

    // setup the viewer
    //----------

    // load the display settings
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENWIDTH,  _screenWidth  );
    Configuration::get()->getSettingValue( YAF3D_GS_SCREENHEIGHT, _screenHeight );
    Configuration::get()->getSettingValue( YAF3D_GS_FULLSCREEN,   _fullScreen   );
    unsigned int colorBits = 24;
    Configuration::get()->getSettingValue( YAF3D_GS_COLORBITS, colorBits );

    // set the icon and caption title only for non-servers
    if ( GameState::get()->getMode() != GameState::Server )
    {
       // init SDL with video
        SDL_Init( SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE );

        // set application window's title
        _appWindowTitle = YAF3D_APP_TITLE " " YAF3D_VERSION;
        setWindowTitle( _appWindowTitle );

        SDL_Surface* p_bmpsurface = SDL_LoadBMP( YAF3D_APP_ICON );
        if ( p_bmpsurface )
        {
            Uint32 col = SDL_MapRGB( p_bmpsurface->format, 255, 255, 255 );
            SDL_SetColorKey( p_bmpsurface, SDL_SRCCOLORKEY, col );
            SDL_WM_SetIcon( p_bmpsurface, NULL );
        }
    }
    else
    {
        // init SDl witout video for server
        SDL_Init( SDL_INIT_NOPARACHUTE );
    }
    // enable unicode translation
    SDL_EnableUNICODE( 1 );
    SDL_EnableKeyRepeat( SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL ); // enable key repeating

    _p_viewer = new osgSDL::Viewer;
    _rootSceneNode = new osg::Group;
    _rootSceneNode->setName( "_topSceneGroup_" );
    osgSDL::Viewport*   p_viewport = new osgSDL::Viewport( _rootSceneNode.get() );
    osgUtil::SceneView* p_sceneView = p_viewport->getSceneView();
    p_sceneView->setDefaults( osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT );
    _p_viewer->addViewport( p_viewport );
    _p_viewer->requestContinuousUpdate( true ); // force event generation for FRAMEs, we need this for animations, etc.

    int flags = SDL_HWSURFACE;
    if ( _fullScreen )
        flags |= SDL_FULLSCREEN;

    _p_viewer->setDisplayMode( _screenWidth, _screenHeight, colorBits, flags );
    _p_viewer->setCursorEnabled( false );
    //------------

    // setup keyboard map
    std::string keybType;
    Configuration::get()->getSettingValue( YAF3D_GS_KEYBOARD, keybType );
    log_info << "Application: setup keyboard map to: " << keybType << std::endl;
    if ( keybType == YAF3D_GS_KEYBOARD_ENGLISH )
        KeyMap::get()->setup( KeyMap::English );
    else
        KeyMap::get()->setup( KeyMap::German );

    // get the instance of gui manager
    _p_guiManager = GuiManager::get();
    // setup networking
    _p_networkDevice = NetworkDevice::get();
    // avoid creating of remote clients so long we are initializing the system
    _p_networkDevice->lockObjects();
    if ( GameState::get()->getMode() == GameState::Server )
    {
        log_info << "Application: loading level file '" << arg_levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( YAF3D_LEVEL_SERVER_DIR + arg_levelname );
        if ( !sceneroot.valid() )
            return false;

        // start networking before setting up entities
        std::string servername;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_NAME, servername );
        NodeInfo nodeinfo( arg_levelname, servername );
        unsigned int channel = 0;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup server
        try
        {
            _p_networkDevice->setupServer( channel, nodeinfo );
        }
        catch ( const NetworkException& e )
        {
            log_error << "Application: error starting server, reason: " << e.what() << std::endl;
            return false;
        }

        // complete level loading
        LevelManager::get()->finalizeLoading();

        // the server needs no drawing
        _p_viewer->setUpdateAllViewports( false );
    }
    else if ( GameState::get()->getMode() == GameState::Client )
    {
        std::string url;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_IP, url );
        std::string clientname( "vrc-client" );
        NodeInfo nodeinfo( "", clientname );
        unsigned int channel = 0;
        Configuration::get()->getSettingValue( YAF3D_GS_SERVER_PORT, channel );

        // try to setup client networking
        try
        {
            _p_networkDevice->setupClient( url, channel, nodeinfo );
        }
        catch ( const NetworkException& e )
        {
            log_error << "Application: error setting up client networking, reason: " << e.what() << std::endl;
            return false;
        }

        // now load level
        std::string levelname = YAF3D_LEVEL_CLIENT_DIR + _p_networkDevice->getNodeInfo()->getLevelName();
        log_info << "Application: loading level file '" << levelname << "'" << std::endl;
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( levelname );
        if ( !sceneroot.valid() )
            return false;
        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a client with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
        EntityManager::get()->sendNotification( notification );
    }
    else // check for any level file name, so we try to start in Standalone mode
    {
        std::string defaultlevel = arg_levelname.length() ? ( std::string( YAF3D_LEVEL_SALONE_DIR ) + arg_levelname ) : std::string( YAF3D_DEFAULT_LEVEL );
        log_info << "Application: loading level file '" << defaultlevel << "'" << std::endl;
        // set game mode
        GameState::get()->setMode( GameState::Standalone );
        // load the level and setup things
        osg::ref_ptr< osg::Group > sceneroot = LevelManager::get()->loadLevel( defaultlevel );
        if ( !sceneroot.valid() )
            return false;
        // complete level loading
        LevelManager::get()->finalizeLoading();

        // if we directly start a level with cmd line option then we must send a leave-menu notification to entities
        //  as many entities do special steps when leaving the menu
        if ( arg_levelname.length() )
        {
            EntityNotification notification( YAF3D_NOTIFY_MENU_LEAVE );
            EntityManager::get()->sendNotification( notification );
        }
    }

    return true;
}
Exemple #6
0
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()->setDescription(arguments.getApplicationName()+" is a utility for converting between various input and output databases formats.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
    //arguments.getApplicationUsage()->addCommandLineOption("--formats","List supported file formats");
    //arguments.getApplicationUsage()->addCommandLineOption("--plugins","List database olugins");


    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        osg::setNotifyLevel(osg::NOTICE);
        usage( arguments.getApplicationName().c_str(), 0 );
        //arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    if (arguments.read("--help-env"))
    {
        arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE);
        return 1;
    }

    if (arguments.read("--plugins"))
    {
        osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins();
        for(osgDB::FileNameList::iterator itr = plugins.begin();
            itr != plugins.end();
            ++itr)
        {
            std::cout<<"Plugin "<<*itr<<std::endl;
        }
        return 0;
    }

    std::string plugin;
    if (arguments.read("--plugin", plugin))
    {
        osgDB::outputPluginDetails(std::cout, plugin);
        return 0;
    }

    std::string ext;
    if (arguments.read("--format", ext))
    {
        plugin = osgDB::Registry::instance()->createLibraryNameForExtension(ext);
        osgDB::outputPluginDetails(std::cout, plugin);
        return 0;
    }

    if (arguments.read("--formats"))
    {
        osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins();
        for(osgDB::FileNameList::iterator itr = plugins.begin();
            itr != plugins.end();
            ++itr)
        {
            osgDB::outputPluginDetails(std::cout,*itr);
        }
        return 0;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    FileNameList fileNames;
    OrientationConverter oc;
    bool do_convert = false;

    if (arguments.read("--use-world-frame"))
    {
        oc.useWorldFrame(true);
    }

    std::string str;
    while (arguments.read("-O",str))
    {
        osgDB::ReaderWriter::Options* options = new osgDB::ReaderWriter::Options;
        options->setOptionString(str);
        osgDB::Registry::instance()->setOptions(options);
    }

    while (arguments.read("-e",ext))
    {
        std::string libName = osgDB::Registry::instance()->createLibraryNameForExtension(ext);
        osgDB::Registry::instance()->loadLibrary(libName);
    }

    std::string libName;
    while (arguments.read("-l",libName))
    {
        osgDB::Registry::instance()->loadLibrary(libName);
    }

    while (arguments.read("-o",str))
    {
        osg::Vec3 from, to;
        if( sscanf( str.c_str(), "%f,%f,%f-%f,%f,%f",
                &from[0], &from[1], &from[2],
                &to[0], &to[1], &to[2]  )
            != 6 )
        {
            float degrees;
            osg::Vec3 axis;
            // Try deg-axis format
            if( sscanf( str.c_str(), "%f-%f,%f,%f",
                    &degrees, &axis[0], &axis[1], &axis[2]  ) != 4 )
            {
                usage( argv[0], "Orientation argument format incorrect." );
                return 1;
            }
            else
            {
                oc.setRotation( degrees, axis );
                do_convert = true;
            }
        }
        else
        {
            oc.setRotation( from, to );
            do_convert = true;
        }
    }

    while (arguments.read("-s",str))
    {
        osg::Vec3 scale(0,0,0);
        if( sscanf( str.c_str(), "%f,%f,%f",
                &scale[0], &scale[1], &scale[2] ) != 3 )
        {
            usage( argv[0], "Scale argument format incorrect." );
            return 1;
        }
        oc.setScale( scale );
        do_convert = true;
    }

    float simplifyPercent = 1.0;
    bool do_simplify = false;
    while ( arguments.read( "--simplify",str ) )
    {
        float nsimp = 1.0;
        if( sscanf( str.c_str(), "%f",
                &nsimp ) != 1 )
        {
            usage( argv[0], "Scale argument format incorrect." );
            return 1;
        }
        std::cout << str << " " << nsimp << std::endl;
        simplifyPercent = nsimp;
        osg::notify( osg::INFO ) << "Simplifying with percentage: " << simplifyPercent << std::endl;
        do_simplify = true;
    }

    while (arguments.read("-t",str))
    {
        osg::Vec3 trans(0,0,0);
        if( sscanf( str.c_str(), "%f,%f,%f",
                &trans[0], &trans[1], &trans[2] ) != 3 )
        {
            usage( argv[0], "Translation argument format incorrect." );
            return 1;
        }
        oc.setTranslation( trans );
        do_convert = true;
    }


    FixTransparencyVisitor::FixTransparencyMode fixTransparencyMode = FixTransparencyVisitor::NO_TRANSPARANCY_FIXING;
    std::string fixString;
    while(arguments.read("--fix-transparency")) fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE;
    while(arguments.read("--fix-transparency-mode",fixString))
    {
         if (fixString=="MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE;
         if (fixString=="MAKE_ALL_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_ALL_STATESET_OPAQUE;
    };

    bool pruneStateSet = false;
    while(arguments.read("--prune-StateSet")) pruneStateSet = true;

    osg::Texture::InternalFormatMode internalFormatMode = osg::Texture::USE_IMAGE_DATA_FORMAT;
    while(arguments.read("--compressed") || arguments.read("--compressed-arb")) { internalFormatMode = osg::Texture::USE_ARB_COMPRESSION; }

    while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; }
    while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; }
    while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; }

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

    bool addMissingColours = false;
    while(arguments.read("--addMissingColours") || arguments.read("--addMissingColors")) { addMissingColours = true; }

    bool do_overallNormal = false;
    while(arguments.read("--overallNormal") || arguments.read("--overallNormal")) { do_overallNormal = true; }

    bool enableObjectCache = false;
    while(arguments.read("--enable-object-cache")) { enableObjectCache = true; }

    // 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);
        return 1;
    }

    for(int pos=1;pos<arguments.argc();++pos)
    {
        if (!arguments.isOption(pos))
        {
            fileNames.push_back(arguments[pos]);
        }
    }

    if (enableObjectCache)
    {
        if (osgDB::Registry::instance()->getOptions()==0) osgDB::Registry::instance()->setOptions(new osgDB::Options());
        osgDB::Registry::instance()->getOptions()->setObjectCacheHint(osgDB::Options::CACHE_ALL);
    }

    std::string fileNameOut("converted.osg");
    if (fileNames.size()>1)
    {
        fileNameOut = fileNames.back();
        fileNames.pop_back();
    }

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

    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(fileNames);

    if (root.valid())
    {
        osg::Timer_t endTick = osg::Timer::instance()->tick();
        osg::notify(osg::INFO)<<"Time to load files "<<osg::Timer::instance()->delta_m(startTick, endTick)<<" ms"<<std::endl;
    }


    if (pruneStateSet)
    {
        PruneStateSetVisitor pssv;
        root->accept(pssv);
    }

    if (fixTransparencyMode != FixTransparencyVisitor::NO_TRANSPARANCY_FIXING)
    {
        FixTransparencyVisitor atv(fixTransparencyMode);
        root->accept(atv);
    }

    if ( root.valid() )
    {

        if (smooth)
        {
            osgUtil::SmoothingVisitor sv;
            root->accept(sv);
        }

        if (addMissingColours)
        {
            AddMissingColoursToGeometryVisitor av;
            root->accept(av);
        }
 		
        auto to_lower = std::bind(&boost::to_lower_copy<std::string>,std::placeholders::_1,std::locale());

        // all names to lower
        Utils::CommonVisitor<osg::Node> names_lower(
            [=](osg::Node& n)->void {
                n.setName(to_lower(n.getName()));
        }); 

        root->accept(names_lower);

        // optimize the scene graph, remove rendundent nodes and state etc.
        osgUtil::Optimizer optimizer;

        FindNodeVisitor::nodeNamesList list_name;
        
        for(int i=0; i<sizeof(do_not_optimize::names)/sizeof(do_not_optimize::names[0]);++i)
        {
            list_name.push_back(do_not_optimize::names[i]);
        }
        

        FindNodeVisitor findNodes(list_name,FindNodeVisitor::not_exact); 
        root->accept(findNodes);

        const FindNodeVisitor::nodeListType& wln_list = findNodes.getNodeList();

        for(auto it = wln_list.begin(); it != wln_list.end(); ++it )
        {
            optimizer.setPermissibleOptimizationsForObject(*it,0);
        }

        optimizer.optimize(root.get(), 
            osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS |
            osgUtil::Optimizer::REMOVE_REDUNDANT_NODES |
            osgUtil::Optimizer::SHARE_DUPLICATE_STATE |
            osgUtil::Optimizer::MERGE_GEOMETRY |
            osgUtil::Optimizer::MERGE_GEODES |
            osgUtil::Optimizer::STATIC_OBJECT_DETECTION );

        boost::filesystem::path pathFileOut(fileNameOut); 
        std::string base_file_name = pathFileOut.parent_path().string() + "/" + pathFileOut.stem().string();

        cg::point_3 offset;

        bool res = generateBulletFile(base_file_name + ".bullet", root, offset);

        if (res)
        {
            osg::notify(osg::NOTICE)<<"Data written to '"<< base_file_name + ".bullet"<<"'."<< std::endl;
        }
        else
        {
            osg::notify(osg::NOTICE)<< "Error Occurred While Writing to "<< base_file_name + ".bullet"<< std::endl;
        }
        
        osg::Group* newroot =  dynamic_cast<osg::Group*>(findFirstNode(root,"Root")); 
        if(newroot==nullptr)
        {
            newroot = new osg::Group; 
            newroot->setName("Root");
            newroot->addChild( root ); 
            root = newroot;
        }

        std::ofstream filelogic( base_file_name + ".stbin", std::ios_base::binary );
        std::ofstream logfile  ( base_file_name + std::string("_structure") + ".txt" );

        heilVisitor  hv(filelogic, logfile, offset);
        hv.apply(*root.get());


        if( do_convert )
            root = oc.convert( root.get() );

        FIXME(Without textures useless)
#if 0 
        const std::string name = pathFileOut.stem().string();

        osgDB::FilePathList fpl_;
        fpl_.push_back(pathFileOut.parent_path().string() + "/");
        std::string mat_file_name = osgDB::findFileInPath(name+".dae.mat.xml", /*fpl.*/fpl_,osgDB::CASE_INSENSITIVE);

        MaterialVisitor::namesList nl;
        nl.push_back("building");
        nl.push_back("default");
        nl.push_back("tree");
        nl.push_back("ground"); 
        nl.push_back("concrete");
        nl.push_back("mountain");
        nl.push_back("sea");
        nl.push_back("railing");
        nl.push_back("panorama");
        nl.push_back("plane");
        //nl.push_back("rotor"); /// �ללללללללללללל נאסךמלוםעאנטע� ט הטםאלטקוסךטי ףבתועס�

        MaterialVisitor mv ( nl, std::bind(&creators::createMaterial,sp::_1,sp::_2,name,sp::_3,sp::_4),creators::computeAttributes,mat::reader::read(mat_file_name));
        root->accept(mv);
#endif

        if (internalFormatMode != osg::Texture::USE_IMAGE_DATA_FORMAT)
        {
            std::string ext = osgDB::getFileExtension(fileNameOut);
            CompressTexturesVisitor ctv(internalFormatMode);
            root->accept(ctv);
            ctv.compress();

            osgDB::ReaderWriter::Options *options = osgDB::Registry::instance()->getOptions();
            if (ext!="ive" || (options && options->getOptionString().find("noTexturesInIVEFile")!=std::string::npos))
            {
                ctv.write(osgDB::getFilePath(fileNameOut));
            }
        }

        // scrub normals
        if ( do_overallNormal )
        {
            DefaultNormalsGeometryVisitor dngv;
            root->accept( dngv );
        }

        // apply any user-specified simplification
        if ( do_simplify )
        {
            osgUtil::Simplifier simple;
            simple.setSmoothing( smooth );
            osg::notify( osg::ALWAYS ) << " smoothing: " << smooth << std::endl;
            simple.setSampleRatio( simplifyPercent );
            root->accept( simple );
        }

        osgDB::ReaderWriter::WriteResult result = osgDB::Registry::instance()->writeNode(*root,fileNameOut,osgDB::Registry::instance()->getOptions());
        if (result.success())
        {
            osg::notify(osg::NOTICE)<<"Data written to '"<<fileNameOut<<"'."<< std::endl;
        }
        else if  (result.message().empty())
        {
            osg::notify(osg::NOTICE)<<"Warning: file write to '"<<fileNameOut<<"' not supported."<< std::endl;
        }
        else
        {
            osg::notify(osg::NOTICE)<<result.message()<< std::endl;
        }

    }
    else
    {
Exemple #7
0
int pipeFunction(std::vector<std::string> args, int pipes, std::vector<std::string> history, bool temp_hist_bool) {

  const int commands = pipes + 1;
  int pipefds[pipes*2];
  int status;
  int pid;
  std::vector<int> commandStarts;
  std::vector<char *> arguments(args.size()+1);

  //need to use vector<char *> instead of vector<std:: string> for execvp()
  for(int i = 0; i < (int)args.size(); i++) {
    arguments[i] = &args[i][0];
  }

  //create pipes
  for(int i = 0; i < pipes; i++) {
    if(pipe(pipefds + i*2) < 0){
      perror("pipe error");
      exit(EXIT_FAILURE);
    }
  }

  //first command is always at index 0
  commandStarts.push_back(0);
  for(int i = 1; arguments[i] != NULL; i++) {
    if(strcmp(arguments[i], "|") == 0) {
      arguments[i] = NULL;
      commandStarts.push_back(i+1);
    }
  }

  for(int i = 0; i < commands; i++) {
    pid = fork();

    if(pid == 0) {
      //not last command
      if(i < (commands - 1)) {
        if(dup2(pipefds[2*i + 1], STDOUT_FILENO) < 0) {
          perror("dup2");
          exit(EXIT_FAILURE);
        }
      }
      //not first command
      if(i != 0) {
        if(dup2(pipefds[2*i -2], STDIN_FILENO) < 0) {
          perror("dup2") ;
          exit(EXIT_FAILURE);
        }
      }

      for(int j = 0; j < pipes * 2; j++) {
        close(pipefds[j]);
      }

      //execute processes
      if(strcmp(arguments[commandStarts[i]], "pwd") == 0){
        pwd();
        exit(0);
      }else if(strcmp(arguments[commandStarts[i]], "ls") == 0){
        if(arguments[commandStarts[i]+1] == NULL){
          ls();
          exit(0);
        }else{
          ls(arguments[commandStarts[i] + 1]);
          exit(0);
        }
      }else if(strcmp(arguments[commandStarts[i]],"history") == 0){
        for(size_t i = 0; i < history.size(); i++)
        {
          write(STDOUT_FILENO, std::to_string(i).c_str(), strlen(std::to_string(i).c_str()) );
          write(STDOUT_FILENO, " ", 1);
          write(STDOUT_FILENO, history[history.size()-i-1].c_str(), strlen(history[history.size()-i-1].c_str()));
          write(STDOUT_FILENO, "\n", 1);
        }
        exit(0);
      }else if( execvp(arguments[commandStarts[i]], arguments.data() + commandStarts[i]) < 0 ){
        perror(*(arguments.data()));
        exit(EXIT_FAILURE);
      }//end pid == 0
    } else if (pid < 0) {
      perror("error");
      exit(EXIT_FAILURE);
      break;
    }
  }

  //last close of pipes
  for(int i = 0; i < 2 * pipes; i++){
    close(pipefds[i]);
  }

  //wait for all child processes
  for(int i = 0; i < pipes + 1; i++){
    wait(&status);
  }
  return 0;
}
Exemple #8
0
    Application(int &argc, char **argv)
        : QApplication(argc, argv)
    {
        QDir dir(applicationDirPath());
#ifdef Q_OS_MAC
        dir.cdUp();
        dir.cd("PlugIns");
        dir.cd("qt");
#else
        dir.cd("lib");
        dir.cd("qt5");
#endif
        addLibraryPath(dir.absolutePath());
        setOrganizationName("Meltytech");
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
        setOrganizationDomain("shotcut.org");
        setDesktopFileName("org.shotcut.Shotcut");
#else
        setOrganizationDomain("meltytech.com");
#endif
        setApplicationName("Shotcut");
        setApplicationVersion(SHOTCUT_VERSION);
        setAttribute(Qt::AA_UseHighDpiPixmaps);
        setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#if defined(Q_OS_MAC)
        setAttribute(Qt::AA_DontShowIconsInMenus);
#endif

        // Process command line options.
        QCommandLineParser parser;
        parser.addHelpOption();
        parser.addVersionOption();
#ifndef Q_OS_WIN
        QCommandLineOption fullscreenOption("fullscreen",
            QCoreApplication::translate("main", "Fill the screen with the Shotcut window."));
        parser.addOption(fullscreenOption);
#endif
        QCommandLineOption noupgradeOption("noupgrade",
            QCoreApplication::translate("main", "Hide upgrade prompt and menu item."));
        parser.addOption(noupgradeOption);
        QCommandLineOption gpuOption("gpu",
            QCoreApplication::translate("main", "Use GPU processing."));
        parser.addOption(gpuOption);
        QCommandLineOption clearRecentOption("clear-recent",
            QCoreApplication::translate("main", "Clear Recent on Exit"));
        parser.addOption(clearRecentOption);
        QCommandLineOption appDataOption("appdata",
            QCoreApplication::translate("main", "The directory for app configuration and data."),
            QCoreApplication::translate("main", "directory"));
        parser.addOption(appDataOption);
        QCommandLineOption scaleOption("QT_SCALE_FACTOR",
            QCoreApplication::translate("main", "The scale factor for a high-DPI screen"),
            QCoreApplication::translate("main", "number"));
        parser.addOption(scaleOption);
        scaleOption = QCommandLineOption("QT_SCREEN_SCALE_FACTORS",
            QCoreApplication::translate("main", "A semicolon-separated list of scale factors for each screen"),
            QCoreApplication::translate("main", "list"));
        parser.addOption(scaleOption);
        parser.addPositionalArgument("[FILE]...",
            QCoreApplication::translate("main", "Zero or more files or folders to open"));
        parser.process(arguments());
#ifdef Q_OS_WIN
        isFullScreen = false;
#else
        isFullScreen = parser.isSet(fullscreenOption);
#endif
        setProperty("noupgrade", parser.isSet(noupgradeOption));
        setProperty("clearRecent", parser.isSet(clearRecentOption));
        if (!parser.value(appDataOption).isEmpty()) {
            appDirArg = parser.value(appDataOption);
            ShotcutSettings::setAppDataForSession(appDirArg);
        }
        if (parser.isSet(gpuOption))
            Settings.setPlayerGPU(true);
        if (!parser.positionalArguments().isEmpty())
            resourceArg = parser.positionalArguments();

        // Startup logging.
        dir = Settings.appDataLocation();
        if (!dir.exists()) dir.mkpath(dir.path());
        const QString logFileName = dir.filePath("shotcut-log.txt");
        QFile::remove(logFileName);
        FileAppender* fileAppender = new FileAppender(logFileName);
        fileAppender->setFormat("[%{type:-7}] <%{function}> %{message}\n");
        cuteLogger->registerAppender(fileAppender);
#ifndef NDEBUG
        // Only log to console in dev debug builds.
        ConsoleAppender* consoleAppender = new ConsoleAppender();
        consoleAppender->setFormat(fileAppender->format());
        cuteLogger->registerAppender(consoleAppender);

        mlt_log_set_level(MLT_LOG_VERBOSE);
#else
        mlt_log_set_level(MLT_LOG_INFO);
#endif
        mlt_log_set_callback(mlt_log_handler);
        cuteLogger->logToGlobalInstance("qml", true);

        // Log some basic info.
        LOG_INFO() << "Starting Shotcut version" << SHOTCUT_VERSION;
#if defined (Q_OS_WIN)
        LOG_INFO() << "Windows version" << QSysInfo::windowsVersion();
#elif defined(Q_OS_MAC)
        LOG_INFO() << "macOS version" << QSysInfo::macVersion();
#else
        LOG_INFO() << "Linux version";
#endif
        LOG_INFO() << "number of logical cores =" << QThread::idealThreadCount();
        LOG_INFO() << "locale =" << QLocale();
        LOG_INFO() << "install dir =" <<  applicationDirPath();
        LOG_INFO() << "device pixel ratio =" << devicePixelRatio();
        Settings.log();

#if defined(Q_OS_WIN)
        if (Settings.playerGPU()) {
            QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
        } else if (Settings.drawMethod() >= Qt::AA_UseDesktopOpenGL &&
                   Settings.drawMethod() <= Qt::AA_UseSoftwareOpenGL) {
            QCoreApplication::setAttribute(Qt::ApplicationAttribute(Settings.drawMethod()));
        }
#endif
        // Load translations
        QString locale = Settings.language();
        dir = applicationDirPath();
    #if defined(Q_OS_MAC)
        dir.cdUp();
        dir.cd("Resources");
        dir.cd("translations");
    #elif defined(Q_OS_WIN)
        dir.cd("share");
        dir.cd("translations");
    #else
        dir.cdUp();
        dir.cd("share");
        dir.cd("shotcut");
        dir.cd("translations");
    #endif
        if (locale.startsWith("pt_"))
            locale = "pt";
        else if (locale.startsWith("en_"))
            locale = "en";
        if (qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            installTranslator(&qtTranslator);
        else if (qtTranslator.load("qt_" + locale, dir.absolutePath()))
            installTranslator(&qtTranslator);
        if (qtBaseTranslator.load("qtbase_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            installTranslator(&qtBaseTranslator);
        else if (qtBaseTranslator.load("qtbase_" + locale, dir.absolutePath()))
            installTranslator(&qtBaseTranslator);
        if (shotcutTranslator.load("shotcut_" + Settings.language(), dir.absolutePath()))
            installTranslator(&shotcutTranslator);
    }
Exemple #9
0
int main( int argc, char *argv[] )
{
	static int  nlen[M];	
	static char name[M][B], **seq;
	static char **bseq;
	static double *eff;
	int i;
	char c;
	int alloclen;
	FILE *infp;

	arguments( argc, argv );

	if( inputfile )
	{
		infp = fopen( inputfile, "r" );
		if( !infp )
		{
			fprintf( stderr, "Cannot open %s\n", inputfile );
			exit( 1 );
		}
	}
	else
		infp = stdin;

	getnumlen( infp );
	rewind( infp );

	if( njob < 2 )
	{
		fprintf( stderr, "At least 2 sequences should be input!\n"
						 "Only %d sequence found.\n", njob ); 
		exit( 1 );
	}

	seq = AllocateCharMtx( njob, nlenmax*9+1 );
	bseq = AllocateCharMtx( njob, nlenmax*9+1 );
	alloclen = nlenmax*9;

	eff = AllocateDoubleVec( njob );

#if 0
	Read( name, nlen, seq );
#else
	readData( infp, name, nlen, seq );
#endif
	fclose( infp );

	constants( njob, seq );

#if 0
	fprintf( stderr, "params = %d, %d, %d\n", penalty, penalty_ex, offset );
#endif

	initSignalSM();

	initFiles();

	WriteOptions( trap_g );

	c = seqcheck( seq );
	if( c )
	{
		fprintf( stderr, "Illeagal character %c\n", c );
		exit( 1 );
	}

//	writePre( njob, name, nlen, seq, 0 );

	for( i=0; i<njob; i++ ) eff[i] = 1.0;


	for( i=0; i<njob; i++ ) gappick0( bseq[i], seq[i] );


	for( i=0; i<njob; i++ ) fprintf( stdout, ">_seed_%s\n%s\n", name[i]+1, bseq[i] );

	pairalign( name, nlen, seq, eff, alloclen );

	fprintf( trap_g, "done.\n" );
#if DEBUG
	fprintf( stderr, "closing trap_g\n" );
#endif
	fclose( trap_g );

#if IODEBUG
	fprintf( stderr, "OSHIMAI\n" );
#endif
	SHOWVERSION;
	return( 0 );
}
Exemple #10
0
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()->setDescription(arguments.getApplicationName()+" example provides an interactive viewer for visualising point clouds..");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--sprites","Point sprites.");
    arguments.getApplicationUsage()->addCommandLineOption("--points","Sets the polygon mode to GL_POINT for front and back faces.");


    // construct the viewer.
    osgViewer::Viewer viewer;

    bool shader = false;
    while (arguments.read("--shader")) shader = true;

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    bool usePointSprites = false;
    while (arguments.read("--sprites")) {
        usePointSprites = true;
    };

    bool forcePointMode = false;
    while (arguments.read("--points")) {
        forcePointMode = true;
    };

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

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

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

    // optimize the scene graph, remove redundant nodes and state etc.
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());


    // set the scene to render
    viewer.setSceneData(loadedModel.get());


    osg::StateSet* stateset = loadedModel->getOrCreateStateSet();
    if (usePointSprites)
    {
        /// Setup cool blending
        osg::BlendFunc *fn = new osg::BlendFunc();
        stateset->setAttributeAndModes(fn, osg::StateAttribute::ON);

        /// Setup the point sprites
        osg::PointSprite *sprite = new osg::PointSprite();
        stateset->setTextureAttributeAndModes(0, sprite, osg::StateAttribute::ON);

        /// The texture for the sprites
        osg::Texture2D *tex = new osg::Texture2D();
        tex->setImage(osgDB::readImageFile("Images/particle.rgb"));
        stateset->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON);
    }

    if( forcePointMode )
    {
        /// Set polygon mode to GL_POINT
        osg::PolygonMode *pm = new osg::PolygonMode(
            osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::POINT );
        stateset->setAttributeAndModes( pm, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
    }


    // register the handler for modifying the point size
    viewer.addEventHandler(new KeyboardEventHandler(viewer.getCamera()->getOrCreateStateSet()));


    if (shader)
    {
        osg::StateSet* stateset = loadedModel->getOrCreateStateSet();

        ///////////////////////////////////////////////////////////////////
        // vertex shader using just Vec4 coefficients
        char vertexShaderSource[] =
            "void main(void) \n"
            "{ \n"
            "\n"
            "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
            "}\n";



        osg::Program* program = new osg::Program;
        stateset->setAttribute(program);

        osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource);
        program->addShader(vertex_shader);

#if 0
        //////////////////////////////////////////////////////////////////
        // fragment shader
        //
        char fragmentShaderSource[] =
            "void main(void) \n"
            "{ \n"
            "    gl_FragColor = gl_Color; \n"
            "}\n";

        osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource);
        program->addShader(fragment_shader);
#endif
    }

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

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which runs units tests.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options]");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("qt","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("quat","Display extended quaternion tests.");
    arguments.getApplicationUsage()->addCommandLineOption("quat_scaled sx sy sz","Display extended quaternion tests of pre scaled matrix.");
    arguments.getApplicationUsage()->addCommandLineOption("sizeof","Display sizeof tests.");
    arguments.getApplicationUsage()->addCommandLineOption("matrix","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("performance","Display qualified tests.");
    arguments.getApplicationUsage()->addCommandLineOption("read-threads <numthreads>","Run multi-thread reading test.");
 

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    bool printQualifiedTest = false; 
    while (arguments.read("qt")) printQualifiedTest = true; 

    bool printMatrixTest = false; 
    while (arguments.read("matrix")) printMatrixTest = true; 

    bool printSizeOfTest = false; 
    while (arguments.read("sizeof")) printSizeOfTest = true; 

    bool printQuatTest = false; 
    while (arguments.read("quat")) printQuatTest = true;

    int numReadThreads = 0; 
    while (arguments.read("read-threads", numReadThreads)) {}

    bool printPolytopeTest = false; 
    while (arguments.read("polytope")) printPolytopeTest = true;
    
    bool doTestThreadInitAndExit = false;
    while (arguments.read("thread")) doTestThreadInitAndExit = true;

    osg::Vec3d quat_scale(1.0,1.0,1.0); 
    while (arguments.read("quat_scaled", quat_scale.x(), quat_scale.y(), quat_scale.z() )) printQuatTest = true; 

    bool performanceTest = false; 
    while (arguments.read("p") || arguments.read("performance")) performanceTest = true; 

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        std::cout<<arguments.getApplicationUsage()->getCommandLineUsage()<<std::endl;
        arguments.getApplicationUsage()->write(std::cout,arguments.getApplicationUsage()->getCommandLineOptions());
        return 1;
    }

    // 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);
        return 1;
    }
    
    if (printQuatTest)
    {
        testQuat(quat_scale);
    }

    if (printMatrixTest)
    {
        std::cout<<"******   Running matrix tests   ******"<<std::endl;

        testFrustum(-1,1,-1,1,1,1000);
        testFrustum(0,1,1,2,2.5,100000);

        testOrtho(0,1,1,2,2.1,1000);
        testOrtho(-1,10,1,20,2.5,100000);

        testPerspective(20,1,1,1000);
        testPerspective(90,2,1,1000);

        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(0.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
        testLookAt(osg::Vec3(10.0,4.0,2.0),osg::Vec3(10.0,4.0,2.0)+osg::Vec3(1.0,1.0,0.0),osg::Vec3(0.0,0.0,1.0));
        
        testMatrixInvert(osg::Matrix(0.999848,  -0.002700,  0.017242, -0.1715,
                                     0,         0.987960,   0.154710,  0.207295,
                                     -0.017452, -0.154687,  0.987809, -0.98239,
                                     0,         0,          0,         1));

        testMatrixInvert(osg::Matrix(0.999848,  -0.002700,  0.017242,   0.0,
                                     0.0,        0.987960,   0.154710,   0.0,
                                     -0.017452, -0.154687,  0.987809,   0.0,
                                     -0.1715,    0.207295,  -0.98239,   1.0));

    }
    
    if (printSizeOfTest)
    {
        std::cout<<"**** sizeof() tests  ******"<<std::endl;
        
        sizeOfTest();

        std::cout<<std::endl;
    }


    if (performanceTest)
    {
        std::cout<<"**** performance tests  ******"<<std::endl;
        
        runPerformanceTests();
    }

    if (numReadThreads>0)
    {
        runMultiThreadReadTests(numReadThreads, arguments);
        return 0;
    }


    if (printPolytopeTest)
    {
        testPolytope();
    }


    if (printQualifiedTest) 
    {
         std::cout<<"*****   Qualified Tests  ******"<<std::endl;

         osgUtx::QualifiedTestPrinter printer;
         osgUtx::TestGraph::instance().root()->accept( printer );    
         std::cout<<std::endl;
    }

    if (doTestThreadInitAndExit)
    {
        testThreadInitAndExit();
    }

    std::cout<<"******   Running tests   ******"<<std::endl;

    // Global Data or Context
    osgUtx::TestContext ctx;
    osgUtx::TestRunner runner( ctx );
    runner.specify("root");

    osgUtx::TestGraph::instance().root()->accept( runner );

    return 0;
}
bool ossimPlanetQtApplication::initWithArgs(int& argc, char** argv)
{
   osg::Texture::setMinimumNumberOfTextureObjectsToRetainInCache(0);
   osg::Drawable::setMinimumNumberOfDisplayListsToRetainInCache(0);
   //osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts(1);

   if(getMaximumFiles() < 1024)
   {
            setMaximumFiles(1024);
   }
   //    setMaximumFiles(25);

   //osgDB::DatabasePager* databasePager = osgDB::Registry::instance()->getOrCreateDatabasePager();
   
   ossimArgumentParser argumentParser(&argc, argv);
   
   wmsInitialize();
   ossimInit::instance()->setPluginLoaderEnabledFlag(false);
   ossimInit::instance()->initialize(argumentParser);
   osg::ArgumentParser arguments(&argumentParser.argc(),argumentParser.argv());
   
   std::string tempString;
   osg::ArgumentParser::Parameter stringParam(tempString);
   addCommandLineOptions(arguments);
   
   if(arguments.read("-h") || arguments.read("--help"))
   {
      arguments.getApplicationUsage()->write(std::cout);
      return false;
   }
   
//    if(arguments.read("--enable-flatland"))
//    {
//       theLandType = ossimPlanetLandType_FLAT;
//    }
   if(arguments.read("--wms-timeout", stringParam))
   {
      setWmsNetworkTimeoutInSeconds(ossimString(tempString).toDouble());
   }
   if(arguments.read("--disable-elevation"))
   {
//       theElevEnabled = false;
      writePreferenceSetting("elev-flag",
                             "false");
   }
   if(arguments.read("--elev-estimation", stringParam))
   {
//       theElevEstimate = 1<<ossimString(tempString.c_str()).toUInt32();
      writePreferenceSetting("elev-patchsize",
                             ossimString::toString(1<<ossimString(tempString.c_str()).toUInt32()).c_str());
  }
   if(arguments.read("--elev-patchsize", stringParam))
   {
      writePreferenceSetting("elev-patchsize", tempString.c_str());
//       theElevEstimate = ossimString(tempString.c_str()).toUInt32();
   }
   if(arguments.read("--elev-exag", stringParam))
   {
//       theElevExag = ossimString(tempString.c_str()).toDouble();
      writePreferenceSetting("elev-exag", tempString.c_str());
   }
   if(arguments.read("--split-metric", stringParam))
   {
//       theSplitMetricRatio = ossimString(tempString.c_str()).toDouble();
      writePreferenceSetting("split-metric", tempString.c_str());
   }
   if(arguments.read("--elev-cache", stringParam))
   {
//       theElevCache = tempString.c_str();
      writePreferenceSetting("elev-cache", tempString.c_str());
   }
   if(arguments.read("--level-detail", stringParam))
   {
//       theLevelOfDetail = ossimString(tempString.c_str()).toUInt32();
      writePreferenceSetting("level-detail", tempString.c_str());
   }
   if(arguments.read("--enable-hud"))
   {
      writePreferenceSetting("hud-flag", "true");
//       theHudEnabled = true;
   }
   else if(arguments.read("--disable-hud"))
   {
      writePreferenceSetting("hud-flag", "false");
   }

   // archive mapping enabled
   if( arguments.read("--enable-archive-mapping-enabled") )
   {
	   writePreferenceSetting("archive-mapping-enabled", "true");
   }
   else if( arguments.read("--disable-archive-mapping-enabled") )
   {
	   writePreferenceSetting("archive-mapping-enabled", "false");
   }

   if(arguments.read("--disable-mipmap"))
   {
      writePreferenceSetting("mipmap-flag", "false");
// 	   theMipMapping = false;
   }
   if(arguments.read("--enable-mipmap"))
   {
      writePreferenceSetting("mipmap-flag", "true");
// 	   theMipMapping = false;
   }
   arguments.reportRemainingOptionsAsUnrecognized();
   
   if (arguments.errors())
   {
      arguments.writeErrorMessages(std::cout);
   }
   ossimFilename currentPath = ossimFilename(argv[0]).path();
   ossimFilename imageBundle;
   ossimFilename referenceImageBundle;
   ossimInit::instance()->setPluginLoaderEnabledFlag(true);
//    ossimString paths = ossimEnvironmentUtility::instance()->getEnvironmentVariable("OSSIM_ELEVATION_PATH");
//    std::vector<ossimString> pathArray;
//    ossimString pathSeparator = ":";
   osgDB::Registry::instance()->getDataFilePathList().push_back(theUserSupportDirectory.toStdString());
   ossimFilename installDir = ossimEnvironmentUtility::instance()->getInstalledOssimSupportDir();
   if(installDir.exists())
   {
      osgDB::Registry::instance()->getDataFilePathList().push_back(installDir);
   }
   ossimFilename userDir    = ossimEnvironmentUtility::instance()->getUserOssimSupportDir();
   ossimFilename userImageDir = userDir.dirCat("images");
   ossimFilename userDataDir = userDir.dirCat("data");
   ossimFilename userImageReferenceDir = userImageDir.dirCat("reference");
   ossimFilename installImageDir = installDir.dirCat("images");
   ossimFilename installDataDir = installDir.dirCat("data");
   ossimFilename instalImageReferenceDir = installImageDir.dirCat("reference");
   userDir = userDir.dirCat("images");
   userDir = userDir.dirCat("reference");
   installDir = installDir.dirCat("images");
   installDir = installDir.dirCat("reference");

   // tmp drb
   // ossimFilename userStatePlaneFile = userDataDir.dirCat("state_plane.csv");
   // ossimFilename installStatePlaneFile = installDataDir.dirCat("state_plane.csv");
   // if(userStatePlaneFile.exists())
   // {
      // allow state plane to override from user directory any installed state plane file.
   //   ossimStatePlaneProjectionFactory::instance()->addCsvFile(userStatePlaneFile);
   // }
#ifdef __MACOSX__
   // test for a bundle
   //
   ossimFilename contentsFolder = currentPath.path();

   // Check for embedded geoid grid nder the resource folder Resources/egm96.grd
   ossimFilename resourceFolder = contentsFolder.dirCat("Resources");
   ossimFilename geoid1996File = resourceFolder.dirCat("egm96.grd");
   ossimFilename statePlaneFile = resourceFolder.dirCat("state_plane.csv");
   if(geoid1996File.exists())
   {
      ossimRefPtr<ossimGeoid> geoid96 = new ossimGeoidEgm96;
      if(geoid96->open(geoid1996File, OSSIM_BIG_ENDIAN))
      {
         ossimGeoidManager::instance()->addGeoid(geoid96.get());
      }
   }
//   if(statePlaneFile.exists())
//   {
//      ossimStatePlaneProjectionFactory::instance()->addCsvFile(statePlaneFile);
//   }
   // Check for embedded plugins and reference images
   ossimFilename resources = contentsFolder.dirCat("Resources");
   ossimFilename ossimPluginsBundle = contentsFolder.dirCat("plugins");
   ossimFilename osgPlugins         = contentsFolder.dirCat("osgplugins");
   referenceImageBundle = contentsFolder.dirCat("Resources");
   imageBundle = referenceImageBundle.dirCat("images");
   referenceImageBundle = imageBundle.dirCat("reference");
   if(ossimPluginsBundle.exists())
   {
      ossimInit::instance()->loadPlugins(ossimPluginsBundle);
   }
   if(osgPlugins.exists())
   {
      osgDB::Registry::instance()->getLibraryFilePathList().push_front(osgPlugins);
   }
   if(resources.exists())
   {
      osgDB::Registry::instance()->getDataFilePathList().push_front(resources);
      osgDB::Registry::instance()->getDataFilePathList().push_front(resources.dirCat("fonts"));
   }

   theThemePath = resourceFolder;
   theThemePath = theThemePath.dirCat("themes");

   ossimFilename elevation = resourceFolder.dirCat("elevation");
   if(elevation.exists())
   {
      ossimElevManager::instance()->loadElevationPath(elevation);
   }
//    addLibraryPath(contentsFolder.dirCat("qtplugins").c_str());
#endif
#ifdef WIN32
   ossimFilename geoid = currentPath.dirCat("geoid1996");
   ossimFilename geoid1996File = geoid.dirCat("egm96.grd");
   if(!geoid1996File.exists())
   {
	   geoid = currentPath.dirCat("geoids");
	   geoid = geoid.dirCat("geoid1996");
	   geoid1996File = geoid.dirCat("egm96.grd");
   }
   if(geoid1996File.exists())
   {
      ossimRefPtr<ossimGeoid> geoid96 = new ossimGeoidEgm96;
      if(geoid96->open(geoid1996File, OSSIM_BIG_ENDIAN))
      {
         ossimGeoidManager::instance()->addGeoid(geoid96.get());
      }
   }
   ossimFilename osgPluginsBundle = currentPath.dirCat("osgplugins");
// ossimFilename ossimPluginsBundle = currentPath.dirCat("plugins");
   referenceImageBundle = currentPath;
   imageBundle = referenceImageBundle.dirCat("images");
   referenceImageBundle = imageBundle.dirCat("reference");
   if(osgPluginsBundle.exists())
   {
	   osgDB::Registry::instance()->getLibraryFilePathList().push_back(osgPluginsBundle);
   }
//   if(ossimPluginsBundle.exists())
//   {
//      ossimInit::instance()->loadPlugins(ossimPluginsBundle);
//   }
   ossimFilename elevation = currentPath.dirCat("elevation");
   if(elevation.exists())
   {
      ossimElevManager::instance()->loadElevationPath(elevation);
   }
//    pathSeparator = ";";
#endif
   ossimFilename dataDir = currentPath.dirCat("data");

   // tmp drb
   // ossimFilename statePlane = dataDir.dirCat("state_plane.csv");

   // if(statePlane.exists())
   // {
   // ossimStatePlaneProjectionFactory::instance()->addCsvFile(statePlane);
   //}
  // we will now initialize any other plugins outside the bundle in standard locations
   //
   // if(installStatePlaneFile.exists())
   // {
   // ossimStatePlaneProjectionFactory::instance()->addCsvFile(installStatePlaneFile);
   // }
   ossimInit::instance()->initializePlugins();
   
   if(arguments.argc() > 1)
   {
      ossimKeywordlist kwl;
      if(kwl.addFile(arguments.argv()[1]))
      {
         osg::ref_ptr<ossimPlanetTextureLayer> layer = ossimPlanetTextureLayerRegistry::instance()->createLayer(kwl.toString());
         if(layer.valid())
         {
            layer->resetLookAt();
            theReferenceImages.push_front(layer);
         }
      }
   }
   else
   {
      ossimFilename refFiles;
      
      if(userDir.exists())
      {
         refFiles = userDir;
      }
      else if(installDir.exists())
      {
         refFiles = installDir;
      }
      else if(referenceImageBundle.exists())
      {
         refFiles = referenceImageBundle;
      }
      if(refFiles.exists())
      {
         ossimDirectory dir;
         if(dir.open(refFiles))
         {
            ossimFilename file;
            dir.getFirst(file);
            do
            {
               ossimString ext = file.ext();
               if((ext != "ovr")&&
                  (ext != "omd")&&
                  (ext != "geom")&&
                  (ext != "his"))
               {
                  osg::ref_ptr<ossimPlanetTextureLayer> layer = ossimPlanetTextureLayerRegistry::instance()->createLayer(ossimString(file.c_str()));
                  if(layer.valid())
                  {
                     layer->resetLookAt();
                     theReferenceImages.push_front(layer);
                  }
               }
               
            }while(dir.getNext(file));
         }
      }      
   }
   if(userImageDir.dirCat("compass.png").exists())
   {
      theCompassRing = userImageDir.dirCat("compass.png");
   }
   else if(imageBundle.dirCat("compass.png").exists())
   {
      theCompassRing = imageBundle.dirCat("compass.png");
   }
   else if(installImageDir.dirCat("compassring.png").exists())
   {
      theCompassRing = installImageDir.dirCat("compassring.png");
      //theCompassRose = installImageDir.dirCat("compassrose.png");
   }
   else if(userImageDir.dirCat("compassring.png").exists())
   {
      theCompassRing = userImageDir.dirCat("compassring.png");
      //theCompassRose = userImageDir.dirCat("compassrose.png");
   }
   else if(imageBundle.dirCat("compassring.png").exists())
   {
      theCompassRing = imageBundle.dirCat("compassring.png");
      //theCompassRose = imageBundle.dirCat("compassrose.png");
   }
   else if(installImageDir.dirCat("compassring.png").exists())
   {
      theCompassRing = installImageDir.dirCat("compassring.png");
      //theCompassRose = installImageDir.dirCat("compassrose.png");
   }
   
   if(autoHistogramStretchMode().isEmpty())
   {
      setAutoHistogramStretchMode("Linear Auto Min Max");
   }
   return true;
}
Exemple #13
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // initialize the viewer.
    osgViewer::Viewer viewer;

    // load the nodes from the commandline arguments.
    osg::Node* rootnode = osgDB::readNodeFiles(arguments);
    if (!rootnode)
    {
        osg::notify(osg::NOTICE)<<"Please specify a model filename on the command line."<<std::endl;
        return 1;
    }
    
    // run optimization over the scene graph
    osgUtil::Optimizer optimzer;
    optimzer.optimize(rootnode);
    
// -------------    Start of copy specific code -------------------------------------------------------
    
    // do a deep copy, using MyCopyOp to reveal whats going on under the hood,
    // in your own code you'd typically just use the basic osg::CopyOp something like
    osg::ref_ptr<osg::Node> mycopy = dynamic_cast<osg::Node*>(rootnode->clone(osg::CopyOp::DEEP_COPY_ALL));
    std::cout << "Doing a deep copy of scene graph"<<std::endl;

    // note, we need the dyanmic_cast because MS Visual Studio can't handle covarient
    // return types, so that clone has return just Object*.  bahh hum bug
    osg::ref_ptr<osg::Node> deep_copy = dynamic_cast<osg::Node*>(rootnode->clone(MyCopyOp(osg::CopyOp::DEEP_COPY_ALL)));
    
    std::cout << "----------------------------------------------------------------"<<std::endl;

    // do a graph preserving deep copy.
    std::cout << "Doing a graph preserving deep copy of scene graph nodes"<<std::endl;
    osg::ref_ptr<osg::Node> graph_copy = dynamic_cast<osg::Node*>(rootnode->clone(GraphCopyOp(osg::CopyOp::DEEP_COPY_NODES)));


    // do a shallow copy.
    std::cout << "Doing a shallow copy of scene graph"<<std::endl;
    osg::ref_ptr<osg::Node> shallow_copy = dynamic_cast<osg::Node*>(rootnode->clone(MyCopyOp(osg::CopyOp::SHALLOW_COPY)));


    // write out the various scene graphs so that they can be browsed, either
    // in an editor or using a graphics diff tool gdiff/xdiff/xxdiff.
    std::cout << std::endl << "Writing out the original scene graph as 'original.osgt'"<<std::endl;
    osgDB::writeNodeFile(*rootnode,"original.osgt");

    std::cout << std::endl << "Writing out the graph preserving scene graph as 'graph_copy.osgt'"<<std::endl;
    osgDB::writeNodeFile(*graph_copy,"graph_copy.osgt");

    std::cout << "Writing out the deep copied scene graph as 'deep_copy.osgt'"<<std::endl;
    osgDB::writeNodeFile(*deep_copy,"deep_copy.osgt");

    std::cout << "Writing out the shallow copied scene graph as 'shallow_copy.osgt'"<<std::endl;
    osgDB::writeNodeFile(*shallow_copy,"shallow_copy.osgt");


    // You can use a bit mask to control which parts of the scene graph are shallow copied
    // vs deep copied.  The options are (from include/osg/CopyOp) :
    // enum Options {
    //        SHALLOW_COPY = 0,
    //        DEEP_COPY_OBJECTS = 1,
    //        DEEP_COPY_NODES = 2,
    //        DEEP_COPY_DRAWABLES = 4,
    //        DEEP_COPY_STATESETS = 8,
    //        DEEP_COPY_STATEATTRIBUTES = 16,
    //        DEEP_COPY_TEXTURES = 32,
    //        DEEP_COPY_IMAGES = 64,
    //        DEEP_COPY_ALL = 0xffffffff
    // };
    // 
    // These options you can use together such as :
    //    osg::Node* mycopy = dynamic_cast<osg::Node*>(rootnode->clone(osg::CopyOp::DEEP_COPY_NODES | DEEP_COPY_DRAWABLES));
    // Which shares state but creates copies of all nodes and drawables (which contain the geometry).
    // 
    // You may also want to subclass from CopyOp to provide finer grained control of what gets shared (shallow copy) vs
    // cloned (deep copy).
    


// -------------    End of copy specific code -------------------------------------------------------
     
    // set the scene to render
    viewer.setSceneData(rootnode);

    // viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);

    return viewer.run();
}
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()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of convex planer occluders.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-m","Manually create occluders");

    // initialize the viewer.
    osgViewer::Viewer viewer;

    bool manuallyCreateOccluders = false;
    while (arguments.read("-m")) { manuallyCreateOccluders = true; }

    if (manuallyCreateOccluders)
    {
        viewer.addEventHandler(new OccluderEventHandler(&viewer));
    }

    // if user requests help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // load the nodes from the commandline arguments.
    osg::ref_ptr<osg::Node> loadedmodel = osgDB::readRefNodeFiles(arguments);

    // if not loaded assume no arguments passed in, try using default mode instead.
    if (!loadedmodel) loadedmodel = osgDB::readRefNodeFile("glider.osgt");

    if (!loadedmodel)
    {
        osg::notify(osg::NOTICE)<<"Please specify a model filename on the command line."<<std::endl;
        return 1;
    }

    // run optimization over the scene graph
    osgUtil::Optimizer optimzer;
    optimzer.optimize(loadedmodel);

    // add the occluders to the loaded model.
    osg::ref_ptr<osg::Group> rootnode;

    if (manuallyCreateOccluders)
    {
        rootnode = new osg::Group;
        rootnode->addChild(loadedmodel);
    }
    else
    {
        rootnode = createOccludersAroundModel(loadedmodel.get());
    }


    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData( rootnode );

    return viewer.run();
}
int main(int argc, char **argv)
{
	//std::string opt_env= "OSG_OPTIMIZER=COMBINE_ADJACENT_LODS SHARE_DUPLICATE_STATE MERGE_GEOMETRY MAKE_FAST_GEOMETRY CHECK_GEOMETRY OPTIMIZE_TEXTURE_SETTINGS STATIC_OBJECT_DETECTION";
//#ifdef WIN32
	//_putenv(opt_env.c_str());
//#else
	

	//const std::string shadow_type = "VDSM";

	osg::DisplaySettings::instance()->setNumMultiSamples(4);
	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);

	arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
	arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the standard OpenSceneGraph example which loads and visualises 3d models.");
	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("--login <url> <username> <password>", "Provide authentication information for http file access.");
	arguments.getApplicationUsage()->addCommandLineOption("-p <filename>", "Play specified camera path animation file, previously saved with 'z' key.");
	arguments.getApplicationUsage()->addCommandLineOption("--speed <factor>", "Speed factor for animation playing (1 == normal speed).");
	arguments.getApplicationUsage()->addCommandLineOption("--device <device-name>", "add named device to the viewer");
	arguments.getApplicationUsage()->addCommandLineOption("--fov <value>", "Field of view");
	arguments.getApplicationUsage()->addCommandLineOption("--enable_fog", "Use Fog");
	arguments.getApplicationUsage()->addCommandLineOption("--shadow_type <value>", "Set Shadow type NONE,LISPSM or VDSM");

	osgViewer::Viewer viewer(arguments);

	unsigned int helpType = 0;
	if ((helpType = arguments.readHelpType()))
	{
		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;
	}

	if (arguments.argc() <= 1)
	{
		arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::COMMAND_LINE_OPTION);
		return 1;
	}

	std::string url, username, password;
	while (arguments.read("--login", url, username, password))
	{
		if (!osgDB::Registry::instance()->getAuthenticationMap())
		{
			osgDB::Registry::instance()->setAuthenticationMap(new osgDB::AuthenticationMap);
			osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails(
				url,
				new osgDB::AuthenticationDetails(username, password)
				);
		}
	}

	std::string device;
	while (arguments.read("--device", device))
	{
#if OSG_VERSION_GREATER_OR_EQUAL(3,5,1)
		osg::ref_ptr<osgGA::Device> dev = osgDB::readRefFile<osgGA::Device>(device);
#else
		osg::ref_ptr<osgGA::Device> dev = osgDB::readFile<osgGA::Device>(device);
#endif
		if (dev.valid())
		{
			viewer.addDevice(dev);
		}
	}

	double fov = 35;
	while (arguments.read("--fov", fov))
	{

	}

	bool use_fog = false;
	while (arguments.read("--enable_fog"))
	{
		use_fog =  true;
	}

	bool enableShadows = true;
	std::string shadow_type = "NONE";
	while (arguments.read("--shadow_type", shadow_type))
	{

	}

	if(shadow_type == "NONE")
		enableShadows = false;


	// set up the camera manipulators.
	{
		osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

		keyswitchManipulator->addMatrixManipulator('1', "Trackball", new osgGA::TrackballManipulator());
		keyswitchManipulator->addMatrixManipulator('2', "Flight", new osgGA::FlightManipulator());
		keyswitchManipulator->addMatrixManipulator('3', "Drive", new osgGA::DriveManipulator());
		keyswitchManipulator->addMatrixManipulator('4', "Terrain", new osgGA::TerrainManipulator());
		keyswitchManipulator->addMatrixManipulator('5', "Orbit", new osgGA::OrbitManipulator());
		keyswitchManipulator->addMatrixManipulator('6', "FirstPerson", new osgGA::FirstPersonManipulator());
		keyswitchManipulator->addMatrixManipulator('7', "Spherical", new osgGA::SphericalManipulator());

		std::string pathfile;
		double animationSpeed = 1.0;
		while (arguments.read("--speed", animationSpeed)) {}
		char keyForAnimationPath = '8';
		while (arguments.read("-p", pathfile))
		{
			osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
			if (apm || !apm->valid())
			{
				apm->setTimeScale(animationSpeed);

				unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
				keyswitchManipulator->addMatrixManipulator(keyForAnimationPath, "Path", apm);
				keyswitchManipulator->selectMatrixManipulator(num);
				++keyForAnimationPath;
			}
		}

		viewer.setCameraManipulator(keyswitchManipulator.get());
	}

	// add the state manipulator
	viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

	// add the thread model handler
	viewer.addEventHandler(new osgViewer::ThreadingHandler);

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

	// add the stats handler
	viewer.addEventHandler(new osgViewer::StatsHandler);

	// add the help handler
	viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));

	// add the record camera path handler
	viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);

	// add the LOD Scale handler
	viewer.addEventHandler(new osgViewer::LODScaleHandler);

	// add the screen capture handler
	viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);

	// load the data
#if OSG_VERSION_GREATER_OR_EQUAL(3,5,1)
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments);
#else
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
#endif
	if (!loadedModel)
	{
		std::cout << arguments.getApplicationName() << ": No data loaded" << std::endl;
		return 1;
	}

	// 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);
		return 1;
	}


	// optimize the scene graph, remove redundant nodes and state etc.
	osgUtil::Optimizer optimizer;
	optimizer.optimize(loadedModel);

	//Create root node
	osg::Group* group = new osg::Group;

	if (use_fog)
	{
		//Add fog
		const osg::Fog::Mode fog_mode = osg::Fog::LINEAR;
		osg::StateSet* state = group->getOrCreateStateSet();
		osg::ref_ptr<osg::Fog> fog = new osg::Fog();
		state->setMode(GL_FOG, osg::StateAttribute::ON);
		state->setAttributeAndModes(fog.get());
		fog->setMode(fog_mode);
		fog->setDensity(0.000005);
		fog->setEnd(800);
		fog->setStart(30);
		fog->setColor(osg::Vec4(1.0, 1.0, 1.0, 1.0));
	}

	//Add light and shadows
	osg::Light* pLight = new osg::Light;
	pLight->setDiffuse(osg::Vec4(0.6f, 0.6f, 0.6f, 0.6f));
	osg::Vec4 lightPos(1, 1.0, 1, 0);
	pLight->setPosition(lightPos);		// last param	w = 0.0 directional light (direction)
	osg::Vec3f lightDir(-lightPos.x(), -lightPos.y(), -lightPos.z());
	lightDir.normalize();
	pLight->setDirection(lightDir);
	pLight->setAmbient(osg::Vec4(0.4f, 0.4f, 0.4f, 1.0f));
	//pLight->setAmbient(osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f) );

	osg::LightSource* pLightSource = new osg::LightSource;
	pLightSource->setLight(pLight);
	group->addChild(pLightSource);
	group->addChild(loadedModel);

	
	double nearClip = 10;
	double farClip = 10000;
	viewer.getCamera()->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR);
	viewer.getCamera()->setProjectionResizePolicy(osg::Camera::HORIZONTAL);
	double aspectRatio = 4.0 / 3.0;

	if (viewer.getCamera()->getViewport())
		aspectRatio = viewer.getCamera()->getViewport()->width() / viewer.getCamera()->getViewport()->height();
	viewer.getCamera()->setProjectionMatrixAsPerspective(fov, aspectRatio, nearClip, farClip);

	static int ReceivesShadowTraversalMask = 0x1;
	static int CastsShadowTraversalMask = 0x2;

	group->setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask);

	osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene;
	int mapres = 2048;
	if (shadow_type == "LISPSM")
	{
		osg::ref_ptr<osgShadow::MinimalShadowMap> sm = new osgShadow::LightSpacePerspectiveShadowMapCB;
		float minLightMargin = 20.f;
		float maxFarPlane = farClip;
		int baseTexUnit = 0;
		int shadowTexUnit = 6;
		sm->setMinLightMargin(minLightMargin);
		sm->setMaxFarPlane(maxFarPlane);
		sm->setTextureSize(osg::Vec2s(mapres, mapres));
		sm->setShadowTextureCoordIndex(shadowTexUnit);
		sm->setShadowTextureUnit(shadowTexUnit);
		sm->setBaseTextureCoordIndex(baseTexUnit);
		sm->setBaseTextureUnit(baseTexUnit);

		//sm->setMainVertexShader(NULL);
		//sm->setShadowVertexShader(NULL);

		shadowedScene->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
		shadowedScene->setCastsShadowTraversalMask(CastsShadowTraversalMask);


		osg::Shader* mainFragmentShader = new osg::Shader(osg::Shader::FRAGMENT,
			" // following expressions are auto modified - do not change them:       \n"
			" // gl_TexCoord[0]  0 - can be subsituted with other index              \n"
			"                                                                        \n"
			"float DynamicShadow( );                                                 \n"
			"                                                                        \n"
			"uniform sampler2D baseTexture;                                          \n"
			"                                                                        \n"
			"void main(void)                                                         \n"
			"{                                                                       \n"
			"  vec4 colorAmbientEmissive = gl_FrontLightModelProduct.sceneColor;     \n"
			"  // Add ambient from Light of index = 0                                \n"
			"  colorAmbientEmissive += gl_FrontLightProduct[0].ambient;              \n"
			"  vec4 color = texture2D( baseTexture, gl_TexCoord[0].xy );             \n"
			"  color *= mix( colorAmbientEmissive, gl_Color, DynamicShadow() );      \n"
			"    float depth = gl_FragCoord.z / gl_FragCoord.w;\n"
			"    float fogFactor = exp(-pow((gl_Fog.density * depth), 2.0));\n"
			"    fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
			"    //color.rgb = mix( gl_Fog.color.rgb, color.rgb, fogFactor );            \n"
			"    gl_FragColor = color;                                                 \n"
			"} \n");

		sm->setMainFragmentShader(mainFragmentShader);
		shadowedScene->setShadowTechnique(sm);
	}
	else if (shadow_type == "VDSM")
	{

		osgShadow::ShadowSettings* settings = shadowedScene->getShadowSettings();
		settings->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask);
		settings->setCastsShadowTraversalMask(CastsShadowTraversalMask);
		//settings->setShadowMapProjectionHint(osgShadow::ShadowSettings::PERSPECTIVE_SHADOW_MAP);
		unsigned int unit = 2;
		settings->setBaseShadowTextureUnit(unit);

		double n = 0.8;
		settings->setMinimumShadowMapNearFarRatio(n);

		unsigned int numShadowMaps = 2;
		settings->setNumShadowMapsPerLight(numShadowMaps);

		//settings->setMultipleShadowMapHint(osgShadow::ShadowSettings::PARALLEL_SPLIT);
		settings->setMultipleShadowMapHint(osgShadow::ShadowSettings::CASCADED);


		settings->setTextureSize(osg::Vec2s(mapres, mapres));
		//settings->setShaderHint(osgShadow::ShadowSettings::PROVIDE_VERTEX_AND_FRAGMENT_SHADER);
		osg::ref_ptr<osgShadow::ViewDependentShadowMap> vdsm = new osgShadow::ViewDependentShadowMap;
		shadowedScene->setShadowTechnique(vdsm.get());
	}


	if (enableShadows)
	{
		shadowedScene->addChild(group);
		viewer.setSceneData(shadowedScene);
	}
	else
	{
		viewer.setSceneData(group);
	}
	viewer.realize();

	while (!viewer.done())
	{
		//animate light if shadows enabled
	//	if (enableShadows)
		{
			float t = viewer.getFrameStamp()->getSimulationTime()*0.04;
			lightPos.set(sinf(t), cosf(t), 0.7f, 0.0f);
			//lightPos.set(0.2f,0,1.1 + cosf(t),0.0f);
			pLight->setPosition(lightPos);
			lightDir.set(-lightPos.x(), -lightPos.y(), -lightPos.z());
			lightDir.normalize();
			pLight->setDirection(lightDir);
		}
		viewer.frame();
	}
	return 1;
}
Exemple #16
0
int osgmain(){
	int argc;
	char* argv[1];
	
	argc=1;
	argv[0]="osg.mod";

	osg::ArgumentParser arguments(&argc,argv);
	
	arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
	arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
	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("--login <url> <username> <password>","Provide authentication information for http file access.");
	
	osgViewer::Viewer viewer(arguments);
	
	// set up the camera manipulators.
	{
	osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
	
	keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
	keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
	keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
	keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
	
	std::string pathfile;
	char keyForAnimationPath = '5';
	while (arguments.read("-p",pathfile))
	{
	osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
	if (apm || !apm->valid()) 
	{
	unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
	keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
	keyswitchManipulator->selectMatrixManipulator(num);
	++keyForAnimationPath;
	}
	}
	viewer.setCameraManipulator( keyswitchManipulator.get() );
	}
	
	// add the state manipulator
	viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
	
	// add the thread model handler
	viewer.addEventHandler(new osgViewer::ThreadingHandler);
	
	// add the window size toggle handler
	viewer.addEventHandler(new osgViewer::WindowSizeHandler);
	
	// add the stats handler
	viewer.addEventHandler(new osgViewer::StatsHandler);
	
	// add the help handler
	//    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
	
	// add the record camera path handler
	viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
	
	// add the LOD Scale handler
	viewer.addEventHandler(new osgViewer::LODScaleHandler);
	
	// add the screen capture handler
	viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);

	/*
	// load the data
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
	if (!loadedModel) 
	{
	std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
	return 1;
	}
	// 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);
	return 1;
	}
	// optimize the scene graph, remove redundant nodes and state etc.
	osgUtil::Optimizer optimizer;
	optimizer.optimize(loadedModel.get());	
	viewer.setSceneData( loadedModel.get() );
*/
	
	viewer.realize();	
	return viewer.run();
	
}
Exemple #17
0
void Evaluate::start() {
  QVariant result = page()->currentFrame()->evaluateJavaScript(arguments()[0]);
  addVariant(result);
  emit finished(new Response(true, m_buffer));
}
Exemple #18
0
int main(int argc, char* argv[])
{
   ossimInit::instance()->initialize(argc, argv);
   ossimString tempString;
   ossimString tempString2;
   osg::ArgumentParser::Parameter stringParam(tempString);
   osg::ArgumentParser::Parameter stringParam2(tempString2);
   
   osg::ArgumentParser arguments(&argc,argv);
   arguments.getApplicationUsage()->addCommandLineOption("--video", 
                                                         "specify the input video to process");
   arguments.getApplicationUsage()->addCommandLineOption("--animation-path-out", 
                                                         "specify the filename to output the animation path to");
   arguments.getApplicationUsage()->addCommandLineOption("--test-sensor-projection", 
                                                         "Test sensor projection from KlvInfo");
   unsigned int helpType = 0;
   if ((helpType = arguments.readHelpType()))
   {
      arguments.getApplicationUsage()->write(std::cout, helpType);
      return 1;
   }
   while(arguments.read("--video", stringParam))
   {
      if(arguments.read("--test-sensor-projection"))
      {
         ossimRefPtr<ossimPredatorUavProjection> proj = new ossimPredatorUavProjection;
         ossimRefPtr<ossimPredatorVideo> predatorVideo = new ossimPredatorVideo();
         
         if(predatorVideo->open(ossimFilename(tempString)))
         {
            ossim_uint32 imageWidth  = predatorVideo->imageWidth();
            ossim_uint32 imageHeight = predatorVideo->imageHeight();
            ossimRefPtr<ossimPredatorVideo::KlvInfo> klvinfo;
            ossim_float64 prevTime = -1.0;
            while(( klvinfo = predatorVideo->nextKlv()).valid())
            {
               ossim_float64 lat,lon,elev;
               ossim_float32 hfov;
               ossim_float32 vfov;
               ossim_float32 h,p,r;
               ossim_float32 obliquityAngle;
               ossim_float32 angleToNorth;
               ossim_float32 slantRange;
               ossim_float32 sensorRoll = 0.0;
               klvinfo->table()->print(std::cout) << std::endl;
               if(klvinfo->table()->getSensorPosition(lat, lon, elev)&&
                  klvinfo->table()->getPlatformOrientation(h,p,r))
               {
                  if(!klvinfo->table()->getObliquityAngle(obliquityAngle))
                  {
                     obliquityAngle = 0.0;
                  }
                  if(!klvinfo->table()->getSlantRange(slantRange))
                  {
                     slantRange = 1.0;
                  }
                  bool gotHfov = true;
                  if(!klvinfo->table()->getHorizontalFieldOfView(hfov))
                  {
                     hfov = 1.0;
                     gotHfov = false;
                  }
                  if(!klvinfo->table()->getVerticalFieldOfView(vfov))
                  {
                     vfov = hfov;
                  }
                  else if(!gotHfov)
                  {
                     hfov = vfov;
                  }
                  klvinfo->table()->getSensorRollAngle(sensorRoll);
                  if(!klvinfo->table()->getAngleToNorth(angleToNorth))
                  {
                     angleToNorth = 0.0;
                  }
                  ossim_float64 value = ossimGeoidManager::instance()->offsetFromEllipsoid(ossimGpt(lat, lon, elev));
                  if(!ossim::isnan(value))
                  {
                     elev += value;
                  }
                  proj->setParameters(imageWidth, 
                                      imageHeight, 
                                      ossimGpt(lat, lon, elev), 
                                      ossimGpt(), 
                                      h, p, sensorRoll,
                                      hfov,
                                      vfov,
                                      obliquityAngle,
                                      angleToNorth,
                                      0.0,
                                      0.0);
                  ossimDpt ipt(imageWidth*.5, imageHeight*.5);
                  ossimGpt centerProj;
                  ossimGpt ul;
                  ossimGpt ur;
                  ossimGpt lr;
                  ossimGpt ll;
                  proj->lineSampleToWorld(ipt, centerProj);
                  proj->lineSampleToWorld(ossimDpt(0,0), ul);
                  proj->lineSampleToWorld(ossimDpt(imageWidth,0), ur);
                  proj->lineSampleToWorld(ossimDpt(imageWidth,imageHeight), lr);
                  proj->lineSampleToWorld(ossimDpt(imageHeight,0), ll);
                  
                  std::cout << std::setprecision(15);
                  std::cout << "position = " << ossimGpt(lat, lon, elev) << std::endl;
                  std::cout << "centerGpt = " << centerProj << std::endl;
                  std::cout << "ul        = " << ul << std::endl;
                  std::cout << "ur        = " << ur << std::endl;
                  std::cout << "lr        = " << lr << std::endl;
                  std::cout << "ll        = " << ll << std::endl;
                  
//                  std::cout << "angle to north = " << angleToNorth << std::endl;
//                  std::cout << "ObliquityAngle = " << obliquityAngle << std::endl;
//                  std::cout << "hpr = " << h << ", " << p << ", " << r << std::endl;
//                  std::cout << "Platform  = " << ossimGpt(lat, lon, elev) << std::endl;
//                  std::cout << "World point = " << centerProj << std::endl;
                  if(klvinfo->table()->getFrameCenter(lat, lon, elev))
                  {
                     std::cout << "Center frame = " << ossimGpt(lat, lon, elev) << std::endl;
                  }
               }
            }
         }
      }
      
      if(arguments.read("--animation-path-out", stringParam2))
      {
         std::ofstream out(tempString2);
         if(out.good())
         {
            out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            out << "<AnimationPath>";
            out << "<GeospatialPath timeUnit='seconds' positionType='latlonhgt' orientationType='lsrhpr'>";
            out << "<description>Cool path</description>";
            out << "<coordinates>";
            
            ossimRefPtr<ossimPredatorVideo> predatorVideo = new ossimPredatorVideo();
            
            if(predatorVideo->open(ossimFilename(tempString)))
            {
               ossim_float32 srange;
               ossimRefPtr<ossimPredatorVideo::KlvInfo> klvinfo;
               ossim_float64 prevTime = -1.0;
               while(( klvinfo = predatorVideo->nextKlv()).valid())
               {
                  klvinfo->table()->getSlantRange(srange);
                  //std::cout << "range === " << srange << std::endl;
                  if(!ossim::almostEqual(klvinfo->time(), prevTime, 1e-10))
                  {
                     prevTime = klvinfo->time();
                     ossimString sensorLat, sensorLon, sensorAlt, h,p,r;
                     if(klvinfo->table()->valueAsString(sensorLat, KLV_KEY_SENSOR_LATITUDE)&&
                        klvinfo->table()->valueAsString(sensorLon, KLV_KEY_SENSOR_LONGITUDE)&&
                        klvinfo->table()->valueAsString(sensorAlt, KLV_KEY_SENSOR_TRUE_ALTITUDE))
                     {
                        klvinfo->table()->valueAsString(h,KLV_KEY_PLATFORM_HEADING_ANGLE);
                        klvinfo->table()->valueAsString(p,KLV_KEY_PLATFORM_PITCH_ANGLE);
                        klvinfo->table()->valueAsString(r,KLV_KEY_PLATFORM_ROLL_ANGLE);
                        
                        double headingAdjust = h.toDouble();
                        if(headingAdjust > 180.0) headingAdjust -= 360.0;
                        out << klvinfo->time() << "," 
                        << sensorLat <<"," << sensorLon << "," <<sensorAlt.toDouble()*0.304801 << ","
                        << headingAdjust << "," << p.toDouble() << "," << r.toDouble() <<std::endl;
                     }
                  }
               }
            }
            out << "</coordinates></GeospatialPath></AnimationPath>";
         }
      }
   }
}
Exemple #19
0
int main( int argc,
          char * argv[] )
{
    osg::ArgumentParser arguments( &argc, argv );
    osgViewer::Viewer viewer;
    viewer.setUpViewInWindow( 10, 30, 800, 600 );

    osgGA::TrackballManipulator * tb = new osgGA::TrackballManipulator();

    tb->setHomePosition( osg::Vec3( 5, -12, 12 ),
                        osg::Vec3( -7, 0, -10 ),
                        osg::Vec3( 0, 0, 1 ) );
    viewer.setCameraManipulator( tb );

    osg::ref_ptr< osg::Group > root = new osg::Group;
    viewer.setSceneData( root.get() );

    osgDB::getDataFilePathList().push_back( "C:\\OpenSceneGraph\\Data" );

    btDynamicsWorld * dynamicsWorld = initPhysics();

    root->addChild( createModel( dynamicsWorld ) );

    /* BEGIN: Create environment boxes */
    osg::MatrixTransform * ground;
    btRigidBody * groundBody;

    float thin = .01;
    ground = createOSGBox( osg::Vec3( 10, 10, thin ) );
    root->addChild( ground );
    groundBody = createBTBox( ground, osg::Vec3( 0, 0, -10 ) );
    dynamicsWorld->addRigidBody( groundBody );

    ground = createOSGBox( osg::Vec3( 10, thin, 5 ) );
    root->addChild( ground );
    groundBody = createBTBox( ground, osg::Vec3( 0, 10, -5 ) );
    dynamicsWorld->addRigidBody( groundBody );

    ground = createOSGBox( osg::Vec3( 10, thin, 5 ) );
    root->addChild( ground );
    groundBody = createBTBox( ground, osg::Vec3( 0, -10, -5 ) );
    dynamicsWorld->addRigidBody( groundBody );

    ground = createOSGBox( osg::Vec3( thin, 10, 5 ) );
    root->addChild( ground );
    groundBody = createBTBox( ground, osg::Vec3( 10, 0, -5 ) );
    dynamicsWorld->addRigidBody( groundBody );

    ground = createOSGBox( osg::Vec3( thin, 10, 5 ) );
    root->addChild( ground );
    groundBody = createBTBox( ground, osg::Vec3( -10, 0, -5 ) );
    dynamicsWorld->addRigidBody( groundBody );
    /* END: Create environment boxes */

    /* BEGIN: Create animated box */
    /* OSG Code */
    osg::MatrixTransform * box = createOSGBox( osg::Vec3( .3, .3, .3 ) );
    osg::AnimationPathCallback * apc = new osg::AnimationPathCallback( createAnimationPath( osg::Vec3( 0, 0, -9.25 ), 9.4, 6 ), 0, 1 );
    box->setUpdateCallback( apc );
    root->addChild( box );

    /* Bullet Code */
    btRigidBody * boxBody = createBTBox( box, osg::Vec3( -9, -3, -9 ) );
    boxBody->setCollisionFlags( boxBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT );
    boxBody->setActivationState( DISABLE_DEACTIVATION );
    dynamicsWorld->addRigidBody( boxBody );

    /* osgBullet Code */
    osgbCollision::RefBulletObject< btRigidBody >* boxRigid =
        new osgbCollision::RefBulletObject< btRigidBody >( boxBody );
    box->setUserData( boxRigid );

    osgbDynamics::RigidBodyAnimation * rba = new osgbDynamics::RigidBodyAnimation;
    apc->setNestedCallback( rba );
    /* END: Create animated box */

    // bonus geometry
    root->addChild( osgDB::readNodeFiles( arguments ) );

    double currSimTime = viewer.getFrameStamp()->getSimulationTime();;
    double prevSimTime = viewer.getFrameStamp()->getSimulationTime();
    viewer.realize();
    while( !viewer.done() )
    {
        currSimTime = viewer.getFrameStamp()->getSimulationTime();
        dynamicsWorld->stepSimulation( currSimTime - prevSimTime );
        prevSimTime = currSimTime;
        viewer.frame();
    }

    return( 0 );
}
Exemple #20
0
App::App(int &argc, char **argv)
: QApplication(argc, argv), d(new Data(this)) {
    if (QFile::exists(applicationDirPath() % "/bomi.ini"_a)) {
        QSettings set(applicationDirPath() % "/bomi.ini"_a, QSettings::IniFormat);
        d->useLocalConfig = set.value(u"app/use-local-config"_q, false).toBool();
        Global::useLocalConfig = set.value(u"global/use-local-config"_q, false).toBool();
        if (d->useLocalConfig != Global::useLocalConfig) {
            const auto from = _WritablePath(Location::Config, false);
            Global::useLocalConfig = d->useLocalConfig;
            const auto to = _WritablePath(Location::Config, false);
            d->copyConfig(from, to);
            set.setValue(u"global/use-local-config"_q, Global::useLocalConfig);
        }
    }

#ifdef Q_OS_LINUX
    setlocale(LC_NUMERIC,"C");
#endif

    OS::initialize();

    _New(d->parser);
    d->parser->addOption(LineCmd::Open, u"open"_q,
                         u"Open given %1 for file path or URL."_q, u"mrl"_q);
    d->parser->addOption(LineCmd::SetSubtitle, u"set-subtitle"_q,
                         u"Set subtitle file to display."_q, u"file"_q);
//    d->parser->addOption(LineCmd::AddSubtitle, u"add-subtitle"_q,
//                         u"Add subtitle file to display."_q, u"file"_q);
    d->parser->addOption(LineCmd::Wake, u"wake"_q,
                         u"Bring the application window in front."_q);
    d->parser->addOption(LineCmd::Action, u"action"_q,
                         u"Exectute %1 action or open %1 menu."_q, u"id"_q);
    d->parser->addOption(LineCmd::LogLevel, u"log-level"_q,
                         u"Maximum verbosity for log. %1 should be one of nexts:\n    "_q
                         % Log::levelNames().join(u", "_q), u"lv"_q);
    d->parser->addOption(LineCmd::Debug, u"debug"_q,
                         u"Turn on options for debugging."_q);
    d->parser->addOption(LineCmd::DumpApiTree, u"dump-api-tree"_q,
                         u"Dump API structure tree to stdout."_q);
    d->parser->addOption(LineCmd::DumpActionList, u"dump-action-list"_q,
                         u"Dump executable action list to stdout."_q);
#ifdef Q_OS_WIN
    d->parser->addOption(LineCmd::WinAssoc, u"win-assoc"_q,
                         u"Associate given comma-separated extension list."_q, u"ext"_q);
    d->parser->addOption(LineCmd::WinUnassoc, u"win-unassoc"_q,
                         u"Unassociate all extensions."_q);
    d->parser->addOption(LineCmd::WinAssocDefault, u"win-assoc-default"_q,
                         u"Associate default extensions."_q);
#endif
    d->parser->parse(arguments());
    d->gldebug = d->parser->isSet(LineCmd::Debug);
    const auto lvStdOut = d->parser->stdoutLogLevel();

    d->import();

    d->storage.setObject(this, u"application"_q);
    d->storage.add("locale", &d->locale);
    d->storage.json("log-option", &d->logOption);
    d->storage.add("style-name", &d->styleName);
    d->storage.add("unique", &d->unique);
    d->storage.add("open-folders", open_folders, set_open_folders);
    d->storage.add("font");
    d->storage.add("fixedFont");
    d->storage.restore();

    setLocale(d->locale);

    auto logOption = d->logOption;
    if (logOption.level(LogOutput::StdOut) < lvStdOut)
        logOption.setLevel(LogOutput::StdOut, lvStdOut);
    Log::setOption(logOption);

    setQuitOnLastWindowClosed(false);
#ifndef Q_OS_MAC
    setWindowIcon(defaultIcon());
#endif

    d->styleNames = [this] () {
        auto names = QStyleFactory::keys();
        const auto defaultName = style()->objectName();
        for (auto it = ++names.begin(); it != names.end(); ++it) {
            if (defaultName.compare(*it, Qt::CaseInsensitive) == 0) {
                const auto name = *it;
                names.erase(it);
                names.prepend(name);
                break;
            }
        }
        return names;
    }();
    auto makeStyle = [&]() {
        auto name = d->styleName;
        if (style()->objectName().compare(name, Qt::CaseInsensitive) == 0)
            return;
        if (!d->styleNames.contains(name, Qt::CaseInsensitive))
            return;
        setStyle(QStyleFactory::create(name));
    };
    makeStyle();
    connect(&d->connection, &LocalConnection::messageReceived,
            this, &App::handleMessage);
}
Exemple #21
0
int main(int argc, char *argv[]) {
  std::vector<std::string> history;
  int fd = STDIN_FILENO;
  struct termios savedAttribtes;
  int dir_len;
  char RXChar;
  std::string temp_hist;
  int curr_vec = -1;
  char back = 0x7F;

 //set non-canonical mode
  SetNonCanonicalMode(fd, &savedAttribtes);

  while(1){
    //shows the current directory at each command line
    dir_len = display_dir();

    while(1){
      read(fd, &RXChar, 1);
      if(0x0A == RXChar){ // newline
        write(STDOUT_FILENO, "\n", 1);
        break;
      }else if(0x04 == RXChar){
        return 0;
      }else if(0x7F == RXChar){
        if (temp_hist.length() == 0){
          write(STDOUT_FILENO, "\a", 1); //output bell
        }else{
          write(STDOUT_FILENO, &RXChar, 1);
          temp_hist.pop_back();
        }
      }else if(0x1B == RXChar){//first for up/down/delete
        read(fd, &RXChar, 1);
        if (0x5B == RXChar){ //2nd check for up/down/delete
          read(fd, &RXChar, 1);
          if(0x33 == RXChar){ //delete
            read(fd, &RXChar, 1);
            if (0x7E == RXChar){ //delete part 2
              if (temp_hist.length() == 0){
                write(STDOUT_FILENO, "\a", 1); //output bell
              }else{
                write(STDOUT_FILENO, &back, 1);
                temp_hist.pop_back();
              }
            }
          }

          if (0x41 == RXChar){ //up arrow
            if(curr_vec == 9 || (int)(history.size()) == 0 || curr_vec == (int)(history.size())-1){ //out of bounds
              write(STDOUT_FILENO, "\a", 1); //output bell
            }else{
              write(STDOUT_FILENO, "\r", 1); //return to beginning
              for (int i = 0; i < (int)(temp_hist.length())+dir_len; ++i){
                write(STDOUT_FILENO, " ", 1); //blank out what was there before
              }
              write(STDOUT_FILENO, "\r", 1); //return to beginning
              display_dir();
              curr_vec++;
              write(STDOUT_FILENO, history[curr_vec].c_str(), (int)(history[curr_vec].length()));
              temp_hist = history[curr_vec];
            }
          }else if (0x42 == RXChar){ //down arrow
            if(curr_vec == -1 || (int)(history.size()) == 0){ //out of bounds
              write(STDOUT_FILENO, "\a", 1); //output bell
            }
            else if(curr_vec == 0){ //wiping to blank
              write(STDOUT_FILENO, "\r", 1); //return to beginning
              for (int i = 0; i < (int)(temp_hist.length())+dir_len; ++i){
                write(STDOUT_FILENO, " ", 1); //blank out what was there before
              }
              write(STDOUT_FILENO, "\r", 1); //return to beginning
              display_dir();
              temp_hist = "";
              curr_vec --;
            }else{
              write(STDOUT_FILENO, "\r", 1); //return to beginning
              for (int i = 0; i < (int)(temp_hist.length()) + dir_len; ++i){
                write(STDOUT_FILENO, " ", 1); //blank out what was there before
              }
              write(STDOUT_FILENO, "\r", 1);
              display_dir();
              curr_vec--;
              write(STDOUT_FILENO, history[curr_vec].c_str(), (int)(history[curr_vec].length()));
              temp_hist = history[curr_vec];

            }
          }
        }
      }else{
        write(STDOUT_FILENO, &RXChar, 1);
        temp_hist.push_back(RXChar);
      }
    }

    if (temp_hist == "")
      continue;

    if(history.size() == 10)
      history.pop_back();

    history.insert(history.begin(), temp_hist); //load last entry into vector
    curr_vec = -1; //reset curr_vec

    bool temp_hist_bool;

    if(temp_hist.substr(temp_hist.size()- 1) == "&"){
      temp_hist_bool = true;
      temp_hist.pop_back();
    }else{
      temp_hist_bool = false;
    }

    std::stringstream ss(temp_hist);
    std::string item;
    std::vector<std::string> args;
    while (std::getline(ss, item, ' ')) {
      args.push_back(item);
    }
    temp_hist = ""; //reset temp_hist

    //check if command contains piping
    int pipecount = std::count(args.begin(), args.end(), "|");

    if(pipecount >0 || std::count(args.begin(), args.end(), "<") > 0 || std::count(args.begin(), args.end(), ">") > 0){
      pipeFunction(args, pipecount, history, temp_hist_bool);
      continue;
    }else if(args[0] == "pwd" || args[0] == "ls" || args[0] == "history") {
      call_fork(args, history, temp_hist_bool);
    }else if(args[0] == "cd") {
      if(args.size() > 1)
        cd(args[1].c_str());
      else
      	cd();
    }else if(args[0] == "exit") {
      break;
    }else{
      std::string command = "";
      command.append(args[0]);
      std::vector<char *> arguments(args.size() + 1);
      for(int i = 0; i < (int)args.size(); i++) {
        arguments[i] = &args[i][0];
      }

      //pid_t parent = getpid();
      pid_t pid = fork();

      if (pid == -1)
      {
          // error, failed to fork()
        write(STDOUT_FILENO, "Error\n", 6);
        exit(-1);
      }else if (pid > 0){
      	if (!temp_hist_bool)
      	{
      		int status;
        	wait(&status);
      	}
      }else{
        // we are the child
        execvp(command.c_str(), arguments.data());
        std::string error = "Failed to execute ";
        error += args[0] + "\n";
        //std::cout << error << std::endl;
        write(STDOUT_FILENO, error.c_str(), error.length());
        exit(-1);
      }
    }
  }
  ResetCanonicalMode(fd, &savedAttribtes);
  return 0;
}
int main( int argc, char** argv )
{
	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);
	// read the scene from the list of file specified command line arguments.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

	// if not loaded assume no arguments passed in, try use default cow model instead.
	if (!loadedModel) loadedModel = osgDB::readNodeFile("cow.osgt");

	// Still no loaded model, then exit
	if (!loadedModel) {
		osg::notify(osg::ALWAYS) << "No model could be loaded and didn't find cow.osgt, terminating.." << std::endl;
		return 0;
	}

	// Create Trackball manipulator
	osg::ref_ptr<osgGA::CameraManipulator> cameraManipulator = new osgGA::TrackballManipulator;
	const osg::BoundingSphere& bs = loadedModel->getBound();

	if (bs.valid()) {
		// Adjust view to object view
		osg::Vec3 modelCenter = bs.center();
		osg::Vec3 eyePos = bs.center() + osg::Vec3(0, bs.radius(), 0);
		cameraManipulator->setHomePosition(eyePos, modelCenter, osg::Vec3(0, 0, 1));
	}

	// Open the HMD
	float nearClip = 0.01f;
	float farClip = 10000.0f;
	float pixelsPerDisplayPixel = 1.0;
	bool useTimewarp = true;
	float worldUnitsPerMetre = 1.0f;
	osg::ref_ptr<OculusDevice> oculusDevice = new OculusDevice(nearClip, farClip, useTimewarp, pixelsPerDisplayPixel, worldUnitsPerMetre);

	// Get the suggested context traits
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = oculusDevice->graphicsContextTraits();

	// Create a graphic context based on our desired traits
	osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits);
	if (!gc) {
		osg::notify(osg::NOTICE) << "Error, GraphicsWindow has not been created successfully" << std::endl;
		return 1;
	}

	// Attach to window, needed for direct mode
	oculusDevice->attachToWindow(gc);

	if (gc.valid()) {
		gc->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
		gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	}

	osgViewer::Viewer viewer(arguments);
	viewer.getCamera()->setGraphicsContext(gc);
	viewer.getCamera()->setViewport(0, 0, traits->width, traits->height);

	// Disable automatic computation of near and far plane
	viewer.getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
	viewer.setCameraManipulator(cameraManipulator);
	viewer.realize();
	
	osg::ref_ptr<OculusViewer> oculusViewer = new OculusViewer(&viewer, oculusDevice);
	oculusViewer->addChild(loadedModel);
	viewer.setSceneData(oculusViewer);
	// Add statistics handler
	viewer.addEventHandler(new osgViewer::StatsHandler);
	// Add Oculus Keyboard Handler to only one view
	viewer.addEventHandler(new OculusEventHandler(oculusDevice));
	// Start Viewer
	viewer.run();
	return 0;
}
Exemple #23
0
AssignmentClientApp::AssignmentClientApp(int argc, char* argv[]) :
    QCoreApplication(argc, argv)
{
#   ifndef WIN32
    setvbuf(stdout, NULL, _IOLBF, 0);
#   endif

    // setup a shutdown event listener to handle SIGTERM or WM_CLOSE for us
#   ifdef _WIN32
    installNativeEventFilter(&ShutdownEventListener::getInstance());
#   else
    ShutdownEventListener::getInstance();
#   endif

    setOrganizationName("High Fidelity");
    setOrganizationDomain("highfidelity.io");
    setApplicationName("assignment-client");
    setApplicationName(BUILD_VERSION);

    // use the verbose message handler in Logging
    qInstallMessageHandler(LogHandler::verboseMessageHandler);

    // parse command-line
    QCommandLineParser parser;
    parser.setApplicationDescription("High Fidelity Assignment Client");
    parser.addHelpOption();

    const QCommandLineOption helpOption = parser.addHelpOption();

    const QCommandLineOption clientTypeOption(ASSIGNMENT_TYPE_OVERRIDE_OPTION,
                                              "run single assignment client of given type", "type");
    parser.addOption(clientTypeOption);

    const QCommandLineOption poolOption(ASSIGNMENT_POOL_OPTION, "set assignment pool", "pool-name");
    parser.addOption(poolOption);

    const QCommandLineOption walletDestinationOption(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION,
                                                     "set wallet destination", "wallet-uuid");
    parser.addOption(walletDestinationOption);

    const QCommandLineOption assignmentServerHostnameOption(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION,
                                                            "set assignment-server hostname", "hostname");
    parser.addOption(assignmentServerHostnameOption);

    const QCommandLineOption assignmentServerPortOption(CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION,
                                                        "set assignment-server port", "port");
    parser.addOption(assignmentServerPortOption);

    const QCommandLineOption numChildsOption(ASSIGNMENT_NUM_FORKS_OPTION, "number of children to fork", "child-count");
    parser.addOption(numChildsOption);

    const QCommandLineOption minChildsOption(ASSIGNMENT_MIN_FORKS_OPTION, "minimum number of children", "child-count");
    parser.addOption(minChildsOption);

    const QCommandLineOption maxChildsOption(ASSIGNMENT_MAX_FORKS_OPTION, "maximum number of children", "child-count");
    parser.addOption(maxChildsOption);

    const QCommandLineOption monitorPortOption(ASSIGNMENT_CLIENT_MONITOR_PORT_OPTION, "assignment-client monitor port", "port");
    parser.addOption(monitorPortOption);

    if (!parser.parse(QCoreApplication::arguments())) {
        qCritical() << parser.errorText() << endl;
        parser.showHelp();
        Q_UNREACHABLE();
    }

    if (parser.isSet(helpOption)) {
        parser.showHelp();
        Q_UNREACHABLE();
    }

    const QVariantMap argumentVariantMap = HifiConfigVariantMap::mergeCLParametersWithJSONConfig(arguments());

    unsigned int numForks = 0;
    if (parser.isSet(numChildsOption)) {
        numForks = parser.value(numChildsOption).toInt();
    }

    unsigned int minForks = 0;
    if (parser.isSet(minChildsOption)) {
        minForks = parser.value(minChildsOption).toInt();
    }

    unsigned int maxForks = 0;
    if (parser.isSet(maxChildsOption)) {
        maxForks = parser.value(maxChildsOption).toInt();
    }

    unsigned short monitorPort = 0;
    if (parser.isSet(monitorPortOption)) {
        monitorPort = parser.value(monitorPortOption).toUShort();
    }

    if (!numForks && minForks) {
        // if the user specified --min but not -n, set -n to --min
        numForks = minForks;
    }

    Assignment::Type requestAssignmentType = Assignment::AllTypes;
    if (argumentVariantMap.contains(ASSIGNMENT_TYPE_OVERRIDE_OPTION)) {
        requestAssignmentType = (Assignment::Type) argumentVariantMap.value(ASSIGNMENT_TYPE_OVERRIDE_OPTION).toInt();
    }
    if (parser.isSet(clientTypeOption)) {
        requestAssignmentType = (Assignment::Type) parser.value(clientTypeOption).toInt();
    }

    QString assignmentPool;
    // check for an assignment pool passed on the command line or in the config
    if (argumentVariantMap.contains(ASSIGNMENT_POOL_OPTION)) {
        assignmentPool = argumentVariantMap.value(ASSIGNMENT_POOL_OPTION).toString();
    }
    if (parser.isSet(poolOption)) {
        assignmentPool = parser.value(poolOption);
    }

    QUuid walletUUID;
    if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) {
        walletUUID = argumentVariantMap.value(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION).toString();
    }
    if (parser.isSet(walletDestinationOption)) {
        walletUUID = parser.value(walletDestinationOption);
    }

    QString assignmentServerHostname;
    if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) {
        assignmentServerHostname = argumentVariantMap.value(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION).toString();
    }
    if (parser.isSet(assignmentServerHostnameOption)) {
        assignmentServerHostname = parser.value(assignmentServerHostnameOption);
    }

    // check for an overriden assignment server port
    quint16 assignmentServerPort = DEFAULT_DOMAIN_SERVER_PORT;
    if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) {
        assignmentServerPort = argumentVariantMap.value(CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION).toString().toUInt();
    }
    
    if (parser.isSet(assignmentServerPortOption)) {
        assignmentServerPort = parser.value(assignmentServerPortOption).toInt();
    }

    if (parser.isSet(numChildsOption)) {
        if (minForks && minForks > numForks) {
            qCritical() << "--min can't be more than -n";
            parser.showHelp();
            Q_UNREACHABLE();
        }
        if (maxForks && maxForks < numForks) {
            qCritical() << "--max can't be less than -n";
            parser.showHelp();
            Q_UNREACHABLE();
        }
    }

    QThread::currentThread()->setObjectName("main thread");

    DependencyManager::registerInheritance<LimitedNodeList, NodeList>();

    if (numForks || minForks || maxForks) {
        AssignmentClientMonitor* monitor =  new AssignmentClientMonitor(numForks, minForks, maxForks,
                                                                        requestAssignmentType, assignmentPool,
                                                                        walletUUID, assignmentServerHostname,
                                                                        assignmentServerPort);
        monitor->setParent(this);
        connect(this, &QCoreApplication::aboutToQuit, monitor, &AssignmentClientMonitor::aboutToQuit);
    } else {
        AssignmentClient* client = new AssignmentClient(requestAssignmentType, assignmentPool,
                                                        walletUUID, assignmentServerHostname,
                                                        assignmentServerPort, monitorPort);
        client->setParent(this);
        connect(this, &QCoreApplication::aboutToQuit, client, &AssignmentClient::aboutToQuit);
    }
}
void Application::createQmlApp()
{
    loadSettings();

    engine.addImportPath("qrc:/qml/");

    connect(HardwareUtils::Instance(), SIGNAL(networkStatusChanged()),
            this, SLOT(networkStatusChanged()));
    connect(HardwareUtils::Instance(), SIGNAL(calaosServerDetected()),
            this, SLOT(calaosServerDetected()));

    connect(HardwareUtils::Instance(), &HardwareUtils::applicationWillResignActive, [=]()
    {
        qDebug() << "Application is in background, logout";
        startedWithOptHandled = false;
        logout();
    });

    connect(HardwareUtils::Instance(), &HardwareUtils::applicationBecomeActive, [=]()
    {
        qDebug() << "Application is in foreground, login again";
        QTimer::singleShot(0, [=]()
        {
            login(get_username(), get_password(), get_hostname());
        });
    });

    Common::registerQml();

#ifdef Q_OS_ANDROID
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
    QAndroidJniObject resource = activity.callObjectMethod("getResources","()Landroid/content/res/Resources;");
    QAndroidJniObject metrics = resource.callObjectMethod("getDisplayMetrics","()Landroid/util/DisplayMetrics;");
    update_density(metrics.getField<float>("density"));

    update_needBackButton(false);
    // Need to fix a bug on Android where text is scratched at runtime on some devices
    qputenv("QML_USE_GLYPHCACHE_WORKAROUND", QByteArray("1"));

    update_isAndroid(true);
    update_isIOS(false);
    update_isDesktop(false);
#else
    if (arguments().contains("--force-hdpi"))
        update_density(2.0);
    else
        update_density(1.0);

    update_needBackButton(true);

#ifdef Q_OS_IOS
    update_isAndroid(false);
    update_isIOS(true);
    update_isDesktop(false);
#else
    update_isAndroid(false);
    update_isIOS(false);
    update_isDesktop(true);
#endif
#endif

    update_applicationStatus(Common::NotConnected);

    calaosConnect = new CalaosConnection(this);
    connect(calaosConnect, SIGNAL(homeLoaded(QVariantMap)),
            this, SLOT(homeLoaded(QVariantMap)));
    connect(calaosConnect, SIGNAL(loginFailed()),
            this, SLOT(loginFailed()));
    connect(calaosConnect, &CalaosConnection::disconnected, [=]()
    {
        update_applicationStatus(Common::NotConnected);

#ifdef CALAOS_DESKTOP
        HardwareUtils::Instance()->showAlertMessage(tr("Network error"),
                                                    tr("The connection to calaos_server was lost."
                                                       "It will reconnect automatically when calaos_server"
                                                       "is available again."),
                                                    tr("Close"));

        //restart autologin, only on desktop to continually try to connect
        QTimer::singleShot(1000, [=]()
        {
            //reload settings in case it was changed
            loadSettings();
            login(get_username(), get_password(), get_hostname());
        });
#endif
    });

    scenarioModel = new ScenarioModel(&engine, calaosConnect, this);
    scenarioSortModel = new ScenarioSortModel(&engine, this);
    scenarioSortModel->setSourceModel(scenarioModel);
    engine.rootContext()->setContextProperty("scenarioModel", scenarioSortModel);
    lightOnModel = new LightOnModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("lightOnModel", lightOnModel);
    homeModel = new HomeModel(&engine, calaosConnect, scenarioModel, lightOnModel, this);
    engine.rootContext()->setContextProperty("homeModel", homeModel);
    audioModel = new AudioModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("audioModel", audioModel);
    favModel = new FavoritesModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("favoritesModel", favModel);
    favHomeModel = new HomeFavModel(&engine, calaosConnect, this);
    engine.rootContext()->setContextProperty("favoritesHomeModel", favHomeModel);
    cameraModel = new CameraModel(&engine, calaosConnect);
    engine.rootContext()->setContextProperty("cameraModel", cameraModel);

#ifdef CALAOS_DESKTOP
    CalaosWidgetModel::Instance()->loadFromDisk();
    engine.rootContext()->setContextProperty("widgetsModel", CalaosWidgetModel::Instance());
#endif

    engine.rootContext()->setContextProperty("calaosApp", this);

    //Register Units singleton
    //qmlRegisterSingletonType(QUrl("qrc:/qml/Units.qml"), "Units", 1, 0, "Units");

    qmlRegisterType<RoomFilterModel>("Calaos", 1, 0, "RoomFilterModel");

#if defined(CALAOS_MOBILE)
    engine.load(QUrl(QStringLiteral("qrc:///qml/mobile/main.qml")));
#elif defined(CALAOS_DESKTOP)
    engine.load(QUrl(QStringLiteral("qrc:///qml/desktop/main.qml")));
#else
#error "Unknown UI type!"
#endif

#ifndef CALAOS_DESKTOP
    //Start autologin, only on mobile. On desktop we wait for calaos_server detection
    QTimer::singleShot(100, [=]()
    {
        login(get_username(), get_password(), get_hostname());
    });
#endif
}
Exemple #25
0
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()->setDescription(arguments.getApplicationName()+" is the example which demonstrates ping pong rendering with FBOs and mutliple rendering branches. It uses Conway's Game of Life to illustrate the concept.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] --startim start_image");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--startim","The initial image to seed the game of life with.");

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    std::string startName("");
    while(arguments.read("--startim", startName)) {}

    if (startName == "") {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // load the image
    osg::ref_ptr<osg::Image> startIm = osgDB::readImageFile(startName);
   
    if (!startIm) {
        std::cout << "Could not load start image.\n";
        return(1);
    }

    osg::Node* scene = createScene(startIm.get());
    
    // construct the viewer.
    osgViewer::Viewer viewer;
    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    viewer.setSceneData(scene);

    viewer.realize();
    viewer.setCameraManipulator( new osgGA::TrackballManipulator );

    while(!viewer.done())
    {
        viewer.frame();
        // flip the textures after we've completed a frame
        golpass->flip();
        // attach the proper output to view
        geomss->setTextureAttributeAndModes(0, 
                                            golpass->getOutputTexture().get(),
                                            osg::StateAttribute::ON);
    }

    return 0;
}
Exemple #26
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setApplicationName("Imageset package manager");
    a.setApplicationVersion("1.0");

    const qint32 delay=3000;

    QCommandLineParser parser;
    parser.setApplicationDescription("This application look throw target folder and creates or refreshes .json file for package builder");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption addSizeset("a","Add sizeset","size");
    QCommandLineOption removeSizeset("r","Remove sizeset","size");
    QCommandLineOption dir("dir","Run for nested folders (assume provided location of multiple packages)");
    QCommandLineOption runningDelay("d",QString("Wait %1 ms before execution").arg(QString::number(delay)));
    parser.addOption(addSizeset);
    parser.addOption(removeSizeset);
    parser.addOption(dir);
    parser.addOption(runningDelay);

    parser.addPositionalArgument("target","Target folder containing source images");

    parser.process(a);

    if(parser.isSet(runningDelay)){
        QThread::msleep(delay);
    }

    QStringList arguments(parser.positionalArguments());
    if(arguments.size()!=1){
        return 1;
    }

    QStringList subfolders;
    if(parser.isSet(dir)){
        QDir sourceDir(arguments.at(0));
        subfolders=sourceDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    }else{
        subfolders<<".";
    }

    foreach(QString subfolder,subfolders){
        PackageManager package(arguments.at(0)+"/"+subfolder);
        if(!package.readData()){
            return 2;
        }

        QStringList sizesToRemove = parser.values(removeSizeset);
        if(!sizesToRemove.isEmpty()){
            foreach(QString size,sizesToRemove)package.removeSizeset(size);
        }
        QStringList sizesToAdd    = parser.values(addSizeset);
        if(!sizesToAdd.isEmpty()){
            foreach(QString size,sizesToAdd)package.addSizeset(size);
        }

        package.refreshPackage();

        if(!package.writeData()){
            return 3;
        }
    }
Exemple #27
0
// main
int main(int argc, char** argv)
{
	osg::ArgumentParser arguments(&argc, argv);

	// Let's use the convenience system from ALVAR for capturing.
	// We initialize Highgui through the CaptureFactory (see manual for other options like AVI)
	alvar::CaptureFactory *factory = alvar::CaptureFactory::instance();
    alvar::CaptureFactory::CaptureDeviceVector devices = factory->enumerateDevices("highgui");

    // Check to ensure that a device was found
    if (devices.size() > 0) {
        capture = factory->createCapture(devices.front());
    }

	// Capture is central feature, so if we fail, we get out of here.
	if (capture && capture->start()) {
	   
		// Let's capture one frame to get video resolution
		IplImage *tempImg = capture->captureImage();
		videoXRes = tempImg->width;
		videoYRes = tempImg->height;

		// Calibration. See manual and ALVAR internal samples how to calibrate your camera
		// Calibration will make the marker detecting and marker pose calculation more accurate.
		if (! camera.SetCalib("calib.xml", videoXRes, videoYRes)) {
			camera.SetRes(videoXRes, videoYRes);
		}

		//Create the osg::Image for the video
		videoImage = new osg::Image;

		//Create the osg::Image for the texture (marker hiding)
		texImage = new osg::Image;
		
		//IplImage for the texture generation.
		markerHiderImage=cvCreateImage(cvSize(64, 64), 8, 4);

		// construct the viewer
		viewer = new osgViewer::Viewer(arguments);
		// Let's use window size of the video (approximate).
		viewer->setUpViewInWindow (200, 200, videoXRes, videoYRes);
		// Viewport is the same
		viewer->getCamera()->setViewport(0,0,videoXRes,videoYRes);
		viewer->setLightingMode(osg::View::HEADLIGHT);

		// Attach our own event handler to the system so we can catch the resizing events
		viewer->addEventHandler(new CSimpleWndSizeHandler(videoXRes,videoYRes ));
		
		// Set projection matrix as ALVAR recommends (based on the camera calibration)
		double p[16];
		camera.GetOpenglProjectionMatrix(p,videoXRes,videoYRes);
		viewer->getCamera()->setProjectionMatrix(osg::Matrix(p));

		// Create main root for everything
		arRoot = new osg::Group;
		arRoot->setName("ALVAR stuff (c) VTT");
		
		// Init the video background class and add it to the graph
        videoBG.Init(videoXRes,videoYRes,(tempImg->origin?true:false));
		arRoot->addChild(videoBG.GetOSGGroup());

		// Create model switch and add it the to graph
		modelSwitch = new osg::Switch;
		arRoot->addChild(modelSwitch.get());

		// Create model transformation for the markers and add them under the switch
		mtForMarkerFive = new osg::MatrixTransform;
		mtForMarkerTen = new osg::MatrixTransform;
		modelSwitch->addChild(mtForMarkerFive.get());
		modelSwitch->addChild(mtForMarkerTen.get());

		// add the texture under the marker transformation node
		mtForMarkerFive->addChild(texOnMarker.GetDrawable());

		// All models off
		modelSwitch->setAllChildrenOff();

		// load the data (models).
		modelForMarkerFive = osgDB::readNodeFile("grid.osg");
		modelForMarkerTen = osgDB::readNodeFile("axes.osg");
	    
		// If loading ok, add models under the matrixtransformation nodes.
		if(modelForMarkerFive)
			mtForMarkerFive->addChild(modelForMarkerFive.get());

		if(modelForMarkerTen)
			mtForMarkerTen->addChild(modelForMarkerTen.get());
	    
		// Tell the ALVAR the markers' size (same to all)
		// You can also specify different size for each individual markers
		markerDetector.SetMarkerSize(MARKER_SIZE);

		// Set scene data 
		viewer->setSceneData(arRoot.get());

		// And start the main loop
		while(!viewer->done()){
			//Call the rendering function over and over again.
			renderer();
		}
	} 
	// Time to close the system
	if(capture){
		capture->stop();
		delete capture;
	}

	if(markerHiderImage)
		cvReleaseImage(&markerHiderImage);
	
	return 0; // bye bye. Happy coding!
}
//
// Executable code.
// Read from disk, evaluate properly, cache as indicated. The whole thing, so far.
//
void PolicyEngine::evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result,
	bool handleUnsignedCode /* = true */)
{
	FileQuarantine qtn(cfString(path).c_str());
	if (qtn.flag(QTN_FLAG_HARD))
		MacOSError::throwMe(errSecCSFileHardQuarantined);
	
	CFRef<SecStaticCodeRef> code;
	MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref()));
	OSStatus rc = noErr;	// last validation error
	
	const SecCSFlags validationFlags = kSecCSEnforceRevocationChecks;
	
	WhitelistPrescreen whitelistScreen(code); // pre-screening filter for whitelist pre-screening (only)

	SQLite::Statement query(*this,
		"SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority"
		" WHERE type = :type"
		" ORDER BY priority DESC;");
	query.bind(":type").integer(type);
	SQLite3::int64 latentID = 0;		// first (highest priority) disabled matching ID
	std::string latentLabel;			// ... and associated label, if any
	while (query.nextRow()) {
		bool allow = int(query[0]);
		const char *reqString = query[1];
		SQLite3::int64 id = query[2];
		const char *label = query[3];
		double expires = query[4];
		sqlite3_int64 ruleFlags = query[5];
		SQLite3::int64 disabled = query[6];
		const char *filter = query[7];
		const char *remarks = query[8];
		
		CFRef<SecRequirementRef> requirement;
		MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref()));
		rc = SecStaticCodeCheckValidity(code, validationFlags, requirement);
		
		// ad-hoc sign unsigned code, skip of Gatekeeper is off or the rule is disabled; but always do it for whitelist recording
		if (rc == errSecCSUnsigned && handleUnsignedCode && (!(disabled || overrideAssessment()) || SYSPOLICY_RECORDER_MODE_ENABLED())) {
			if (!SYSPOLICY_RECORDER_MODE_ENABLED()) {
				// apply whitelist pre-screening to speed things up for non-matches
				if (ruleFlags & kAuthorityFlagDefault)	// can't ever match standard rules with unsigned code
					continue;
				if (whitelistScreen.reject(filter, remarks))	// apply whitelist pre-filter
					continue;
			}
			try {
				// ad-hoc sign the code and attach the signature
				CFRef<CFDataRef> signature = CFDataCreateMutable(NULL, 0);
				CFTemp<CFDictionaryRef> arguments("{%O=%O, %O=#N}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity);
				CFRef<SecCodeSignerRef> signer;
				MacOSError::check(SecCodeSignerCreate(arguments, kSecCSDefaultFlags, &signer.aref()));
				MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags));
				MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags));
								
				// if we're in GKE recording mode, save that signature and report its location
				if (SYSPOLICY_RECORDER_MODE_ENABLED()) {
					int status = recorder_code_unable;	// ephemeral signature (not recorded)
					if (geteuid() == 0) {
						CFRef<CFUUIDRef> uuid = CFUUIDCreate(NULL);
						std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig";
						try {
							UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT);
							fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature));
							status = recorder_code_adhoc;	// recorded signature
							SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str());
						} catch (...) { }
					}

					// now report the D probe itself
					CFRef<CFDictionaryRef> info;
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
					CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
					SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "",
						cdhash ? CFDataGetBytePtr(cdhash) : NULL, status);
				}
				
				// rerun the validation to update state
				rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSBasicValidateOnly, requirement);
			} catch (...) { }
		}

		switch (rc) {
		case noErr: // well signed and satisfies requirement...
			break;	// ... continue below
		case errSecCSSignatureFailed:
			if (!codeInvalidityExceptions(code, result)) {
				if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
					SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, false);
				MacOSError::throwMe(rc);
			}
			if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
				SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, true);
			// treat as unsigned to fix problems in the field
		case errSecCSUnsigned:
			if (handleUnsignedCode) {
				cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
				addAuthority(result, "no usable signature");
			}
			return;
		case errSecCSReqFailed: // requirement missed, but otherwise okay
			continue;
		default: // broken in some way; all tests will fail like this so bail out
			MacOSError::throwMe(rc);
		}
		if (disabled) {
			if (latentID == 0) {
				latentID = id;
				if (label)
					latentLabel = label;
			}
			continue;	// the loop
		}
	
		CFRef<CFDictionaryRef> info;	// as needed
		if (flags & kSecAssessmentFlagRequestOrigin) {
			if (!info)
				MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
			if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
				setOrigin(chain, result);
		}
		if (!(ruleFlags & kAuthorityFlagInhibitCache) && !(flags & kSecAssessmentFlagNoCache)) {	// cache inhibit
			if (!info)
				MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
			if (SecTrustRef trust = SecTrustRef(CFDictionaryGetValue(info, kSecCodeInfoTrust))) {
				CFRef<CFDictionaryRef> xinfo;
				MacOSError::check(SecTrustCopyExtendedResult(trust, &xinfo.aref()));
				if (CFDateRef limit = CFDateRef(CFDictionaryGetValue(xinfo, kSecTrustExpirationDate))) {
					this->recordOutcome(code, allow, type, min(expires, dateToJulian(limit)), id);
				}
			}
		}
		if (allow) {
			if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) {
				if (!info)
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
				CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
				SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, cdhash ? CFDataGetBytePtr(cdhash) : NULL);
			}
		} else {
			if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
				if (!info)
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
				CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
				std::string cpath = cfString(path);
				const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
				SYSPOLICY_ASSESS_OUTCOME_DENY(cpath.c_str(), type, label, hashp);
				SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, label, hashp, recorder_code_untrusted);
			}
		}
		cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow);
		addAuthority(result, label, id);
		return;
	}

	if (rc == errSecCSUnsigned) {	// skipped all applicable rules due to pre-screening
		cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
		addAuthority(result, "no usable signature");
		return;
	}
	
	// no applicable authority (but signed, perhaps temporarily). Deny by default
	CFRef<CFDictionaryRef> info;
	MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
	if (flags & kSecAssessmentFlagRequestOrigin) {
		if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
			setOrigin(chain, result);
	}
	if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
		CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
		const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
		std::string cpath = cfString(path);
		SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath.c_str(), type, latentLabel.c_str(), hashp);
		SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, latentLabel.c_str(), hashp, 0);
	}
	if (!(flags & kSecAssessmentFlagNoCache))
		this->recordOutcome(code, false, type, this->julianNow() + NEGATIVE_HOLD, latentID);
	cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, false);
	addAuthority(result, latentLabel.c_str(), latentID);
}
int main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc, argv);

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

    // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        std::string pathfile;
        char keyForAnimationPath = '5';
        while (arguments.read("-p",pathfile))
        {
            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
            if (apm || !apm->valid())
            {
                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                keyswitchManipulator->selectMatrixManipulator(num);
                ++keyForAnimationPath;
            }
        }

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }


    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add the record camera path handler
    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);

    // attach an IncrementaCompileOperation to allow the master loading
    // to be handled with an incremental compile to avoid frame drops when large objects are added.
    viewer.setIncrementalCompileOperation(new osgUtil::IncrementalCompileOperation());

    double x = 0.0;
    double y = 0.0;
    double w = 1.0;
    double h = 1.0;

    unsigned int numLoadThreads = 1;
    while (arguments.read("--load-threads",numLoadThreads)) { }

    osg::ref_ptr<MasterOperation> masterOperation;
    std::string masterFilename;
    while(arguments.read("-m",masterFilename))
    {
        masterOperation = new MasterOperation(masterFilename, viewer.getIncrementalCompileOperation());
    }


    osg::ref_ptr<osgTerrain::TerrainTile> terrainTile = new osgTerrain::TerrainTile;
    osg::ref_ptr<osgTerrain::Locator> locator = new osgTerrain::Locator;
    osg::ref_ptr<osgTerrain::ValidDataOperator> validDataOperator = new osgTerrain::NoDataValue(0.0);
    osg::ref_ptr<osgTerrain::Layer> lastAppliedLayer;

    locator->setCoordinateSystemType(osgTerrain::Locator::GEOCENTRIC);
    locator->setTransformAsExtents(-osg::PI, -osg::PI*0.5, osg::PI, osg::PI*0.5);

    unsigned int layerNum = 0;

    std::string filterName;

    osg::Texture::FilterMode filter = osg::Texture::LINEAR;

    float minValue, maxValue;
    float scale = 1.0f;
    float offset = 0.0f;

    int pos = 1;
    while(pos<arguments.argc())
    {
        std::string filename;

        if (arguments.read(pos, "--layer",layerNum))
        {
            osg::notify(osg::NOTICE)<<"Set layer number to "<<layerNum<<std::endl;
        }

        else if (arguments.read(pos, "-b"))
        {
            terrainTile->setTreatBoundariesToValidDataAsDefaultValue(true);
        }

        else if (arguments.read(pos, "-e",x,y,w,h))
        {
            // define the extents.
            locator->setCoordinateSystemType(osgTerrain::Locator::GEOCENTRIC);
            locator->setTransformAsExtents(x,y,x+w,y+h);
        }

        else if (arguments.read(pos, "--transform",offset, scale) || arguments.read(pos, "-t",offset, scale))
        {
            // define the extents.
        }

        else if (arguments.read(pos, "--cartesian",x,y,w,h))
        {
            // define the extents.
            locator->setCoordinateSystemType(osgTerrain::Locator::PROJECTED);
            locator->setTransformAsExtents(x,y,x+w,y+h);
        }

        else if (arguments.read(pos, "--hf",filename))
        {
            osg::notify(osg::NOTICE)<<"--hf "<<filename<<std::endl;

            osg::ref_ptr<osg::HeightField> hf = osgDB::readRefHeightFieldFile(filename);
            if (hf.valid())
            {
                osg::ref_ptr<osgTerrain::HeightFieldLayer> hfl = new osgTerrain::HeightFieldLayer;
                hfl->setHeightField(hf.get());

                hfl->setLocator(locator.get());
                hfl->setValidDataOperator(validDataOperator.get());
                hfl->setMagFilter(filter);

                if (offset!=0.0f || scale!=1.0f)
                {
                    hfl->transform(offset,scale);
                }

                terrainTile->setElevationLayer(hfl.get());

                lastAppliedLayer = hfl.get();

                osg::notify(osg::NOTICE)<<"created osgTerrain::HeightFieldLayer"<<std::endl;
            }
            else
            {
                osg::notify(osg::NOTICE)<<"failed to create osgTerrain::HeightFieldLayer"<<std::endl;
            }

            scale = 1.0f;
            offset = 0.0f;

        }

        else if (arguments.read(pos, "-d",filename) || arguments.read(pos, "--elevation-image",filename))
        {
            osg::notify(osg::NOTICE)<<"--elevation-image "<<filename<<std::endl;

            osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(filename);
            if (image.valid())
            {
                osg::ref_ptr<osgTerrain::ImageLayer> imageLayer = new osgTerrain::ImageLayer;
                imageLayer->setImage(image.get());
                imageLayer->setLocator(locator.get());
                imageLayer->setValidDataOperator(validDataOperator.get());
                imageLayer->setMagFilter(filter);

                if (offset!=0.0f || scale!=1.0f)
                {
                    imageLayer->transform(offset,scale);
                }

                terrainTile->setElevationLayer(imageLayer.get());

                lastAppliedLayer = imageLayer.get();

                osg::notify(osg::NOTICE)<<"created Elevation osgTerrain::ImageLayer"<<std::endl;
            }
            else
            {
                osg::notify(osg::NOTICE)<<"failed to create osgTerrain::ImageLayer"<<std::endl;
            }

            scale = 1.0f;
            offset = 0.0f;

        }

        else if (arguments.read(pos, "-c",filename) || arguments.read(pos, "--image",filename))
        {
            osg::notify(osg::NOTICE)<<"--image "<<filename<<" x="<<x<<" y="<<y<<" w="<<w<<" h="<<h<<std::endl;

            osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(filename);
            if (image.valid())
            {
                osg::ref_ptr<osgTerrain::ImageLayer> imageLayer = new osgTerrain::ImageLayer;
                imageLayer->setImage(image.get());
                imageLayer->setLocator(locator.get());
                imageLayer->setValidDataOperator(validDataOperator.get());
                imageLayer->setMagFilter(filter);

                if (offset!=0.0f || scale!=1.0f)
                {
                    imageLayer->transform(offset,scale);
                }

                terrainTile->setColorLayer(layerNum, imageLayer.get());

                lastAppliedLayer = imageLayer.get();

                osg::notify(osg::NOTICE)<<"created Color osgTerrain::ImageLayer"<<std::endl;
            }
            else
            {
                osg::notify(osg::NOTICE)<<"failed to create osgTerrain::ImageLayer"<<std::endl;
            }

            scale = 1.0f;
            offset = 0.0f;

        }

        else if (arguments.read(pos, "--filter",filterName))
        {
            if (filterName=="NEAREST")
            {
                osg::notify(osg::NOTICE)<<"--filter "<<filterName<<std::endl;
                filter = osg::Texture::NEAREST;
            }
            else if (filterName=="LINEAR")
            {
                filter = osg::Texture::LINEAR;
                osg::notify(osg::NOTICE)<<"--filter "<<filterName<<std::endl;
            }
            else
            {
                osg::notify(osg::NOTICE)<<"--filter "<<filterName<<" unrecognized filter name, please use LINEAER or NEAREST."<<std::endl;
            }

            if (terrainTile->getColorLayer(layerNum))
            {
                terrainTile->getColorLayer(layerNum)->setMagFilter(filter);
            }

        }

        else if (arguments.read(pos, "--tf",minValue, maxValue))
        {
            osg::ref_ptr<osg::TransferFunction1D> tf = new osg::TransferFunction1D;

            unsigned int numCells = 6;
            float delta = (maxValue-minValue)/float(numCells-1);
            float v = minValue;

            tf->allocate(6);
            tf->setColor(v, osg::Vec4(1.0,1.0,1.0,1.0)); v += delta;
            tf->setColor(v, osg::Vec4(1.0,0.0,1.0,1.0)); v += delta;
            tf->setColor(v, osg::Vec4(1.0,0.0,0.0,1.0)); v += delta;
            tf->setColor(v, osg::Vec4(1.0,1.0,0.0,1.0)); v += delta;
            tf->setColor(v, osg::Vec4(0.0,1.0,1.0,1.0)); v += delta;
            tf->setColor(v, osg::Vec4(0.0,1.0,0.0,1.0));

            osg::notify(osg::NOTICE)<<"--tf "<<minValue<<" "<<maxValue<<std::endl;

            terrainTile->setColorLayer(layerNum, new osgTerrain::ContourLayer(tf.get()));
        }
        else
        {
            ++pos;
        }

    }


    osg::ref_ptr<osg::Group> scene = new osg::Group;

    if (terrainTile.valid() && (terrainTile->getElevationLayer() || terrainTile->getColorLayer(0)))
    {
        osg::notify(osg::NOTICE)<<"Terrain created"<<std::endl;

        scene->addChild(terrainTile.get());

        osg::ref_ptr<osgTerrain::GeometryTechnique> geometryTechnique = new osgTerrain::GeometryTechnique;
        terrainTile->setTerrainTechnique(geometryTechnique.get());
        viewer.addEventHandler(new FilterHandler(geometryTechnique.get()));
        viewer.addEventHandler(new LayerHandler(lastAppliedLayer.get()));
    }

    if (masterOperation.valid())
    {
        osg::notify(osg::NOTICE)<<"Master operation created"<<std::endl;

        masterOperation->open(scene.get());
    }

    if (scene->getNumChildren()==0)
    {
        osg::notify(osg::NOTICE)<<"No model created, please specify terrain or master file on command line."<<std::endl;
        return 0;
    }

    viewer.setSceneData(scene.get());


    // start operation thread if a master file has been used.
    osg::ref_ptr<osg::OperationThread> masterOperationThread;

    typedef std::list< osg::ref_ptr<osg::OperationThread> > OperationThreadList;
    OperationThreadList generalThreadList;

    if (masterOperation.valid())
    {
        masterOperationThread = new osg::OperationThread;
        masterOperationThread->startThread();

        masterOperationThread->add(masterOperation.get());

//        if (numLoadThreads>0)
        {
            osg::ref_ptr<osg::OperationQueue> operationQueue = new osg::OperationQueue;
            masterOperation->setOperationQueue(operationQueue.get());

            for(unsigned int i=0; i<numLoadThreads; ++i)
            {
                osg::ref_ptr<osg::OperationThread> thread = new osg::OperationThread;
                thread->setOperationQueue(operationQueue.get());
                thread->startThread();
                generalThreadList.push_back(thread);
            }
        }

        viewer.addUpdateOperation(masterOperation.get());
    }

    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);

    // enable the use of compile contexts and associated threads.
    // osg::DisplaySettings::instance()->setCompileContextsHint(true);

    // realize the graphics windows.
    viewer.realize();

    // run the viewers main loop
    return viewer.run();

}
nsresult
nsPrintingPromptService::DoDialog(nsIDOMWindow *aParent,
                                  nsIDialogParamBlock *aParamBlock, 
                                  nsIWebBrowserPrint *aWebBrowserPrint, 
                                  nsIPrintSettings* aPS,
                                  const char *aChromeURL)
{
    NS_ENSURE_ARG(aParamBlock);
    NS_ENSURE_ARG(aPS);
    NS_ENSURE_ARG(aChromeURL);

    if (!mWatcher)
        return NS_ERROR_FAILURE;

    nsresult rv = NS_OK;

    // get a parent, if at all possible
    // (though we'd rather this didn't fail, it's OK if it does. so there's
    // no failure or null check.)
    nsCOMPtr<nsIDOMWindow> activeParent; // retain ownership for method lifetime
    if (!aParent) 
    {
        mWatcher->GetActiveWindow(getter_AddRefs(activeParent));
        aParent = activeParent;
    }

    // create a nsISupportsArray of the parameters 
    // being passed to the window
    nsCOMPtr<nsISupportsArray> array;
    NS_NewISupportsArray(getter_AddRefs(array));
    if (!array) return NS_ERROR_FAILURE;

    nsCOMPtr<nsISupports> psSupports(do_QueryInterface(aPS));
    NS_ASSERTION(psSupports, "PrintSettings must be a supports");
    array->AppendElement(psSupports);

    if (aWebBrowserPrint) {
      nsCOMPtr<nsISupports> wbpSupports(do_QueryInterface(aWebBrowserPrint));
      NS_ASSERTION(wbpSupports, "nsIWebBrowserPrint must be a supports");
      array->AppendElement(wbpSupports);
    }

    nsCOMPtr<nsISupports> blkSupps(do_QueryInterface(aParamBlock));
    NS_ASSERTION(blkSupps, "IOBlk must be a supports");
    array->AppendElement(blkSupps);

    nsCOMPtr<nsISupports> arguments(do_QueryInterface(array));
    NS_ASSERTION(array, "array must be a supports");


    nsCOMPtr<nsIDOMWindow> dialog;
    rv = mWatcher->OpenWindow(aParent, aChromeURL, "_blank",
                              "centerscreen,chrome,modal,titlebar", arguments,
                              getter_AddRefs(dialog));

    // if aWebBrowserPrint is not null then we are printing
    // so we want to pass back NS_ERROR_ABORT on cancel
    if (NS_SUCCEEDED(rv) && aWebBrowserPrint) 
    {
        PRInt32 status;
        aParamBlock->GetInt(0, &status);
        return status == 0?NS_ERROR_ABORT:NS_OK;
    }

    return rv;
}