Exemplo n.º 1
0
void CullSettings::readCommandLine(ArgumentParser& arguments)
{
    // report the usage options.
    if (arguments.getApplicationUsage())
    {
        arguments.getApplicationUsage()->addCommandLineOption("--COMPUTE_NEAR_FAR_MODE <mode>","DO_NOT_COMPUTE_NEAR_FAR | COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES | COMPUTE_NEAR_FAR_USING_PRIMITIVES");
        arguments.getApplicationUsage()->addCommandLineOption("--NEAR_FAR_RATIO <float>","Set the ratio between near and far planes - must greater than 0.0 but less than 1.0.");
    }

    std::string str;
    while(arguments.read("--COMPUTE_NEAR_FAR_MODE",str))
    {
        if (str=="DO_NOT_COMPUTE_NEAR_FAR") _computeNearFar = DO_NOT_COMPUTE_NEAR_FAR;
        else if (str=="COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES") _computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
        else if (str=="COMPUTE_NEAR_FAR_USING_PRIMITIVES") _computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;

        OSG_NOTIFY(osg::INFO)<<"Set compute near far mode to "<<_computeNearFar<<std::endl;
    }

    double value;
    while(arguments.read("--NEAR_FAR_RATIO",value))
    {
        _nearFarRatio = value;

        OSG_NOTIFY(osg::INFO)<<"Set near/far ratio to "<<_nearFarRatio<<std::endl;
    }

}
Exemplo n.º 2
0
int main(int argc, char **argv)
{
  QCoreApplication app(argc, argv);

  ArgumentParser parser;
  QTextStream out(stdout);

  parser.next();    // eat the program name
  if (!parser.hasNext()) {
    showHelp(out);
    return 0;
  }

  try {
    Engine eng;

    commandWebExport(out, parser);
  }
  catch (ArgumentParser::HelpException &) {
    showHelp(out);
    return 0;
  }
  catch (ArgumentParser::Exception &e){
    showError(out, e);
    return 1;
  }

  return 0;
}
int main(int argc, char* argv[])
{
	Config* config = Config::getConfig();
	ArgumentParser argParser;
	if(!argParser.parseArgs(argc, argv))
	{
		argParser.printUsage();
		return 1;
	}
	if(config->rtPrio)
	{
		PrioritySwitcher prioSwitcher(config->fifoScheduling);
		if(prioSwitcher.switchToRealtimePriority() != 0)
		{
			Logger::ERROR("Switching to realtime priority failed, maybe not running as root?");
			return 1;
		}
	}
	ros::init(argc, argv, "communication_tests_subscriber");
	config->nodeHandle = new ros::NodeHandle();
	Subscriber subscriber("communication_tests");
	subscriber.startMeasurement();
	subscriber.printMeasurementResults();
	subscriber.saveGnuplotData();
	return 0;
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
    ArgumentParser argParser;
    if(!argParser.parseArgs(argc, argv))
    {
        Logger::ERROR("Invalid arguments provided!");
        Logger::ERROR(argParser.getUsage());
        return 1;
    }
    Config* config = Config::getConfig();
    config->testnodePrioritySwitcher = new PrioritySwitcher(0, config->fifoScheduling);
    if(!setProcessPriority())
    {
        Logger::ERROR("Couldn't set priority appropriately, maybe not running as root?");
        return 1;
    }
    ros::init(argc, argv, "oneshot_timer_tests");
    config->nodeHandle = new ros::NodeHandle;
    Logger::INFO("Performing ROS Timer latency measurements...");
    OneShotLatencyMeasurer* measurer;
    if(config->busyMode)
    {
        Logger::INFO("Running in busy mode");
        measurer = new BusyOneShotLatencyMeasurer();
    } else {
        Logger::INFO("Running in default mode");
        measurer = new IdleOneShotLatencyMeasurer();
    }
    measurer->measure();
    measurer->printMeasurementResults();
    measurer->saveMeasuredLatencyGnuplotData();
    return 0;
}
Exemplo n.º 5
0
int 
ArgumentParserTest::testStringMatch(){
  int retval = 0;

  char *argv[2] = {
    "-stringArg",
    "someString",
  };

  ArgumentParser *toTest = getDefaultArgumentParser();
  vector<string> argVec = ArgumentParser::vectorifyArguments( 2, argv, false );
  if( argVec[0] != "-stringArg" || argVec[1] != "someString" ){
    retval = 1;
    goto end;
  }
  toTest->checkArgs( argVec );
  if( stringArg != "someString" ){
    retval = 1;
    goto end;
  }
  if( argVec.size() > 0 ){
    retval = 1;
    goto end;
  }

 end:
  return retval;
}
Exemplo n.º 6
0
int 
ArgumentParserTest::testNoneMatch(){
  int retval = 0;

  char *argv[4] = {
    "the",
    "quick",
    "brown",
    "fox"
  };

  ArgumentParser *toTest = getDefaultArgumentParser();
  vector<string> argVec = ArgumentParser::vectorifyArguments( 4, argv, false );
  if( argVec[0] != "the" ||
      argVec[1] != "quick" ||
      argVec[2] != "brown" ||
      argVec[3] != "fox" ){
    retval = 1;
    goto end;
  }
  toTest->checkArgs( argVec );
  
  if( boolArg != false || intArg != 0 || stringArg != ""  ){
    retval = 1;
    goto end;
  }
  
  if( argVec.size() != 4 ){
    retval = 1;
    goto end;
  }

 end:
  return retval;
}
Exemplo n.º 7
0
int 
ArgumentParserTest::testMultiple(){
int retval = 0;
  char *argv[5] = {
    "-stringArg",
    "someString2",
    "-intArg",
    "12",
    "shouldnotmatch",
  };

  ArgumentParser *toTest = getDefaultArgumentParser();
  vector<string> argVec = ArgumentParser::vectorifyArguments( 5, argv, false );
  if( argVec[0] != "-stringArg" || argVec[1] != "someString2" ||
      argVec[2] != "-intArg" || argVec[3] != "12" || 
      argVec[4] != "shouldnotmatch"  ){
    retval = 1;
    goto end;
  }
  toTest->checkArgs( argVec );
  if( argVec.size() != 1 || argVec[0] != "shouldnotmatch" ){
    retval = 1;
    goto end;
  }
  if( stringArg != "someString2" || intArg != 12 ){
    retval = 1;
    goto end;
  }

 end:
  return retval;
}
Exemplo n.º 8
0
int 
ArgumentParserTest::testBoolMatch(){
  int retval = 0;

  char *argv[1] = {
    "-boolArg",
  };

  ArgumentParser *toTest = getDefaultArgumentParser();
  vector<string> argVec = ArgumentParser::vectorifyArguments( 1, argv, false );
  if( argVec[0] != "-boolArg" ){
    retval = 1;
    goto end;
  }
  toTest->checkArgs( argVec );
  if( boolArg != true ){
    retval = 1;
    goto end;
  }
  if( argVec.size() > 0 ){
    retval = 1;
    goto end;
  }

 end:
  return retval;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
  initArgs();
  args.parseArgs(argc, argv);

  TypeVec types = getTypes();
  SquareSelector<double> coordCutoffs = getCoordCutoffs(types);
  Atom *atoms;

  if (args.getStandaloneCount() != 1)
  {
    cerr << "no input file. See --help for help" << endl;
    exit(1);
  }

  const char *filename = args.getCStandalone(0);
  const double globalCutoff = args.getDouble("cutoff");

  double *spaceSize = NULL;

  int numatoms = readFile(filename, &types, &atoms, &spaceSize);
  saveAtomTypes(types);
  writeInteratomics(atoms, numatoms, globalCutoff, types, spaceSize,
    coordCutoffs);

  if (spaceSize)
  {
    delete[] spaceSize;
    spaceSize = NULL;
  }

  return 0;
}
Exemplo n.º 10
0
long getSeed(const ArgumentParser &args){//{{{
   long seed;
   if(args.isSet("seed"))seed=args.getL("seed");
   else seed = time(NULL);
   if(args.verbose)message("seed: %ld\n",seed);
   return seed;
}//}}}
Exemplo n.º 11
0
int
main(int argc, char **argv)
{
  ArgumentParser *argp = new ArgumentParser(argc, argv, "arlsh");

  if ( argp->has_arg("h") ) {
    cout << "Usage: " << argv[0] << "[-r] [-h] [-s] [-l] [-a]" << endl
	 << " -r   receiver (sender otherwise)" << endl
	 << " -h   this help message" << endl
	 << " -s   single per recv, only process a single message per recv()" << endl
#ifdef HAVE_AVAHI
	 << " -a   enable Avahi for mDNS lookup" << endl
#else
	 << " -a   not available (Avahi not installed)" << endl
#endif
	 << " -l   enable multicast loop back" << endl;
    return 0;
  }

  WorldInfoQAMain m(argp);
  SignalManager::register_handler(SIGINT, &m);
  SignalManager::ignore(SIGPIPE);

  m.run();

  SignalManager::finalize();

  delete argp;
  return 0;
}
Exemplo n.º 12
0
int main(int argc, char *argv[]) {
    ArgumentParser ap;
    ap.parse_args(argc, argv);

    initialize_dash_dirs();

    if (ap.index) {
        if (ap.genome == "" || ap.seed_len <= 0 || ap.threads <= 0) {
            parse_error(ap);
        } else {
            indexer(ap.genome, ap.seed_len, ap.threads);
        }
    }
    else if (ap.align) {
        if (ap.out == "" || ap.in == "" || ap.threads <= 0 || ap.edit_dist < 0 \
                || ap.conf <= 0 ) {
            parse_error(ap);
        } else {
            aligner(ap.in, ap.out, ap.threads, ap.edit_dist, ap.conf);
        }
    }
    else {
        parse_error(ap);
    }
    return 0;
}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
    ArgumentParser parser;
    parser.addArgument("-i", "--input", 1, false);
    parser.parse(argc, argv);
    TApplication *myapp = new TApplication("App", &argc, argv);
    fit(parser.retrieve<string>("i"));
    myapp->Run();
}
Exemplo n.º 14
0
void initArgs()
{
  args.Double("cutoff", 10.0, "global cutoff distance", 'c');
  args.String("species", "",
    "atomic species. Optional, but necessary for specific interatomic cutoffs",
    's');
  args.String("coordinationCutoffs", "",
    "cutoff distances between types. Handled as a line-representation of a matrix, i.e. species \"A B\" results in \"AA AB BA BB\". Requires species to be set.",
    'C');

  args.Standalones(1, "input.xyz",
    "xyz file containing the atomic positions to analyze. Please note that only the first dataset of the file is considered.");
}
Exemplo n.º 15
0
bool openOutput(const ArgumentParser &args, ofstream *outF){//{{{
   outF->open(args.getS("outFileName").c_str());
   if(!outF->is_open()){
      error("Main: Output file open failed.\n");
      return false;
   }
   return true;
}//}}}
Exemplo n.º 16
0
string getOutputType(const ArgumentParser &args, const string &defaultType){ //{{{
   string type = ns_misc::toLower(args.getS("outputType"));
   if((type!="theta") && (type!="rpkm") && (type!="counts") && (type!="tau")){
      type = defaultType;
      warning("Using output type %s.",type.c_str());
   }
   return type;
} //}}}
Exemplo n.º 17
0
   /**
    * @brief parseOptions parse user arguments
    */
   UserOptions parseOptions(const int argc, const char* argv[]) {
      UserOptions user_options;

      vector<string> arguments;
      for (const size_t argn : crange(argc))
         arguments.push_back(argv[argn]);

      // Parse arguments
      ArgumentParser parser;
      user_options = parser.parseArguments(arguments);
      user_options.addDefaultFiles();

      if (user_options.use_textfile) {
         output_streamer.createStreamFile(results_str, user_options.datatext_file);
      }

      return user_options;
   }
Exemplo n.º 18
0
bool readConditions(const ArgumentParser &args, long *C, long *M, long *N, Conditions *cond){//{{{
   if(! cond->init("NONE", args.args(), C, M, N)){
      error("Main: Failed loading MCMC samples.\n");
      return false;
   }
   if(args.isSet("normalization")){
      if(! cond->setNorm(args.getTokenizedS2D("normalization"))){
         error("Main: Applying normalization constants failed.\n");
         return false;
      }
   }
   if(!cond->logged() && args.verb()){
      message("Samples are not logged. (will log for you)\n");
      message("Using %lg as minimum instead of log(0).\n",LOG_ZERO);
   }
   if(args.verb())message("Files with samples loaded.\n");
   return true;
}//}}}
Exemplo n.º 19
0
TypeVec getTypes()
{
  TypeVec types;
  // init types with predefined species (if any)
  vector<string> species = strsplit(args.getCString("species"));
  for (size_t i = 0; i < species.size(); ++i)
  {
    types.push_back(Type(species[i].c_str(), types.size()));
  }

  return types;
}
Exemplo n.º 20
0
int main(int argc, char* argv[]){
    ArgumentParser parser;
    parser.parse_args(argc, argv);

    if ( argc != 2 ){
        printf("usage: DisplayImage.out <Image_Path>\n");
        return -1;
    }

    Mat image;
    image = imread( argv[1], 1 );

    if (!image.data){
        printf("No image data \n");
        return -1;
    }
    namedWindow("Display Image", WINDOW_AUTOSIZE );
    imshow("Display Image", image);

    return 0;
}
Exemplo n.º 21
0
int Command::run(std::vector<std::string> arguments, std::ostream *errorStream) {
    vector<Argument> parsedArguments;
    vector<string> values;
    
    if (arguments.size() > 0) {
        if (_subcommands.size() > 0) {
            // Check for subcommands
            for (auto it = _subcommands.begin(); it != _subcommands.end(); ++it) {
                if (arguments[0] == it->name()) {
                    // Remove first argument (=command)
                    arguments.erase(arguments.begin());
                    
                    // Set pointer to sender
                    it->setParentCommand(this);
                    
                    return it->run(arguments);
                }
            }
            
            // Show error
            *errorStream << "Error: Invalid command: " << arguments[0] << endl;
            
            return EXIT_FAILURE;
        }
        
        // Parse arguments
        ArgumentParser parser;
        if (!parser.parse(arguments, _options, parsedArguments, values)) {
            return EXIT_FAILURE;
        }
    }
    
    // Run command
    if (_action) {
        _action(Context(this, parsedArguments, values));
    }
    
    return EXIT_SUCCESS;
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(qtmindmap);

    QApplication a(argc, argv);

    // translation
    QString locale = QLocale::system().name();
    QTranslator translator;
    if (locale != "C" && !translator.load(
                QString("/usr/share/qtmindmap/i18n/qtmindmap_") + locale))
    {
        std::cerr << "No translation file for locale: "
                  << locale.toStdString()
                  << std::endl;
    }
    else
    {
        a.installTranslator(&translator);
    }

    // parse args
    ArgumentParser argParser;
    if (!argParser.parseCmdLineArgs())
        return EXIT_FAILURE;

    // system tray?
    MainWindow w;
    SystemTray *systemtray;
    if (argParser.isSystemTray() or argParser.isShowMinimized())
    {
        if (!QSystemTrayIcon::isSystemTrayAvailable())
        {
            QMessageBox::critical(0,
              QObject::tr("QtMindMap Error"),
              QObject::tr("I couldn't detect any system tray on this system."));
            return EXIT_FAILURE;
        }
        QApplication::setQuitOnLastWindowClosed(false);
        systemtray = new SystemTray(&w);
        systemtray->show();
    }

    // open file if any
    if (!argParser.filePath().isEmpty())
        w.openFile(argParser.filePath());

    // show minimized?
    if (!argParser.isShowMinimized())
        w.show();

    return a.exec();
}
Exemplo n.º 23
0
Daemon::Daemon(const ArgumentParser &args) {
    ConfigParser config(args.GetConfig());
    plog::init<plog::LogFormatter>(config.GetLogSeverity(),
                                   config.GetLogFilename().c_str());

    IpcConnection conn("\0INTEGRITY");
    conn.Listen();

    Storage storage;

    daemon(1, 0);

    std::unique_ptr<std::thread> schedule;

    if (config.GetSleepDuration() > 0) {
        schedule = std::unique_ptr<std::thread>(
                       new std::thread(&Daemon::Schedule,
                                       this,
                                       std::ref(storage),
                                       config.GetPathListFile(),
                                       config.GetSleepDuration()));
    }

    while (running) {
        std::shared_ptr<IpcClient> client = conn.WaitForClient();
        int message = client->ReceiveCommand();

        switch (message) {
        case ArgumentParser::STORE: {
            Store(storage, config.GetPathListFile());
            break;
        }
        case ArgumentParser::CHECK: {
            Check(storage, config.GetPathListFile());
            break;
        }
        case ArgumentParser::KILL:
            running = false;
            storage.mtx.lock(); // wait for all db operations to end
            break;
        default:
            break;
        }
    }

    if (config.GetSleepDuration() > 0) {
        schedule->join();
    }
}
Exemplo n.º 24
0
SquareSelector<double> getCoordCutoffs(const TypeVec &types)
{
  vector<string> cutstrs = strsplit(args.getCString("coordinationCutoffs"));

  if (cutstrs.size() != 0)
  {
    if (types.size() == 0)
    {
      cerr << "coordinationCutoffs: species not defined" << endl;
      exit(1);
    }
    if (cutstrs.size() < types.size() * types.size())
    {
      cerr
        << "coordinationCutoffs: too few values. Must be number of species squared"
        << endl;
      exit(1);
    }
    if (cutstrs.size() > types.size() * types.size())
    {
      cerr
        << "coordinationCutoffs: too many values. Must be number of species squared"
        << endl;
      exit(1);
    }

    vector<double> cutoffs(cutstrs.size());
    for (size_t i = 0; i < cutstrs.size(); ++i)
    {
      double value;
      if (convert(cutstrs[i].c_str(), &value))
      {
        cerr << "coordinationCutoffs: invalid double value '"
          << cutstrs[i].c_str() << "'" << endl;
        exit(1);
      }

      cutoffs[i] = value;
    }
    return SquareSelector<double>(cutoffs);
  }

  return SquareSelector<double>(vector<double>());
}
Exemplo n.º 25
0
void parse_error(ArgumentParser &ap) {
    ap.print_usage();
    exit(1);
}
Exemplo n.º 26
0
static void commandWebExport(QTextStream &out, ArgumentParser &parser)
{
  std::vector<QString> ops;
  QString outputdir, title;
  bool build_file_tree = false;
  bool verbose_output = false;

  // parse the command line
  while (parser.hasNext()) {
    bool isswitch;
    QString cmd(parser.next(&isswitch));

    if (cmd == "-o")
      outputdir = parser.nextParam("-o");
    else if (cmd == "-t")
      title = parser.nextParam("-t");
    else if (cmd == "-f")
      build_file_tree = true;
    else if (cmd == "-v")
      verbose_output = true;
    else if (isswitch)
      throw ArgumentParser::ErrorException("Unknown switch: " + cmd);
    else
      ops.push_back(cmd);
  }

  if (outputdir.isEmpty())
    throw ArgumentParser::ErrorException("The output (-o) directory must be specified");

  if (!QFileInfo(outputdir).isDir())
    throw ArgumentParser::ErrorException(outputdir + " must be a directory");

  // parse the ops into the webexporter

  WebExport exporter(outputdir, out);
  QString fullcur, dir_prefix;
  int j, maxj;
  enum {
    flat_type,
    subdir_type,
    pivot_type,
  };
  short curtype = flat_type;
  QString pivot_tag, pivot_path, webpath;
  std::shared_ptr<hydra::Token> query_tok, pivot_tok;
  int scanned_count = 0;

  parseQueryTokens("", query_tok);   // init it

  if (!title.isEmpty())
    exporter.setTitle(title);

  maxj = static_cast<int>(ops.size());
  j = 0;
  while (j<maxj) {
    QString &param = ops[j];

    if (param == "flat") {
      curtype = flat_type;
    } else if (param == "subdir") {
      curtype = subdir_type;
    } else if (param == "pivot") {
      j++;
      if (j<maxj) {
        curtype = pivot_type;
        pivot_tag = ops[j];
        parseQueryTokens(pivot_tag + "*", pivot_tok);
      } else {
        out << "passing empty tag parameter to pivot subcommand!" << endl;
        curtype = flat_type;    // fail
      }
    } else if (param == "webpath") {
      j++;
      if (j<maxj)
        webpath = ops[j];
    } else if (param == "query") {
      j++;
      if (j<maxj)
        parseQueryTokens(ops[j], query_tok);
    } else {
      // must be a file param
      FileIterator ii(param);
      FileItemRecord item;
      FilePathRecord path;

      dir_prefix = prepPrefix(param);

      while (ii.hasNext()) {
        fullcur = ii.next();

        scanned_count++;
        if (verbose_output && scanned_count % 100 == 0)
          out << "Files scanned: " << scanned_count << endl;
        // load and check query
        if (Engine::instance()->getFileItem(fullcur, &item, 0, &path) != Engine::Load_OK)
          continue;
        if (!query_tok->isMatch(item.tags))
          continue;

        //std::cerr << "prefix=" << dir_prefix.utf8_str() << " cur=" << fullcur.utf8_str() << endl;
        switch (curtype) {
          case subdir_type:
            exporter.addFile(fullcur, AppendPath(webpath, JustPath(stripPrefix(fullcur, dir_prefix))), item, path.hash);
            break;
          case pivot_type:
            if (!PivotPath(pivot_tag, item.tags, pivot_path))
              continue;
            exporter.addFile(fullcur, pivot_path, item, path.hash);
            break;
          // assume flat
          default:
            exporter.addFile(fullcur, webpath, item, path.hash);
        }
      }//while
    }// if-else chain
    j++;
  }//while j

  // perform the export
  if (build_file_tree) {
    int count = exporter.commitFileCopy();

    if (count == -1)
      throw ArgumentParser::ErrorException("failed to copy files");

    out << count << " files copied" << endl;
  } else {
    int count = exporter.commitWebSite();

    if (count == -1)
      throw ArgumentParser::ErrorException("failed to build site");

    out << count << " files processed for the web site" << endl;
  }
}
Exemplo n.º 27
0
int main(int argc, char** argv)
{
    sofa::simulation::tree::init();
    sofa::component::initComponentBase();
    sofa::component::initComponentCommon();

    bool showHelp = false;
    unsigned int idExample = 0;
    ArgumentParser* argParser = new ArgumentParser(argc, argv);
    argParser->addArgument(po::value<bool>(&showHelp)->default_value(false)->implicit_value(true),                  "help,h", "Display this help message");
    argParser->addArgument(po::value<unsigned int>(&idExample)->default_value(0)->notifier([](unsigned int value)
    {
        if (value < 0 || value > 9) {
            std::cerr << "Example Number to enter from (0 - 9), current value: " << value << std::endl;
            exit( EXIT_FAILURE );
        }
    }),                                                                                                             "example,e", "Example Number to enter from (0 - 9)");

    argParser->parse();

    if(showHelp)
    {
        argParser->showHelp();
        exit( EXIT_SUCCESS );
    }

    // init GUI
    sofa::gui::initMain();
    sofa::gui::GUIManager::Init(argv[0]);

    // Create simulation tree
    sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());


    // Create the graph root node with collision
    sofa::simulation::Node::SPtr root = sofa::modeling::createRootWithCollisionPipeline();
    root->setGravity( sofa::defaulttype::Vec3Types::Deriv(0,-10.0,0) );


    // Create scene example (depends on user input)
    switch (idExample)
    {
    case 0:
        fallingCubeExample(root);
        break;
    case 1:
        fallingCylinderExample(root);
        break;
    case 2:
        fallingSphereExample(root);
        break;
    case 3:
        fallingDrapExample(root);
        break;
    default:
        fallingCubeExample(root);
        break;
    }


    root->setAnimate(false);

    sofa::simulation::getSimulation()->init(root.get());

    //=======================================
    // Run the main loop
    sofa::gui::GUIManager::MainLoop(root);

    sofa::simulation::tree::cleanup();

    return 0;
}
Exemplo n.º 28
0
Arguments parse_args(const int argc, char * argv[]){
    ArgumentParser ap;
    return ap.parse(argc, const_cast<const char **>(argv));
}
Exemplo n.º 29
0
void DisplaySettings::readCommandLine(ArgumentParser& arguments)
{
    if (_application.empty()) _application = arguments[0];

    // report the usage options.
    if (arguments.getApplicationUsage())
    {
        arguments.getApplicationUsage()->addCommandLineOption("--display <type>","MONITOR | POWERWALL | REALITY_CENTER | HEAD_MOUNTED_DISPLAY");
        arguments.getApplicationUsage()->addCommandLineOption("--stereo","Use default stereo mode which is ANAGLYPHIC if not overriden by environmental variable");
        arguments.getApplicationUsage()->addCommandLineOption("--stereo <mode>","ANAGLYPHIC | QUAD_BUFFER | HORIZONTAL_SPLIT | VERTICAL_SPLIT | LEFT_EYE | RIGHT_EYE | HORIZONTAL_INTERLACE | VERTICAL_INTERLACE | CHECKERBOARD | ON | OFF ");
        arguments.getApplicationUsage()->addCommandLineOption("--rgba","Request a RGBA color buffer visual");
        arguments.getApplicationUsage()->addCommandLineOption("--stencil","Request a stencil buffer visual");
        arguments.getApplicationUsage()->addCommandLineOption("--accum-rgb","Request a rgb accumulator buffer visual");
        arguments.getApplicationUsage()->addCommandLineOption("--accum-rgba","Request a rgb accumulator buffer visual");
        arguments.getApplicationUsage()->addCommandLineOption("--samples <num>","Request a multisample visual");
        arguments.getApplicationUsage()->addCommandLineOption("--cc","Request use of compile contexts and threads");
        arguments.getApplicationUsage()->addCommandLineOption("--serialize-draw <mode>","OFF | ON - set the serialization of draw dispatch");
        arguments.getApplicationUsage()->addCommandLineOption("--implicit-buffer-attachment-render-mask","OFF | DEFAULT | [~]COLOR | [~]DEPTH | [~]STENCIL. Substitute missing buffer attachments for render FBO");
        arguments.getApplicationUsage()->addCommandLineOption("--implicit-buffer-attachment-resolve-mask","OFF | DEFAULT | [~]COLOR | [~]DEPTH | [~]STENCIL. Substitute missing buffer attachments for resolve FBO");
        arguments.getApplicationUsage()->addCommandLineOption("--gl-version <major.minor>","Set the hint of which GL version to use when creating graphics contexts.");
        arguments.getApplicationUsage()->addCommandLineOption("--gl-flags <mask>","Set the hint of which GL flags projfile mask to use when creating graphics contexts.");
        arguments.getApplicationUsage()->addCommandLineOption("--gl-profile-mask <mask>","Set the hint of which GL context profile mask to use when creating graphics contexts.");
        arguments.getApplicationUsage()->addCommandLineOption("--swap-method <method>","DEFAULT | EXCHANGE | COPY | UNDEFINED. Select preferred swap method.");
    }

    std::string str;
    while(arguments.read("--display",str))
    {
        if (str=="MONITOR") _displayType = MONITOR;
        else if (str=="POWERWALL") _displayType = POWERWALL;
        else if (str=="REALITY_CENTER") _displayType = REALITY_CENTER;
        else if (str=="HEAD_MOUNTED_DISPLAY") _displayType = HEAD_MOUNTED_DISPLAY;
    }

    int pos;
    while ((pos=arguments.find("--stereo"))>0)
    {
        if (arguments.match(pos+1,"ANAGLYPHIC"))            { arguments.remove(pos,2); _stereo = true;_stereoMode = ANAGLYPHIC; }
        else if (arguments.match(pos+1,"QUAD_BUFFER"))      { arguments.remove(pos,2); _stereo = true;_stereoMode = QUAD_BUFFER; }
        else if (arguments.match(pos+1,"HORIZONTAL_SPLIT")) { arguments.remove(pos,2); _stereo = true;_stereoMode = HORIZONTAL_SPLIT; }
        else if (arguments.match(pos+1,"VERTICAL_SPLIT"))   { arguments.remove(pos,2); _stereo = true;_stereoMode = VERTICAL_SPLIT; }
        else if (arguments.match(pos+1,"HORIZONTAL_INTERLACE")) { arguments.remove(pos,2); _stereo = true;_stereoMode = HORIZONTAL_INTERLACE; }
        else if (arguments.match(pos+1,"VERTICAL_INTERLACE"))   { arguments.remove(pos,2); _stereo = true;_stereoMode = VERTICAL_INTERLACE; }
        else if (arguments.match(pos+1,"CHECKERBOARD"))     { arguments.remove(pos,2); _stereo = true;_stereoMode = CHECKERBOARD; }
        else if (arguments.match(pos+1,"LEFT_EYE"))         { arguments.remove(pos,2); _stereo = true;_stereoMode = LEFT_EYE; }
        else if (arguments.match(pos+1,"RIGHT_EYE"))        { arguments.remove(pos,2); _stereo = true;_stereoMode = RIGHT_EYE; }
        else if (arguments.match(pos+1,"ON"))               { arguments.remove(pos,2); _stereo = true; }
        else if (arguments.match(pos+1,"OFF"))              { arguments.remove(pos,2); _stereo = false; }
        else                                                { arguments.remove(pos); _stereo = true; }
    }

    while (arguments.read("--rgba"))
    {
        _RGB = true;
        _minimumNumberAlphaBits = 1;
    }            

    while (arguments.read("--stencil"))
    {
        _minimumNumberStencilBits = 1;
    }

    while (arguments.read("--accum-rgb"))
    {
        setMinimumNumAccumBits(8,8,8,0);
    }

    while (arguments.read("--accum-rgba"))
    {
        setMinimumNumAccumBits(8,8,8,8);
    }

    while(arguments.read("--samples",str))
    {
        _numMultiSamples = atoi(str.c_str());
    }

    while(arguments.read("--cc"))
    {
        _compileContextsHint = true;
    }

    while(arguments.read("--serialize-draw",str))
    {
        if (str=="ON") _serializeDrawDispatch = true;
        else if (str=="OFF") _serializeDrawDispatch = false;
    }

    while(arguments.read("--num-db-threads",_numDatabaseThreadsHint)) {}
    while(arguments.read("--num-http-threads",_numHttpDatabaseThreadsHint)) {}

    while(arguments.read("--texture-pool-size",_maxTexturePoolSize)) {}
    while(arguments.read("--buffer-object-pool-size",_maxBufferObjectPoolSize)) {}

    {  // Read implicit buffer attachments combinations for both render and resolve mask
        const char* option[] = {
            "--implicit-buffer-attachment-render-mask",
            "--implicit-buffer-attachment-resolve-mask",
        };

        int * mask[] = { 
            &_implicitBufferAttachmentRenderMask,
            &_implicitBufferAttachmentResolveMask,
        };

        for( unsigned int n = 0; n < sizeof( option ) / sizeof( option[0]); n++ )
        {
            while(arguments.read( option[n],str))
            {
                if(str.find("OFF")!=std::string::npos) *mask[n] = 0;

                if(str.find("~DEFAULT")!=std::string::npos) *mask[n] ^= DEFAULT_IMPLICIT_BUFFER_ATTACHMENT;
                else if(str.find("DEFAULT")!=std::string::npos) *mask[n] |= DEFAULT_IMPLICIT_BUFFER_ATTACHMENT;

                if(str.find("~COLOR")!=std::string::npos) *mask[n] ^= IMPLICIT_COLOR_BUFFER_ATTACHMENT;
                else if(str.find("COLOR")!=std::string::npos) *mask[n] |= IMPLICIT_COLOR_BUFFER_ATTACHMENT;

                if(str.find("~DEPTH")!=std::string::npos) *mask[n] ^= IMPLICIT_DEPTH_BUFFER_ATTACHMENT;
                else if(str.find("DEPTH")!=std::string::npos) *mask[n] |= IMPLICIT_DEPTH_BUFFER_ATTACHMENT;

                if(str.find("~STENCIL")!=std::string::npos) *mask[n] ^= IMPLICIT_STENCIL_BUFFER_ATTACHMENT;
                else if(str.find("STENCIL")!=std::string::npos) *mask[n] |= IMPLICIT_STENCIL_BUFFER_ATTACHMENT;
            }
        }
    }

    while (arguments.read("--gl-version", _glContextVersion)) {}
    while (arguments.read("--gl-flags", _glContextFlags)) {}
    while (arguments.read("--gl-profile-mask", _glContextProfileMask)) {}

    while(arguments.read("--swap-method",str))
    {
        if (str=="DEFAULT") _swapMethod = SWAP_DEFAULT;
        else if (str=="EXCHANGE") _swapMethod = SWAP_EXCHANGE;
        else if (str=="COPY") _swapMethod = SWAP_COPY;
        else if (str=="UNDEFINED") _swapMethod = SWAP_UNDEFINED;
    }


}
Exemplo n.º 30
0
int
main(int argc, char **argv)
{
	ArgumentParser *argp = new ArgumentParser(argc, argv, "h:f:c:");

	if (argp->has_arg("h") && argp->has_arg("f"))
	// read image from file
	{
		const char *cascade_file = argp->arg("h");
		const char *image_file   = argp->arg("f");

		JpegReader *   reader = new JpegReader(image_file);
		unsigned char *buffer =
		  malloc_buffer(YUV422_PLANAR, reader->pixel_width(), reader->pixel_height());

		reader->set_buffer(buffer);
		reader->read();

		FacesClassifier *classifier =
		  new FacesClassifier(cascade_file, reader->pixel_width(), reader->pixel_height());

		classifier->set_src_buffer(buffer, reader->pixel_width(), reader->pixel_height());
		std::list<ROI> *rois = classifier->classify();

		FilterROIDraw *roi_draw = new FilterROIDraw();
		for (std::list<ROI>::iterator i = rois->begin(); i != rois->end(); ++i) {
			printf("ROI: start (%u, %u)  extent %u x %u\n",
			       (*i).start.x,
			       (*i).start.y,
			       (*i).width,
			       (*i).height);

			roi_draw->set_dst_buffer(buffer, &(*i));
			roi_draw->apply();
		}

		ImageDisplay *display = new ImageDisplay(reader->pixel_width(), reader->pixel_height());
		display->show(buffer);

		display->loop_until_quit();

		delete display;

		delete rois;
		free(buffer);
		delete reader;
		delete classifier;
	}

	else if (argp->has_arg("h") && argp->has_arg("c"))
	// get images from camera
	{
		const char *cascade_file = argp->arg("h");

		Camera *camera = NULL;
		try {
			camera = CameraFactory::instance(argp->arg("c"));
			camera->open();
			camera->start();
		} catch (Exception &e) {
			printf("Failed to open camera.\n");
			delete camera;
			return (-1);
		}

		printf("successfully opened camera: w=%d h=%d\n",
		       camera->pixel_width(),
		       camera->pixel_height());

		TimeTracker *tt              = new TimeTracker();
		unsigned int ttc_recognition = tt->add_class("Face recognition");
		unsigned int loop_count      = 0;

		IplImage *image =
		  cvCreateImage(cvSize(camera->pixel_width(), camera->pixel_height()), IPL_DEPTH_8U, 3);

		IplImage *scaled_image =
		  cvCreateImage(cvSize(camera->pixel_width() / 2, camera->pixel_height() / 2), IPL_DEPTH_8U, 3);

		FacesClassifier *classifier = new FacesClassifier(cascade_file,
		                                                  camera->pixel_width(),
		                                                  camera->pixel_height(),
		                                                  scaled_image,
		                                                  1.2 /* scale factor */,
		                                                  2 /* min neighbours */,
		                                                  CV_HAAR_DO_CANNY_PRUNING);

		unsigned char *display_buffer = (unsigned char *)malloc(camera->buffer_size());

		ImageDisplay *display =
		  new ImageDisplay(camera->pixel_width(), camera->pixel_height(), "QA Faces Classifier");

		Drawer *drawer = new Drawer();
		drawer->set_buffer(display_buffer, camera->pixel_width(), camera->pixel_height());

		SDL_Event redraw_event;
		redraw_event.type           = SDL_KEYUP;
		redraw_event.key.keysym.sym = SDLK_SPACE;

		SDL_PushEvent(&redraw_event);

		bool quit = false;
		while (!quit) {
			SDL_Event event;
			if (SDL_WaitEvent(&event)) {
				switch (event.type) {
				case SDL_QUIT: quit = true; break;

				case SDL_KEYUP:
					if (event.key.keysym.sym == SDLK_SPACE) {
						camera->capture();

						if (camera->buffer() != NULL) {
							IplImageAdapter::convert_image_bgr(camera->buffer(), image);
							cvResize(image, scaled_image, CV_INTER_LINEAR);
							memcpy(display_buffer, camera->buffer(), camera->buffer_size());

							tt->ping_start(ttc_recognition);
							std::list<ROI> *rois = classifier->classify();
							tt->ping_end(ttc_recognition);

							camera->dispose_buffer();

							bool first = true;
							for (std::list<ROI>::reverse_iterator i = rois->rbegin(); i != rois->rend(); ++i) {
								if (first) {
									drawer->set_color(127, 70, 200);
								}
								drawer->draw_rectangle(2 * i->start.x, 2 * i->start.y, 2 * i->width, 2 * i->height);
								if (first) {
									drawer->set_color(30, 30, 30);
									first = false;
								}
							}

							if (++loop_count % 15 == 0) {
								tt->print_to_stdout();
							}

							display->show(display_buffer);
						}

						SDL_PushEvent(&redraw_event);
					}

					else if (event.key.keysym.sym == SDLK_ESCAPE) {
						quit = true;
					}

					break;

				default: break;
				}
			}
		}

		camera->stop();
		camera->close();
		delete camera;
		delete display;
		delete drawer;
		free(display_buffer);
		cvReleaseImage(&image);
		cvReleaseImage(&scaled_image);
		delete tt;
	}

	else {
		printf("Usage: %s -h <Haar cascade file> -f <Image file as JPEG>\n", argv[0]);
		printf("    or %s -h <Haar cascade file> -c <Camera argument string>\n", argv[0]);
		exit(-1);
	}

	delete argp;
}