int main(int argc, char* argv[])
{
   ossimString tempString;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser argumentParser(&argc, argv);
   //ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);
   ossim_uint32 threads = 10;
   ossim_uint32 nvalues = 10;
   ossim_uint32 randomSeed = 0;

   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
   argumentParser.getApplicationUsage()->addCommandLineOption("--threads","Specify the number of threads to test simultaneus access to elevation");
   argumentParser.getApplicationUsage()->addCommandLineOption("--nvalues","Specify the number of random values");
   if (argumentParser.read("-h") ||
       argumentParser.read("--help"))
   {
      argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_WARN));
      exit(0);
   }
   if(argumentParser.read("--threads", stringParam))
   {
      threads = tempString.toUInt32();
   }
   if(argumentParser.read("--nvalues", stringParam))
   {
      nvalues = tempString.toUInt32();
   }

   std::vector<Polyarea2dThread*> threadList(threads);
   startBarrier = new OpenThreads::Barrier(threads); // include the main thread for synching
   endBarrier   = new OpenThreads::Barrier(threads+1); //   include main thread for syncing end 
   ossim_uint32 idx = 0;
   for(idx = 0; idx < threads; ++ idx)
   {
      threadList[idx] = new Polyarea2dThread("Thread " + ossimString::toString(idx));
      threadList[idx]->setNumberOfPointsToQuery(nvalues);
      threadList[idx]->start();
   }
   ossimTimer::Timer_t t1 = ossimTimer::instance()->tick();
   // synch all threads to start at the same time
   std::cout << "Number of threads:         " << threads      << "\n";
//   startBarrier->block();
   endBarrier->block();
   std::cout << "All threads finished\n";
   ossimTimer::Timer_t t2 = ossimTimer::instance()->tick();
   std::cout << "Time elapsed:              " << ossimTimer::instance()->delta_s(t1, t2) << " seconds" << "\n";
   delete startBarrier;
   delete endBarrier;
   return 0;
}
Exemple #2
0
TuioServer::TuioServer(std::unordered_map<std::string, std::string> &parameters) {
	this->ipaddr = stringParam(parameters, PARAM_ADDRESS, DEFAULT_ADDRESS);
	this->port = intParam(parameters, PARAM_PORT, DEFAULT_PORT);
	this->fseq = 0;

	WSADATA wsaData;
	int startupResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (startupResult != 0) {
        std::cerr << "Winsock startup failed (error " << startupResult << ")\n";
        throw 1;
    }

	this->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (this->sock == INVALID_SOCKET) {
		std::cerr << "Socket cannot be opened (error " << WSAGetLastError() << ")\n";
		throw 1;
	}
}
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.c_str());
         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 #4
0
int main(int argc, char* argv[])
{
   static const char MODULE[] = "icp:main";
   std::string tempString;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   
   ossimArgumentParser ap(&argc, argv);
   ossimInit::instance()->addOptions(ap);
   ossimInit::instance()->initialize(ap);

   ossimApplicationUsage* au = ap.getApplicationUsage();
   
   au->setApplicationName(ap.getApplicationName());
   au->setDescription(ap.getApplicationName()+
      " copies any supported input image format to any supported output image format format");
   au->setCommandLineUsage(ap.getApplicationName()+
      " [options] <output_type> <input_file> <output_file>");
   au->addCommandLineOption("-h or --help",
      "Display this information");
   au->addCommandLineOption("-a or --use-scalar-remapper", 
      "Uses scalar remapper, transforms to 8-bit");
   au->addCommandLineOption("-o or --create-overview", 
      "Creates and overview for the output image");
   au->addCommandLineOption("-b or --bands <n,n...>", 
      "uses the specified bands: ex. \"1, 2, 4\" will select bands 1 2 and 4 of the input image.  "
      "Note: it is 1 based");
   au->addCommandLineOption("-c or --compression-type <type>", 
      "Uses compression.  Currently valid for only tiff output -c jpeg will use jpeg compression");
   au->addCommandLineOption("-e or --entry <n>", 
      "For multi image handlers which entry do you wish to extract");
   au->addCommandLineOption("-q or --compression-quality <n>", 
      "Uses compression.  Valid for jpeg type. default is 75 where 100 is best and 1 is worst");
   au->addCommandLineOption("--pixel-type <type>", 
      "Valid values: area or point, this will determine if the tie point is upper left corner of "
      "the upper left pixel (area) or the center of the upper left corner (point), default=point. "
      "NOTE: This option will only affect the tiff writer.");
   au->addCommandLineOption("-r or --res-level <n>", 
      "Which res level to extract from the input: ex -r 1 will get res level 1");
   au->addCommandLineOption("-l or --start-line <n>", 
      "Which start line do you wish to copy from the input. If none is given then 0 is used");
   au->addCommandLineOption("-L or --end-line <n>", 
      "Which end line do you wish to copy from the input.  If none is given then max line is used");
   au->addCommandLineOption("-s or --start-sample <n>", 
      "Which start sample do you wish to copy from the input.  If none is given then 0 is used");
   au->addCommandLineOption("-p or --end-sample <n>", 
      "The end sample you wish to copy from the input. If none is given then max sample is used");
   au->addCommandLineOption("-t or --create-thumbnail <n>", 
      "Takes an argument which is the maximum pixel dimension desired.");
   au->addCommandLineOption("-w or --tile-width <n>", 
      "Defines the tile width for the handlers that support tiled output");

   au->addCommandLineOption("--reader-prop <string>", 
      "Adds a property to send to the reader. format is name=value");

   au->addCommandLineOption("--writer-prop <string>", 
      "Adds a property to send to the writer. format is name=value");

   au->addCommandLineOption("--filter-spec <fname>", 
      "This is an external file spec that describes a chain for filtering the input image.");
   au->addCommandLineOption("--use-mask [<fname>]", 
      "Optionally specify name of mask file to use for masking the input image. If no filename "
      "given, then the default mask filename is used.");
   
   
   if (traceDebug()) CLOG << " Entered..." << std::endl;
   
   // Keyword list to initialize image writers with.
   ossimKeywordlist kwl;
   const char* PREFIX = "imagewriter.";

   bool        lineEndIsSpecified       = false;
   bool        sampEndIsSpecified       = false;
   bool        lineStartIsSpecified     = false;
   bool        sampStartIsSpecified     = false;
   bool        create_overview          = false;
   bool        create_thumbnail         = false;
   bool        use_band_selector        = false;
   bool        use_scalar_remapper      = false;
   bool        use_mask                 = false;
   ossim_int32 tile_width               = 0;
   ossim_int32 max_thumbnail_dimension  = 0;
   ossim_int32 rr_level                 = 0;
   ossim_int32 line_start               = 0;
   ossim_int32 line_stop                = 0;
   ossim_int32 sample_start             = 0;
   ossim_int32 sample_stop              = 0;
   ossim_int32 cibcadrg_entry           = 0;
   vector<ossimString> band_list(0);
   ossimFilename filterSpec, maskFile;
   std::map<ossimString, ossimString> readerPropertyMap;
   std::map<ossimString, ossimString> writerPropertyMap;

   if (ap.read("-h") ||
       ap.read("--help")||(ap.argc() < 2))
   {
      au->write(ossimNotify(ossimNotifyLevel_NOTICE));
      usage(); // for writer output types
      finalize(0);
   }

   while(ap.read("--reader-prop", stringParam))
   {
      std::vector<ossimString> nameValue;
      ossimString(tempString).split(nameValue, "=");
      if(nameValue.size() == 2)
      {
         readerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1])));
      }
   }   
   while(ap.read("--writer-prop", stringParam))
   {
      std::vector<ossimString> nameValue;
      ossimString(tempString).split(nameValue, "=");
      if(nameValue.size() == 2)
      {
         writerPropertyMap.insert(std::make_pair(nameValue[0], massageQuotedValue(nameValue[1])));
      }
   }
   while(ap.read("-a") ||
         ap.read("--use-scalar-remapper"))
   {
      use_scalar_remapper = true;        
   }
   while(ap.read("--filter-spec",stringParam))
   {
      filterSpec = ossimFilename(tempString);        
   }
   
   while(ap.read("--use-mask") ||
         ap.read("--use-mask",stringParam) )
   {
      maskFile = ossimFilename(tempString);     
      use_mask = true;
   }
   
   while(ap.read("-o") ||
         ap.read("--create-overview"))
   {
      create_overview = true;
   }
   
   while(ap.read("-b", stringParam) ||
         ap.read("--bands", stringParam))
   {
      use_band_selector = true;
      ossimString s = tempString;
      band_list = s.split(",");
   }
   
   while(ap.read("-c", stringParam) ||
         ap.read("--compression-type", stringParam))
   {
      ossimString s = tempString;
      s.downcase();
      kwl.add(PREFIX, ossimKeywordNames::COMPRESSION_TYPE_KW, s.c_str(), true);
   }
   
   while(ap.read("-e", stringParam) ||
         ap.read("--entry", stringParam))
   {
      cibcadrg_entry = ossimString(tempString).toInt();
   }
   
   while(ap.read("-q", stringParam) ||
         ap.read("--compression-quality", stringParam))
   {
      // Set the jpeg compression quality level.
      kwl.add(PREFIX,
              ossimKeywordNames::COMPRESSION_QUALITY_KW,
              tempString.c_str(),
              true);
   }
   while(ap.read("-r", stringParam) ||
         ap.read("--res-level", stringParam))
   {
      rr_level = ossimString(tempString).toInt();
   }
   
   while(ap.read("-l", stringParam) ||
         ap.read("--start-line", stringParam))
   {
      lineStartIsSpecified = true;
      line_start = ossimString(tempString).toInt();
   }
   
   while(ap.read("-L", stringParam) ||
         ap.read("--end-line", stringParam))
   {
      lineEndIsSpecified = true;
      line_stop = ossimString(tempString).toInt();
   }
   while(ap.read("-s", stringParam) ||
         ap.read("--start-sample", stringParam))
   {
      sampStartIsSpecified = true;
      sample_start = ossimString(tempString).toInt();
   }
   
   while(ap.read("-p", stringParam) ||
         ap.read("--end-sample", stringParam))
   {
      sampEndIsSpecified = true;
      sample_stop = ossimString(tempString).toInt();
   }
   
   while(ap.read("-t", stringParam) ||
         ap.read("--create-thumbnail", stringParam))
   {
      create_thumbnail = true;
      max_thumbnail_dimension=ossimString(tempString).toInt();
   }
   
   while(ap.read("-w", stringParam) ||
         ap.read("-tile-width", stringParam))
   {
      tile_width = ossimString(tempString).toInt();
      if ((tile_width % 16) != 0)
      {
         ossimNotify(ossimNotifyLevel_NOTICE)
            << MODULE << " NOTICE:"
            << "\nTile width must be a multiple of 16!"
            << "\nDefaulting to 128"
            << std::endl;
         tile_width = 0;
      }
   }
   if (ap.read("--pixel-type", stringParam))
   {
      ossimString os = tempString;
      os.downcase();
      if (os.contains("area"))
      {
         kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "area", true);
      }
      else
      {
         kwl.add(PREFIX, ossimKeywordNames::PIXEL_TYPE_KW, "point", true);
 
      }
   }
   
   ap.reportRemainingOptionsAsUnrecognized();
   
   // Three required args:  output_type, input file, and output file.
   if (ap.errors())
   {
      ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE));
      finalize(0);
   }
   if (ap.argc() < 4)
   {
      au->write(ossimNotify(ossimNotifyLevel_NOTICE));
      usage(); // for writer output types
      finalize(0);
   }
   
   //---
   // Set the writer type and the image type.
   //---
   ossimString output_type = ap.argv()[ap.argc()-3];
//   output_type.downcase();
   
   
   kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true);
   // Get the input file.
   const char* input_file = argv[ap.argc()-2];
   
   // Get the output file.
   ossimFilename    output_file = argv[ap.argc()-1];
   
   if (traceDebug())
   {
      CLOG << "DEBUG:"
           << "\noutput type:  "
           << ap.argv()[ap.argc()-3]
           << "\ninput file:   "
           << ap.argv()[ap.argc()-2]
           << "\noutput file:  "
           << ap.argv()[ap.argc()-1]
           << std::endl;
      
      if (tile_width) ossimNotify(ossimNotifyLevel_NOTICE) << "tile_width:  " << tile_width << std::endl;
   }
   
   // Get an image handler for the input file.
   ossimRefPtr<ossimImageHandler> ih =
      ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file));
   
   ossimCibCadrgTileSource* its = PTR_CAST(ossimCibCadrgTileSource, ih.get());
   
   if (its)
   {
      if (cibcadrg_entry > 0)
      {
         its->setCurrentEntry(cibcadrg_entry);
      }
   }
   
   if (!ih)
   {
      ossimNotify(ossimNotifyLevel_NOTICE) << "Unsupported image file:  " << input_file
           << "\nExiting application..." << std::endl;
      finalize(0);
   }
   if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
   {
      ossimNotify(ossimNotifyLevel_FATAL)
         << "Error reading image:  " << input_file
         << "Exiting application..." << std::endl; 
      finalize(1);
   }

   // Set the reader properties if any.
   if ( readerPropertyMap.size() )
   {
      ossimPropertyInterface* pi = (ossimPropertyInterface*)ih.get();
      std::map<ossimString, ossimString>::iterator iter = readerPropertyMap.begin();
      while(iter != readerPropertyMap.end())
      {
         pi->setProperty(iter->first, iter->second);
         ++iter;
      }
   }
   
   ih->initialize();
   ossimRefPtr<ossimImageSource> source = ih.get();
   
   if (traceDebug())
   {
      CLOG << "DEBUG:"
           << "\nImage Handler:  " << ih->getLongName()
           << std::endl;
   }
   
   ossimRefPtr<ossimMaskFilter> mask_filter = 0;
   if (use_mask)
   {
      if (maskFile.empty())
         maskFile = ih->getFilenameWithThisExtension("mask");
      ossimRefPtr<ossimImageHandler> mh = ossimImageHandlerRegistry::instance()->open(maskFile);
      if (!mh.valid())
      {
         ossimNotify(ossimNotifyLevel_FATAL)<<"ossim-icp -- Could not open raster mask file <"
            <<maskFile<<">. Maske request will be ignored. Aborting..."<<endl;
         finalize(1);
      }
      mask_filter = new ossimMaskFilter(ih.get(), mh.get());
      source = mask_filter.get();
   }

   ossimRefPtr<ossimBandSelector> bs = 0;
   if(!filterSpec.empty()&&filterSpec.exists())
   {
      ossimKeywordlist kwl;
      if(kwl.addFile(filterSpec))
      {
         ossimRefPtr<ossimObject> input = ossimObjectFactoryRegistry::instance()->createObject(kwl);
         if(input.valid())
         {
            ossimImageSource* inputImageSource = dynamic_cast<ossimImageSource*> (input.get());
            if(inputImageSource)
            {
               inputImageSource->connectMyInputTo(source.get());
               source = inputImageSource;
            }
         }
      }
   }
   if (use_band_selector && (source->getNumberOfOutputBands() > 1))
   {
      // Build the band list.
      ossim_uint32 bands = source->getNumberOfOutputBands();
      vector<ossim_uint32> bl;
      ossim_uint32 i;
      for (i=0; i<band_list.size(); ++i)
      {
         bl.push_back(band_list[i].toULong()-1);
      }
      
      // Check the list.  Make sure all the bands are within range.
      for (i=0; i<bl.size(); ++i)
      {
         if (bl[i] >= bands)
         {
            ossimNotify(ossimNotifyLevel_FATAL)
               << MODULE << " ERROR:"
               << "\nBand list range error!"
               << "\nHighest available band:  " << bands
               << std::endl;
            finalize(1);
         }
      }
      
      bs = new ossimBandSelector();
      bs->connectMyInputTo(source.get());
      bs->setOutputBandList(bl);
      bs->enableSource();
      bs->initialize();
      source = bs.get();
      
      if (traceDebug())
      {
         CLOG << "DEBUG:"
              << "\nZero based output band list:" << std::endl;
         for (i=0; i<bl.size(); ++i)
         {
            ossimNotify(ossimNotifyLevel_NOTICE)
               << "   band[" << i << "]:  " << bl[i] << std::endl;
         }
         ossimNotify(ossimNotifyLevel_NOTICE) << std::endl;
      }
   }
   
   //---
   // Get the image rectangle for the rrLevel selected.
   //---
   ossimIrect output_rect;
   ossimRefPtr<ossimRLevelFilter> rlevelFilter = 0;
   
   if (create_thumbnail == true)
   {
      rlevelFilter = new ossimRLevelFilter;
      
      rlevelFilter->connectMyInputTo(source.get());
      
      source = rlevelFilter.get();
      // Get the rlevel that <= max thumbnail dimension.
      int max   = 0;
      int level = 0;
      
      while (level < ((ossim_int32)ih->getNumberOfDecimationLevels()-1))
      {
         int lines   = ih->getNumberOfLines(level);
         int samples = ih->getNumberOfSamples(level);
         max = lines > samples ? lines : samples;
         if (max <= max_thumbnail_dimension)
         {
            break;
         }
         level++;
      }
      
      if (max > max_thumbnail_dimension)
      {
         ossimNotify(ossimNotifyLevel_NOTICE) << " NOTICE:"
              << "\nLowest rlevel not small enough to fullfill "
              << "max_thumbnail_dimension requirement!" << std::endl;
      }
      
      // Set the reduced res level.  This will override the -r option.
      rr_level = level;
      rlevelFilter->setCurrentRLevel(rr_level);
      if (rr_level)
      {
         rlevelFilter->setOverrideGeometryFlag(true);
      }


      // Set the rectangle to that of the res level.
      output_rect = rlevelFilter->getBoundingRect();

   } // end of "if  (create_thumbnail == true)
   else
   {
      // modified to only do an rlevel if one is requested
      if(rr_level != 0)
      {
         //***
         // Check for a valid reduced resolution level.
         // If the operator entered an invalid rr_level with the -r option,
         // spit out a warning and set to default "0".
         //***
         if (rr_level >= (ossim_int32)(ih->getNumberOfDecimationLevels()))
         {
            ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:"
            << "\n\t Selected res level greater than available res levels."
            << "\n\t Defaulting to res level zero. " << std::endl;
            rr_level = 0;
         }
         
         rlevelFilter = new ossimRLevelFilter;
         
         rlevelFilter->connectMyInputTo(source.get());
         
         source = rlevelFilter.get();
         
         rlevelFilter->setCurrentRLevel(rr_level);
         if (rr_level)
         {
            rlevelFilter->setOverrideGeometryFlag(true);
         }
      }
      output_rect = source->getBoundingRect(rr_level);
      
      //***
      // If any of these are true the user wants to cut the rectangle.
      //***
      if ( lineStartIsSpecified || lineEndIsSpecified ||
           sampStartIsSpecified || sampEndIsSpecified)
      {
         if (!lineStartIsSpecified) line_start   = output_rect.ul().y;
         if (!lineEndIsSpecified)   line_stop    = output_rect.lr().y;
         if (!sampStartIsSpecified) sample_start = output_rect.ul().x;
         if (!sampEndIsSpecified)   sample_stop  = output_rect.lr().x;
                                                 
         //***
         // Check the start and stop points and make sure they are in
         // the right order; if not, swap them.
         //***
         if (line_stop < line_start)
         {
            ossimNotify(ossimNotifyLevel_NOTICE) << " WARNING:\n"
                 << "\t Line end is less than line start, swapping."
                 << std::endl;
            int tmp    = line_start;
            line_start = line_stop;
            line_stop  = tmp;
         }
         if (sample_stop < sample_start)
         {
            ossimNotify(ossimNotifyLevel_WARN)
               << " WARNING:\n"
               << "\t Sample end is less than sample start, swapping."
               << std::endl;
            int tmp      = sample_start;
            sample_start = sample_stop;
            sample_stop  = tmp;
         }

//          if (sample_start > output_rect.ul().x &&
//              sample_start < output_rect.lr().x)
//          {
             output_rect.set_ulx(sample_start);
//          }
//          if (sample_stop > output_rect.ul().x &&
//              sample_start < output_rect.lr().x)
//          {
             output_rect.set_lrx(sample_stop);
//          }
//          if (line_start > output_rect.ul().y &&
//              line_start < output_rect.lr().y)
//          {
             output_rect.set_uly(line_start);
//          }
//          if (line_stop > output_rect.ul().y &&
//              line_start < output_rect.lr().y)
//          {
             output_rect.set_lry(line_stop);
//          }
         
      } // End of "if ((lineEndIsSpecified) ||..."
   }

   if (traceDebug())
   {
      CLOG << "icp:main debug"
           << "\nrr_level:  " << rr_level
           << "\noutput_rect:   " << output_rect
           << "\nkeyword list:  " << kwl << std::endl;
   }
   
   
   ossimRefPtr<ossimImageFileWriter> writer =
      ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);

   if( writer == 0 )
   {
      ossimNotify(ossimNotifyLevel_NOTICE)
         << "\nCould not create writer of type:  "
         << output_type
         << std::endl;
      usage();
      finalize(1);
   }

   writer->connectMyInputTo(0, source.get());

   if (tile_width)
   {
      // Set the tile size...
      writer->setTileSize(ossimIpt(tile_width, tile_width));
   }
   
   writer->open(output_file);
   
   // Add a listener to get percent complete.
   ossimStdOutProgress prog(0, true);
   writer->addListener(&prog);

   if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
   {
      if( (ih->getOutputScalarType() != OSSIM_UCHAR) &&
          ((PTR_CAST(ossimJpegWriter, writer.get())) ||
           use_scalar_remapper))
      {
         writer->setScaleToEightBitFlag(true);
      }

      ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource;
      ossimIpt tileWidthHeight(ih->getImageTileWidth(),
                               ih->getImageTileHeight());
      // only use the cache if its stripped
      if(static_cast<ossim_uint32>(tileWidthHeight.x) ==
         ih->getBoundingRect().width())
      {
         cache->connectMyInputTo(0, source.get());
         cache->setTileSize(tileWidthHeight);
         writer->connectMyInputTo(0, cache.get());
      }
      else
      {
         writer->connectMyInputTo(0, source.get());
      }
      writer->initialize();
      writer->setAreaOfInterest(output_rect); // Set the output rectangle.

      try
      {
         if ( writerPropertyMap.size() )
         {
            ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get();
            std::map<ossimString, ossimString>::iterator iter = writerPropertyMap.begin();
            while(iter!=writerPropertyMap.end())
            {
               propInterface->setProperty(iter->first, iter->second);
               ++iter;
            }
         }
         writer->execute();
      }
      catch(std::exception& e)
      {
         ossimNotify(ossimNotifyLevel_FATAL)
            << "icp:main ERROR:\n"
            << "Caught exception!\n"
            << e.what()
            << std::endl;
      }
      catch(...)
      {
         ossimNotify(ossimNotifyLevel_FATAL)
            << "icp:main ERROR:\n"
            << "Unknown exception caught!\n"
            << std::endl;
      }

      cache = 0;
   }
   else
   {
      ossimNotify(ossimNotifyLevel_FATAL)
         << "Error detected in the image writer..."
         << "\nExiting application..." << std::endl;

      finalize(1);
   }
   
   if (create_overview == true)
   {
      writer->writeOverviewFile();
   }
   
   finalize(0);
}
int main(int argc, char* argv[])
{
   static const char MODULE[] = "band_merge:main";

   std::string tempString;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);
 
   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" merges band separate images to one image");
   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
   argumentParser.getApplicationUsage()->addCommandLineOption("-o or --create-overiew", "Creates and overview for the output image");
   argumentParser.getApplicationUsage()->addCommandLineOption("-w or --tile-width", "Defines the tile width for the handlers that support tiled output");
   
   if (traceDebug()) CLOG << " Entered..." << std::endl;

   if (argumentParser.read("-h") ||
       argumentParser.read("--help")||(argumentParser.argc() < 2))
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      usage(); // for writer output types
      exit(0);
   }

   // Keyword list to initialize image writers with.
   ossimKeywordlist kwl;
   const char* PREFIX = "imagewriter.";

   ossim_uint32 tile_width = 32;
   bool create_overview = false;

   if (argumentParser.read("-o") || argumentParser.read("--crate-overview"))
   {
      create_overview = true;
      std::cout << "\nOutput overview building enabled." << std::endl;
   }

   if (argumentParser.read("-w", stringParam) ||
       argumentParser.read("-tile-width", stringParam))
   {
      tile_width = ossimString(tempString).toInt();
      if ((tile_width % 16) != 0)
      {
         cerr << MODULE << " NOTICE:"
              << "\nTile width must be a multiple of 16!"
              << "\nDefaulting to 128"
              << std::endl;
         tile_width = 0;
      }
      std::cout << "Tile width set to:  " << tile_width << std::endl;
   }
   
   argumentParser.reportRemainingOptionsAsUnrecognized();
   
   // Three required args:  output_type, input file, and output file.
   if (argumentParser.errors())
   {
      argumentParser.writeErrorMessages(std::cout);
      exit(0);
   }
   if (argumentParser.argc() == 1)
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      usage(); // for writer output types
      exit(0);
   }
   
   ossim_uint32 number_of_source_images = argumentParser.argc() - 3;

   if (traceDebug())
   {
      CLOG << "DEBUG:"
           << "\nargc:  " << argumentParser.argc()
           << "\nnumber_of_source_images:  " << number_of_source_images
           << "\ntile_width:  " << tile_width
           << "\ncreate_overview:  " << (create_overview?"true":"false")
           << std::endl;
   }

   ossimString output_type = argv[1];
   output_type.downcase();
   std::cout << "Output type:        " << output_type << std::endl;

   // Create the vector of image handlers.
   ossimConnectableObject::ConnectableObjectList ihs;
   for(ossim_uint32 h = 0; h < number_of_source_images; ++h)
   {
      ossimFilename f = argv[h + 2];
      std::cout << "Input_image[" << h << "]:     " << f << std::endl;
      ihs.push_back(ossimImageHandlerRegistry::instance()->open(f));
   }

   // Get the output file.
   ossimFilename output_file = argv[argumentParser.argc() - 1];
   std::cout << "Output file:        " << output_file << std::endl;   

   //---
   // Set the output writer type and the image type.
   //---
   kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str());

   ossimRefPtr<ossimBandMergeSource> bm = new ossimBandMergeSource(ihs);
   ossimRefPtr<ossimImageFileWriter> fileWriter =
      ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);
   if(!fileWriter)
   {
      bm->disconnect();
      bm = 0;
      ossimConnectableObject::ConnectableObjectList::iterator i = ihs.begin();
      while (i != ihs.end())
      {
         (*i)->disconnect();
         (*i) = 0;
         ++i;
      }
      
      cerr << "Error making an image writer..."
           << "\nExiting application..." << std::endl;
      exit(1);
   }
   
   // Write out a geometry file for new image.
   ossimKeywordlist bm_geom;
   ossimRefPtr<ossimImageGeometry> geom = bm->getImageGeometry();
   geom->saveState(bm_geom);
   
   ossimFilename geom_file = output_file;
   geom_file.setExtension("geom");
   bm_geom.write(geom_file);
   
   fileWriter->connectMyInputTo(0, bm.get());
   
   if (tile_width)
   {
      // Set the tile size...
      fileWriter->setTileSize(ossimIpt(tile_width, tile_width));
   }
   
   fileWriter->open(output_file);
   
   ossimStdOutProgress prog(2);
   fileWriter->addListener(&prog);
   
   fileWriter->setAreaOfInterest(bm->getBoundingRect());

   if( fileWriter->canCastTo("ossimTiffWriter") )
   {
//      ossimTiffWriter* twriter = PTR_CAST(ossimTiffWriter, fileWriter);
      
      if(fileWriter.valid())
      {
         try
         {
            fileWriter->execute();
         }
         catch(std::exception& e)
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "band_merge: ERROR exception caught:\n"
               << e.what()
               << std::endl;
         }
         catch (...)
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "band_merge: ERROR - Unknown exception caught!"
               << std::endl;
         }
      }
   }
   else if(fileWriter->canCastTo("ossimJpegWriter"))
   {
      ossimRefPtr<ossimScalarRemapper> remapper = NULL;
      
      if(PTR_CAST(ossimJpegWriter, fileWriter.get()) &&
         (bm->getOutputScalarType() != OSSIM_UCHAR))
      {
         remapper = new ossimScalarRemapper(bm.get(), OSSIM_UCHAR);
         remapper->initialize();
         fileWriter->connectMyInputTo(0, remapper.get());
      }
      fileWriter->initialize();
      try
      {
         fileWriter->execute();
      }
      catch(std::exception& e)
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "band_merge: ERROR exception caught:\n"
            << e.what()
            << std::endl;
      }
      catch (...)
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "band_merge: ERROR - Unknown exception caught!"
            << std::endl;
      }
   }
   else
   {
      try
      {
         fileWriter->execute();
      }
      catch(std::exception& e)
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "band_merge: ERROR exception caught:\n"
               << e.what()
               << std::endl;
         }
      }
      catch (...)
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "band_merge: ERROR - Unknown exception caught!"
               << std::endl;
         }
      }
   }
   
   if (create_overview == true)
   {
      fileWriter->writeOverviewFile();
   }
   fileWriter->disconnect();
   fileWriter = 0;
   bm = 0;
   ossimConnectableObject::ConnectableObjectList::iterator it = ihs.begin();
   while (it != ihs.end())
   {
      (*it)->disconnect();
      (*it) = 0;
      ++it;
   }

   exit(0);
}
Exemple #6
0
int main(int argc, char* argv[])
{
   
#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
   ossimMpi::instance()->initialize(&argc, &argv);
   if (ossimMpi::instance()->getRank() == 0)
   {
      ossimNotify(ossimNotifyLevel_INFO)
         << "MPI running with "
         << ossimMpi::instance()->getNumberOfProcessors()
         << " processors..." << std::endl;
   }
#  endif
#endif
   
   std::string tempString;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);
   
   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" flips any null pixels to a valid pixel");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options] <output_type> <input_file> <output_file> <target_value> <replacement_value>");
   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
   argumentParser.getApplicationUsage()->addCommandLineOption("-o or --create-overview", "Creates and overview for the output image");
   argumentParser.getApplicationUsage()->addCommandLineOption("-c or --clamp-value", "clamp values (any pixel with value larger than input will be clamped to input)");
   argumentParser.getApplicationUsage()->addCommandLineOption("-m",  "Replacement mode (see notes below)");
   argumentParser.getApplicationUsage()->addCommandLineOption("-w",  "output tile width(only valid with tiled output types).  Must be a multiply of 16");
   
 
   static const char MODULE[] = "pixelflip:main";
   if (traceDebug()) CLOG << " Entered..." << std::endl;
   ossimInit::instance()->initialize(argc, argv);
   // Keyword list to initialize image writers with.
   ossimKeywordlist kwl;
   const char* PREFIX = "imagewriter.";
   bool create_overview = false;
   ossim_int32 tile_width = 0;
   double clamp_value = 0.0;
   bool do_clamp = false;
   ossimPixelFlipper::ReplacementMode replacement_mode =
      ossimPixelFlipper::REPLACE_BAND_IF_TARGET;


   if(argumentParser.read("-h") || argumentParser.read("--help")||(argumentParser.argc() == 1))
   {
      argumentParser.getApplicationUsage()->write(ossimNotify(ossimNotifyLevel_INFO));
      usage();
      exit(0);
   }
   while(argumentParser.read("-o") || argumentParser.read("--create-overview"))
   {
      create_overview = true;
   }
   while(argumentParser.read("-c", stringParam))
   {
      clamp_value = ossimString(tempString).toDouble();
      do_clamp = true;
   }
   while(argumentParser.read("-m", stringParam))
   {
      ossimString mode = tempString;
      mode.downcase();
      if (mode == "replace_band_if_target")
      {
         replacement_mode = ossimPixelFlipper::REPLACE_BAND_IF_TARGET;
      }
      else if (mode == "replace_band_if_partial_target")
      {
         replacement_mode =
            ossimPixelFlipper::REPLACE_BAND_IF_PARTIAL_TARGET;
      }
      else if (mode == "replace_all_bands_if_partial_target")
      {
         replacement_mode = ossimPixelFlipper::REPLACE_ALL_BANDS_IF_PARTIAL_TARGET;
      }
      else if (mode != "replace_all_targets")
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << "Invalid mode:  "
            << mode
            << "\nMode remains:  replace_band_if_target"
            << std::endl;
      }
   }
   while(argumentParser.read("-w", stringParam))
   {
      tile_width = ossimString(tempString).toInt32();
      if (tile_width % 16)
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE
            << " NOTICE:"
            << "\nTile width must be a multiple of 16!"
            << "\nDefaulting to 128"
            << std::endl;
         tile_width = 0;
      }
   }

   if(argumentParser.argc() != 6)
   {
      ossimMpi::instance()->finalize();
      
      exit(0);
   }
   //***
   // Set the writer type and the image type.
   //***
   ossimString output_type = argumentParser.argv()[1];
   output_type.downcase();
   kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str());
   // Get the input file.
   ossimFilename input_file = argumentParser.argv()[2];
   // Get the output file.
   ossimFilename    output_file = argumentParser.argv()[3];
   // Get the value to replace.
   double target_value = ossimString(argumentParser.argv()[4]).toDouble();
   // Get the replacement value.
   double replacement_value = ossimString(argumentParser.argv()[5]).toDouble();
   bool master = true;

   if (ossimMpi::instance()->getRank() != 0)
   {
      master = false;
   }
   if (master)
   {
      ossimNotify(ossimNotifyLevel_INFO)
         << "pixelflip settings:"
         << "\noutput type:        " << output_type
         << "\ninput file:         " << input_file
         << "\noutput file:        " << output_file
         << "\ntarget value:       " << target_value
         << "\nreplacement value:  " << replacement_value
         << std::endl;
      if (tile_width)
      {
         ossimNotify(ossimNotifyLevel_INFO)
            << "tile width:         " << tile_width << std::endl;
      }
      if (do_clamp)
      {
          ossimNotify(ossimNotifyLevel_INFO)
             << "clamp value:        " << clamp_value << std::endl;
      }
   }
   // Get an image handler for the input file.
   ossimRefPtr<ossimImageHandler> ih
      = ossimImageHandlerRegistry::instance()->open(ossimFilename(input_file));
   if (!ih)
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "Unsupported image file:  " << input_file
         << "\nExiting application..." << std::endl;
      ossimMpi::instance()->finalize();
      exit(0);
   }
   // Initialize the
   if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "Error reading image:  " << input_file
         << "Exiting application..." << std::endl;
      ossimMpi::instance()->finalize();
      exit(1);
   }
   ih->initialize();
   if (traceDebug())
   {
      CLOG << "DEBUG:"
           << "\nImage Handler:  " << ih->getLongName()
           << std::endl;
   }
   // Capture the bounding rectangle of the image handler.
   ossimIrect output_rect = ih->getBoundingRect(0);
   // hook up the pixel flipper to the image handler.
   ossimRefPtr<ossimPixelFlipper> pf = new ossimPixelFlipper();
   pf->connectMyInputTo(ih.get());
   pf->initialize();
   // Setup the pixel flipper target/replacement values, and replace mode.
   pf->setTargetValue(target_value);
   pf->setReplacementValue(replacement_value);
   pf->setReplacementMode(replacement_mode);
   // Setup pixel flipper clamp value
   if (do_clamp)
   {
      pf->setClampValue(clamp_value);
   }
   if (master)
   {
      ossimNotify(ossimNotifyLevel_INFO)
         << "replacement mode:   " << pf->getReplacementModeString()
         << std::endl;
   }
   ossimImageSourceSequencer* sequencer = NULL;

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
   // only allocate the slave connection if
   // the number of processors is larger than
   // 1
   //
   if(ossimMpi::instance()->getNumberOfProcessors() > 1)
   {
      if(ossimMpi::instance()->getRank()!=0)
      {
         sequencer = new ossimImageMpiSWriterSequenceConnection(NULL, 4);
      }
      else
      {
         sequencer = new ossimImageMpiMWriterSequenceConnection();
      }
   }
   else
   {
      sequencer = new ossimImageSourceSequencer();
   }
#  else
   // we will just load a serial connection if MPI is not supported.
   sequencer = new ossimImageSourceSequencer(NULL);
#  endif
#else
   sequencer = new ossimImageSourceSequencer(NULL);
#endif
   
   ossimRefPtr<ossimImageWriter> writer
      = ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);
   ossimImageFileWriter* fileWriter = PTR_CAST(ossimImageFileWriter, writer.get());
   if( fileWriter == NULL )
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "Error making an image writer..."
         << "\nExiting application..." << std::endl;
      ossimMpi::instance()->finalize();
      exit(1);
   }
   // Change out the sequencer...
   fileWriter->changeSequencer(sequencer);
   // Hook up the pixel flipper to the file writer.
   fileWriter->connectMyInputTo(0, pf.get());
   if (tile_width)
   {
      // Set the tile size...
      fileWriter->setTileSize(ossimIpt(tile_width, tile_width));
   }
   fileWriter->open(output_file);
   // Add a listener to get percent complete.
   ossimStdOutProgress prog(0, true);
   fileWriter->addListener(&prog);
   if (fileWriter->getErrorStatus() == ossimErrorCodes::OSSIM_OK)
   {
      fileWriter->initialize();
      fileWriter->setAreaOfInterest(output_rect); // Set the output rectangle.

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
      double start_time = 0.0;
      if(ossimMpi::instance()->getRank() == 0)
      {
         start_time= MPI_Wtime();
      }
#  endif
#endif

      // Filter and write the file...
      fileWriter->execute();

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI
      if(ossimMpi::instance()->getRank() == 0)
      {
         double stop_time = MPI_Wtime();
         cout << "Elapsed time: " << (stop_time-start_time) << std::endl;
      }
#  endif
#endif
   }
   else
   {
      cerr << "Error detected in the image writer..."
           << "\nExiting application..." << std::endl;
      exit(1);
   }
   if (create_overview == true)
   {
      fileWriter->writeOverviewFile();
   }

#ifdef OSSIM_HAS_MPI
#  if OSSIM_HAS_MPI   
   ossimMpi::instance()->finalize();
#  endif
#endif
   
   exit(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;
}
//*************************************************************************************************
// MAIN
//*************************************************************************************************
int main(int argc, char* argv[])
{
   ossimString tempString;
   double tempDouble, tempDouble2;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser::ossimParameter doubleParam(tempDouble);
   ossimArgumentParser::ossimParameter doubleParam2(tempDouble2);

   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);

   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+
      " Generates a bit-mask given source image and target pixel range to mask out. If the input"
      " image has overviews, then masks will be generated for all R-levels.");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+
      " [options] <input file>");

   argumentParser.getApplicationUsage()->addCommandLineOption("-d", 
      "Write mask to directory specified.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-e or --entry",
      "Give the entry(zero based) for which to build a mask. Only one entry can be processed. "
      "If the input is multi-entry and no entry was specified, entry 0 is assumed.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", 
      "Shows help");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-mode <mode>",
      "Specifies how to treat multi-band imagery when determining whether pixel will be masked "
      "according to the defined target value or range. Possible modes are: "
      "\"mask_full_and_partial_targets\" (default) | \"mask_only_full_targets\".");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-range <min> <max>", 
      "Specifies the range of pixels to target for masking out.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-value <target>", 
      "Specifies the unique pixel value to target for masking out.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-o", 
      "Write mask to file specified.  If used on a multi-entry file, given \"foo.mask\" you will "
      "get: \"foo_e0.mask\". If none specified, the input filename is used with \".mask\" "
      "extension.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--ovr-from-image", 
      "Uses exclusively the image overview data when computing subsequent overviews. "
      "Normally the mask overview from the prior level is referenced for establishing the masks at "
      "the next level.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--spec-kwl <filename>", 
      "In lieu of providing mask parameters on the command line, this option specifies a keyword "
      "list filename that contains all settings. Typically used when spawning from other process.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-x or --exclude-fullres", 
      "Excludes R0 mask computation. The mask file will start at R1.");

   if(argumentParser.read("-h") || argumentParser.read("--help"))
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      finalize(0);
   }

   if ( argumentParser.read("--version") || argumentParser.read("-v"))
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " 
         << ossimInit::instance()->instance()->version().c_str()<< std::endl;
      finalize(0);
   }

   // Fetch command line options:
   ossimFilename outputFile;
   if (argumentParser.read("-o", stringParam))
      outputFile = tempString.trim();

   ossimFilename outputDir;
   if (argumentParser.read("-d", stringParam))
      outputDir = tempString.trim();

   bool exclude_r0 = false;
   if (argumentParser.read("-x") || argumentParser.read("--exclude-fullres"))
      exclude_r0 = true;

   bool entry_specified = false;
   ossim_int32 entry = 0;
   if (argumentParser.read("-e", stringParam) || argumentParser.read("--entry", stringParam))
   {
      entry = ossimString(tempString).toUInt32();
      entry_specified = true;
   }

   double target_min = 0;
   double target_max = 0;
   if (argumentParser.read("--mask-range", doubleParam, doubleParam2))
   {
      target_min = tempDouble;
      target_max = tempDouble2;
   }

   if (argumentParser.read("--mask-value", doubleParam))
   {
      target_min = tempDouble;
      target_max = target_min;
   }

   ossimString mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET";
   ossimString mask_mode_arg;
   if (argumentParser.read("--mask-mode", stringParam))
   {
      mask_mode_arg = tempString;
      if (mask_mode_arg == "mask_full_and_partial_targets")
         mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET";
      else if (mask_mode_arg == "mask_only_full_targets")
         mask_mode = "REPLACE_ONLY_FULL_TARGETS";
      else
      {
         ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " 
            << " Unknown mask-mode <"<<mask_mode_arg<<"> specified. See usage below." << std::endl;
         argumentParser.getApplicationUsage()->write(std::cout);
         finalize(1);
      }
   }

   bool ovr_from_image = false;
   if (argumentParser.read("--ovr-from-image"))
      ovr_from_image = true;

   ossimFilename spec_kwl_file;
   if (argumentParser.read("--spec_kwl", stringParam))
      spec_kwl_file = tempString.trim();

   // Handle bad command line:
   argumentParser.reportRemainingOptionsAsUnrecognized();
   if (argumentParser.errors())
   {
      argumentParser.writeErrorMessages(std::cout);
      finalize(1);
   }
   if ((argumentParser.argc()<2) && spec_kwl_file.empty())
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      finalize(1);
   }

   // Establish input filename:
   ossimFilename inputFile;
   ossimKeywordlist kwl;
   if (spec_kwl_file.isReadable())
   {
      kwl.addFile(spec_kwl_file);
      inputFile = kwl.find(ossimKeywordNames::IMAGE_FILE_KW);
      outputFile = kwl.find(ossimKeywordNames::OUTPUT_FILE_KW);
   }
   else
   {
      inputFile = argv[1];
   }

   // Establish the input image handler:
   ossimRefPtr<ossimImageHandler> handler = ossimImageHandlerRegistry::instance()->open(inputFile);
   if (!handler.valid())
   {
      ossimNotify(ossimNotifyLevel_FATAL)<<argumentParser.getApplicationName().c_str()
         <<" Error encountered opening input file <"<<inputFile<<">."<<endl;
      finalize(1);
   }

   // Establish output filename:
   if (outputFile.empty())
      outputFile = handler->getFilenameWithThisExtension("mask", entry_specified);
   if (!outputDir.empty())
      outputFile.setPath(outputDir);
   else
   {
      ossimFilename path (outputFile.path());
      if (path.empty())
         outputFile.setPath(inputFile.path());
   }

   // Consider input file with multiple entries:
   std::vector<ossim_uint32> entryList;
   handler->getEntryList(entryList); 
   if (entryList.size() <= entry)
   {
      ossimNotify(ossimNotifyLevel_FATAL)<<argumentParser.getApplicationName().c_str()
         <<" Entry specified <"<<entry<<"> exceeds total number of entries available <"
         <<entryList.size()<<">. Aborting..."<<endl;
      finalize(1);
   }
   handler->setCurrentEntry(entry); 


   // Establish a keywordlist to pass to the mask builder. This KWL may have already been specified
   // on the command line with --spec_kwl option:
   kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, outputFile.chars()); // may overwrite same value
   if (kwl.getSize() == 0)
   {
      kwl.add(ossimKeywordNames::IMAGE_FILE_KW, inputFile.chars());
      ossimString target_str (ossimString::toString(target_min)+" "+ossimString::toString(target_max));
      kwl.add(ossimPixelFlipper::PF_TARGET_RANGE_KW, target_str.chars());
      kwl.add(ossimPixelFlipper::PF_REPLACEMENT_MODE_KW, mask_mode.chars());
      kwl.add(ossimPixelFlipper::PF_REPLACEMENT_VALUE_KW, (int) 0);
      if (exclude_r0)
         kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 1);
      else
         kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 0);
   }

   // Instantiate the bit mask processor and write out the mask file:
   ossimRefPtr<ossimBitMaskWriter> mask_writer = new ossimBitMaskWriter;
   mask_writer->loadState(kwl);
   mask_writer->connectMyInputTo(handler.get());

   // Need to loop over all R-levels. Use a sequencer:
   ossimRefPtr<ossimImageSourceSequencer> sequencer =  new ossimImageSourceSequencer(handler.get());
   sequencer->initialize();
   int num_rlevels = handler->getNumberOfDecimationLevels();
   int num_tiles = sequencer->getNumberOfTiles();
   int tile_idx = 0;
   int percent_complete = 0;
   ossimRefPtr<ossimImageData> tile = 0;

   int start_res = 0;
   if (exclude_r0)
   {
      start_res = 1;
      num_tiles = (num_tiles+3)/4;
   }

   for (int r=start_res; r<num_rlevels; r++)
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<<"\nProcessing R-level "<<r<<"... "<<endl;

      // Set the area of interest to the full image rectangle at this R-level:
      ossimIrect rect (handler->getBoundingRect(r));
      sequencer->setAreaOfInterest(rect);
      sequencer->setToStartOfSequence();
      do
      {
         tile = sequencer->getNextTile(r);
         mask_writer->generateMask(tile, r);

         percent_complete = 100 * tile_idx++/num_tiles;
         ossimNotify(ossimNotifyLevel_NOTICE)<<percent_complete<< "%\r";
      } 
      while(tile.valid());
      tile_idx = 0;
      num_tiles = (num_tiles+3)/4;
      if (num_tiles == 0)
         num_tiles = 1;

      // Check if additional overviews are to be generated directly from the mask at first R-level:
      if ((r == start_res) && !ovr_from_image)
      {
         ossimNotify(ossimNotifyLevel_NOTICE)<<"\nBuilding remaining overviews from initial mask..."
            <<endl;
         mask_writer->buildOverviews(num_rlevels);
         break;
      }
   }

   // Finished sequencing all levels, ready to write out the mask buffers:
   mask_writer->close();
   ossimNotify(ossimNotifyLevel_NOTICE)<<"\nSuccessfully wrote mask file to <"<<outputFile
      <<">. Finished."<<endl;
   
   finalize(0);
}
int main(int argc, char *argv[])
{
   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);
   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+" GUI application for the ossim core library");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+" [options]");
   argumentParser.getApplicationUsage()->addCommandLineOption("-project","OPTIONAL: project file");
   argumentParser.getApplicationUsage()->addCommandLineOption("No '-','*.gcl' file","untagged project file with 'gcl' extension");
  
   if (argumentParser.read("-h") || argumentParser.read("--help"))
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      exit(0);
   }

   // project file
   std::string tempString;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimString projFile;
   while(argumentParser.read("-project", stringParam))
   {
      projFile = tempString;
   }

   // additional check for stand-alone ".gcl" project file
   // or list of images
   std::vector<ossimString> ilist;
   if (argc > 1)
   {
      for (int k=1; k<argc; ++k)
      {
         tempString = argv[k];
         if (tempString.find(".gcl") != std::string::npos)
         {
            projFile = tempString;
         }
         else
         {
            ilist.push_back(tempString);
         }
      }
   }


   argumentParser.reportRemainingOptionsAsUnrecognized();   
   QApplication app(argc, argv);
   QSplashScreen splash(QPixmap(":/splash/GeoCellSplash.png"));
   splash.setWindowFlags(splash.windowFlags()|Qt::WindowStaysOnTopHint);
   splash.show();
#ifdef OSSIMQT_USE_WINDOWS_STYLE
   QWindowsStyle *style = new QWindowsStyle();
   app.setStyle(style);
#endif
   ossimObjectFactoryRegistry::instance()->registerFactory(ossimGui::OssimObjectFactory::instance());
   ossimGui::MainWindow*  mainWindow = new ossimGui::MainWindow();
   
   // Load command line project file or image files if present
   if (projFile.size()>0)
   {
      mainWindow->loadProjectFile(projFile);
   }
   else if (ilist.size()>0)
   {
      mainWindow->loadImageFileList(ilist);
   }
   mainWindow->show();

   OpenThreads::Thread::microSleep((1000*1000));
   //splash.finish(mainWindow);
   splash.close();
   int result = app.exec();
   ossimInit::instance()->finalize();

   return result;
}
int main(int argc, char* argv[])
{
   ossimInit::instance()->initialize(argc, argv);
   
   osg::ref_ptr<ossimPlanetGrid> grid = new ossimPlanetAdjustableCubeGrid(ossimPlanetAdjustableCubeGrid::MEDIUM_CAP);  
   
   ossimString tempString;
   osg::ArgumentParser::Parameter stringParam(tempString);
   
   osg::ArgumentParser arguments(&argc,argv);
   arguments.getApplicationUsage()->addCommandLineOption("--terrain-requests-per-frame", 
                                                         "Specify the number of requests to apply to the terrain graph per frame");
   arguments.getApplicationUsage()->addCommandLineOption("--terrain-threads", 
                                                         "Specify the number of terrain threads to use  Specify between 1 and 3 for now");
	arguments.getApplicationUsage()->addCommandLineOption("--add-image", "Image to add");
	arguments.getApplicationUsage()->addCommandLineOption("--polar-cap", "Values can be LOW, MEDIUM_LOW, MEDIUM, MEDIUM_HIGH, HIGH");
	arguments.getApplicationUsage()->addCommandLineOption("--osg-view", "no ossimPlanet just use osg's readNode to add to scene");
	arguments.getApplicationUsage()->addCommandLineOption("--split-merge-speed", "enumeration that maps to split merge ratio.  Values can be LOW, MEDIUM_LOW, MEDIUM, MEDIUM_HIGH, and HIGH");
	arguments.getApplicationUsage()->addCommandLineOption("--elevation-density-type", "enumeration that maps amount of elevation posts to use per patch.  Values can be LOW, MEDIUM_LOW, MEDIUM, MEDIUM_HIGH, and HIGH");
	arguments.getApplicationUsage()->addCommandLineOption("--texture-density-type", "enumeration that maps amount of texture samples to use per patch.  Values can be LOW, MEDIUM_LOW, MEDIUM, MEDIUM_HIGH, and HIGH");
	arguments.getApplicationUsage()->addCommandLineOption("--elevation-exaggeration", "Scales the elevation by this factor");
	arguments.getApplicationUsage()->addCommandLineOption("--cull-amount", "Sets the amount of culling in the graph.  Values can be low, medium, high");
	arguments.getApplicationUsage()->addCommandLineOption("--min-time-compile", "sets the minimum time to compile per frame in seconds.  So 3 milliseconds is .003");
	arguments.getApplicationUsage()->addCommandLineOption("--animation-path", "Reads in an animation path");
	arguments.getApplicationUsage()->addCommandLineOption("--animation-node", "Reads in an animation node");
	arguments.getApplicationUsage()->addCommandLineOption("--add-kml", "Adds a kml layer to planet");
	arguments.getApplicationUsage()->addCommandLineOption("--moon-image", "Moon image used for the moon sprite for the Ephemeris");
	arguments.getApplicationUsage()->addCommandLineOption("--sun-image", "Moon image used for the moon sprite for the Ephemeris");
	arguments.getApplicationUsage()->addCommandLineOption("--visibility", "Visibility in meters");
	arguments.getApplicationUsage()->addCommandLineOption("--fog-near", "near plane for fog attenuation in meters");
	arguments.getApplicationUsage()->addCommandLineOption("--cloud-coverage", "integer value used to adjust the perlin noise");
	arguments.getApplicationUsage()->addCommandLineOption("--cloud-sharpness", "float value (0..1) used to adjust the perlin noise");
	arguments.getApplicationUsage()->addCommandLineOption("--cloud-altitude", "Altitude of the cloud");
	arguments.getApplicationUsage()->addCommandLineOption("--add-cloud", "float value (0..1) used to adjust the perlin noise");
	arguments.getApplicationUsage()->addCommandLineOption("--fog-near", "near plane for fog attenuation in meters");
   
   
   
	ossim_uint32 helpType = 0;
	
	if ((helpType = arguments.readHelpType()))
	{
		arguments.getApplicationUsage()->write(std::cout, helpType);
		return 1;
	}
	
   
   osg::MatrixTransform* rootScene = new osg::MatrixTransform();
   
   // osg::DisplaySettings::instance()->setRGB(true);
   // osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts(1);
   ossimPlanetTerrainGeometryTechnique* technique = new ossimPlanetTerrainGeometryTechnique();
   ossimPlanetViewer viewer(arguments);
   ossimPlanetTerrain::CullAmountType cullAmount = ossimPlanetTerrain::HIGH_CULL;
   ossimPlanetTerrain::SplitMergeSpeedType splitMergeSpeed = ossimPlanetTerrain::LOW_SPEED;
   ossimPlanetTerrain::ElevationDensityType elevationDensity = ossimPlanetTerrain::LOW_ELEVATION_DENSITY;
   ossimPlanetTerrain::TextureDensityType textureDensity = ossimPlanetTerrain::MEDIUM_TEXTURE_DENSITY;
   std::vector<osg::ref_ptr<ossimPlanetAnimationPath> > animationPathArray;
   std::vector<osg::ref_ptr<ossimPlanetPointModel> > pointModels;
   std::vector<osg::ref_ptr<ossimPlanetAnimatedPointModel> > animatedPointModels;
   osg::ref_ptr<ossimPlanetGeoRefModel> model;
   osg::ref_ptr<ossimPlanetManipulator> manipulator = new ossimPlanetManipulator();
   osg::ref_ptr<ossimPlanetAnnotationLayer> annotationLayer =new ossimPlanetAnnotationLayer();
   osg::ref_ptr<ossimPlanetKmlLayer> kmlLayer;
   std::vector<ossimFilename> kmlFiles;
   ossimFilename flightgearFile = "";
   osg::ref_ptr<ossimPlanet> planet;
   double elevationExaggeration = 1.0;
   double minTimeToCompilePerFrame = 10000;
   ossimFilename sunTextureFile = "";
   ossimFilename moonTextureFile = "";
   ossim_float64 visibility = 1000000000.0;
   ossim_float64 fogNear = 0.0;
   ossim_int32 cloudCoverage = 20;
   ossim_float64 cloudSharpness = .95;
   ossim_float64 cloudAltitude = 20000;
   bool addCloud = false;
   
   if(arguments.read("--cloud-coverage", stringParam))
   {
      cloudCoverage = tempString.toDouble();
   }
   if(arguments.read("--cloud-sharpness", stringParam))
   {
      cloudSharpness = tempString.toDouble();
   }
   if(arguments.read("--cloud-altitude", stringParam))
   {
      cloudAltitude = tempString.toDouble();
   }
   if(arguments.read("--add-cloud"))
   {
      addCloud = true;
   }
   
   if(arguments.read("--visibility", stringParam))
   {
      visibility = tempString.toDouble();
   }
   if(arguments.read("--fog-near", stringParam))
   {
      fogNear = tempString.toDouble();
   }
   while(arguments.read("--add-kml", stringParam))
   {
      kmlFiles.push_back(ossimFilename(tempString));
   }
   if(arguments.read("--animation-node", stringParam))
   {
      flightgearFile = ossimFilename(tempString);
   }
   while(arguments.read("--animation-path", stringParam))
   {
      osg::ref_ptr<ossimPlanetAnimationPath> animationPath = new ossimPlanetAnimationPath;
      
      if(animationPath->openAnimationPathByXmlDocument(ossimFilename(tempString)))
      {
         animationPathArray.push_back(animationPath.get());
      }
   }
   if(arguments.read("--moon-image", stringParam))
   {
      moonTextureFile = ossimFilename(tempString);
   }
   if(arguments.read("--sun-image", stringParam))
   {
      sunTextureFile = ossimFilename(tempString);
   }
   if(arguments.read("--min-time-compile", stringParam))
   {
      minTimeToCompilePerFrame = tempString.toDouble();
   }
   if(arguments.read("--elevation-exaggeration", stringParam))
   {
      elevationExaggeration = tempString.toDouble();
   }
   if(arguments.read("--texture-density-type", stringParam))
   {
      tempString = tempString.downcase();
      if(tempString == "low")
      {
         textureDensity = ossimPlanetTerrain::LOW_TEXTURE_DENSITY;
      }
      else if(tempString == "medium_low")
      {
         textureDensity = ossimPlanetTerrain::MEDIUM_LOW_TEXTURE_DENSITY;
      }
      else if(tempString == "medium")
      {
         textureDensity = ossimPlanetTerrain::MEDIUM_TEXTURE_DENSITY;
      }
      else if(tempString == "medium_high")
      {
         textureDensity = ossimPlanetTerrain::MEDIUM_HIGH_TEXTURE_DENSITY;
      }
      else if(tempString == "high")
      {
         textureDensity = ossimPlanetTerrain::HIGH_TEXTURE_DENSITY;
      }
   }
   if(arguments.read("--elevation-density-type", stringParam))
   {
      tempString = tempString.downcase();
      if(tempString == "low")
      {
         elevationDensity = ossimPlanetTerrain::LOW_ELEVATION_DENSITY;
      }
      else if(tempString == "medium_low")
      {
         elevationDensity = ossimPlanetTerrain::MEDIUM_LOW_ELEVATION_DENSITY;
      }
      else if(tempString == "medium")
      {
         elevationDensity = ossimPlanetTerrain::MEDIUM_ELEVATION_DENSITY;
      }
      else if(tempString == "medium_high")
      {
         elevationDensity = ossimPlanetTerrain::MEDIUM_HIGH_ELEVATION_DENSITY;
      }
      else if(tempString == "high")
      {
         elevationDensity = ossimPlanetTerrain::HIGH_ELEVATION_DENSITY;
      }
   }
   if(arguments.read("--split-merge-speed", stringParam))
   {
      tempString = tempString.downcase();
      if(tempString == "low")
      {
         splitMergeSpeed = ossimPlanetTerrain::LOW_SPEED;
      }
      
      else if(tempString == "medium_low")
      {
         splitMergeSpeed = ossimPlanetTerrain::MEDIUM_LOW_SPEED;
      }
      else if(tempString == "medium")
      {
         splitMergeSpeed = ossimPlanetTerrain::MEDIUM_SPEED;
      }
      else if(tempString == "medium_high")
      {
         splitMergeSpeed = ossimPlanetTerrain::MEDIUM_HIGH_SPEED;
      }
      else if(tempString == "high")
      {
         splitMergeSpeed = ossimPlanetTerrain::HIGH_SPEED;
      }
   }
   if(arguments.read("--polar-cap", stringParam))
   {
      tempString = tempString.downcase();
      if(tempString == "low")
      {
         grid = new ossimPlanetAdjustableCubeGrid(ossimPlanetAdjustableCubeGrid::LOW_CAP);
      }
      else if(tempString == "medium_low")
      {
         grid = new ossimPlanetAdjustableCubeGrid(ossimPlanetAdjustableCubeGrid::MEDIUM_LOW_CAP);
      }
      else if(tempString == "medium")
      {
         grid = new ossimPlanetAdjustableCubeGrid(ossimPlanetAdjustableCubeGrid::MEDIUM_CAP);
      }
      else if(tempString == "medium_high")
      {
         grid = new ossimPlanetAdjustableCubeGrid(ossimPlanetAdjustableCubeGrid::MEDIUM_HIGH_CAP);
      }
      else if(tempString == "high")
      {
         grid = new ossimPlanetAdjustableCubeGrid(ossimPlanetAdjustableCubeGrid::HIGH_CAP);
      }
   }
   if(arguments.read("--cull-amount", stringParam))
   {
      tempString = tempString.downcase();
      if(tempString == "none")
      {
         cullAmount = ossimPlanetTerrain::NO_CULL;
      }
      if(tempString == "low")
      {
         cullAmount = ossimPlanetTerrain::LOW_CULL;
      }
      else if(tempString == "medium_low")
      {
         cullAmount = ossimPlanetTerrain::MEDIUM_LOW_CULL;
      }
      else if(tempString == "medium")
      {
         cullAmount = ossimPlanetTerrain::MEDIUM_CULL;
      }
      else if(tempString == "medium_high")
      {
         cullAmount = ossimPlanetTerrain::MEDIUM_HIGH_CULL;
      }
      else if(tempString == "high")
      {
         cullAmount = ossimPlanetTerrain::HIGH_CULL;
      }
   }
   
   
   planet = new ossimPlanet();
   model = planet->model().get();
   osg::ref_ptr<ossimPlanetTerrain> terrain = new ossimPlanetTerrain(grid.get());
   terrain->setTerrainTechnique(technique);
   terrain->setCullAmountType(cullAmount);
   terrain->setSplitMergeSpeedType(splitMergeSpeed);
   terrain->setTextureDensityType(textureDensity);
   terrain->setElevationDensityType(elevationDensity);
   terrain->setElevationExaggeration(elevationExaggeration);
   terrain->setMinimumTimeToCompilePerFrameInSeconds(minTimeToCompilePerFrame);
   terrain->setPrecompileEnabledFlag(false);
   //terrain->setTextureLayer(0, group);
   terrain->initElevation();
   planet->addChild(terrain.get());
   planet->addChild(annotationLayer.get());
   rootScene->addChild(planet.get());
   viewer.setSceneData( rootScene );
   
   osg::ref_ptr<osg::StateSet> sset = planet->getOrCreateStateSet();
   if(arguments.read("--terrain-requests-per-frame", stringParam))
   {
      ossim_int32 requestsPerFrame = ossimString(tempString).toInt32();
      if(requestsPerFrame <= 0)
      {
         requestsPerFrame = 1;
      }
      viewer.setTerrainMaxNumberOfOperationsToApplyToGraphPerFrame(requestsPerFrame);
   }
   while(arguments.read("--add-image", stringParam))
   {
      osg::ref_ptr<ossimPlanetTextureLayer> layer = ossimPlanetTextureLayerRegistry::instance()->createLayer(tempString);
      if(layer.valid())
      {
         viewer.addImageTexture(layer.get());
         
      }
   }	
   viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
   viewer.addEphemeris(ossimPlanetEphemeris::SUN_LIGHT
                       //|ossimPlanetEphemeris::MOON_LIGHT
                       //|ossimPlanetEphemeris::AMBIENT_LIGHT
                       // |ossimPlanetEphemeris::SUN
                       |ossimPlanetEphemeris::MOON
                       |ossimPlanetEphemeris::SKY
                       |ossimPlanetEphemeris::FOG
                       );
   ossimLocalTm date;
   date.now();
   viewer.ephemeris()->setDate(date);

   osg::ref_ptr<osg::GraphicsContext> pbuffer;
   osg::Image *image = new osg::Image();

   osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
   traits->readDISPLAY();
   traits->alpha = 8;
   traits->width = 1920;
   traits->height = 1080;
   traits->pbuffer = true;
   pbuffer = osg::GraphicsContext::createGraphicsContext(traits.get());
   manipulator->setEventHandlingFlag(true);
   manipulator->viewMatrixBuilder()->setLookAxis(ossimPlanetViewMatrixBuilder::LOOK_AXIS_Y);
   viewer.setCameraManipulator(manipulator.get());
   
   osg::ref_ptr<CustomRenderer> renderer; 
   if (pbuffer.valid())
   {
      osg::Camera *camera = viewer.getCamera();
      renderer = new CustomRenderer( camera );
      camera->setGraphicsContext(pbuffer.get());
      camera->setDrawBuffer(GL_FRONT);
      camera->setReadBuffer(GL_FRONT);
      camera->setViewport(new osg::Viewport(0,0,traits->width,traits->height));
      double fovy, aspectRatio, near, far;
      camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, near, far);
      double newAspectRatio = double(traits->width) / double(traits->height);
      double aspectRatioChange = newAspectRatio / aspectRatio;
      if (aspectRatioChange != 1.0)
         camera->getProjectionMatrix() *=
         osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
      
      camera->attach(osg::Camera::COLOR_BUFFER0, image);
      if(renderer.valid()) camera->setRenderer( renderer.get() );
   
      viewer.realize();
   }
   else 
   {
      std::cout << "Invalid pbuffer!!!!!!!!!!!!!!!!!!!!" << std::endl;
      exit(1);
   }
   double time = 0.0;
   GLenum pixelFormat = GL_RGB;
   bool gotTheImage = false;
   manipulator->viewMatrixBuilder()->setLookFrom(osg::Vec3d(37,87,15000),
                                                 osg::Vec3d(0, 0.0, 0.0),
                                                 0);   
   manipulator->viewMatrixBuilder()->setLookTo(osg::Vec3d(38,87,5500));   
   
   if(!viewer.done())
   {
      osg::Timer_t lastFrameTick = osg::Timer::instance()->tick();
      viewer.frame();
      //viewer.advance();
      if(renderer.valid())renderer->setCullOnly( true );
      while(viewer.getAndSetRedrawFlag(false)) 
      {
         viewer.frame();
//         viewer.eventTraversal();
//         viewer.updateTraversal();
//         viewer.renderingTraversals();
      }
      if(renderer.valid()) renderer->setCullOnly( false );
      viewer.frame();
      osg::Timer_t frameTick = osg::Timer::instance()->tick();
      double delta = osg::Timer::instance()->delta_s(lastFrameTick, frameTick);
      std::cout << "delta = " << delta << std::endl;
      if(!gotTheImage)
      {
         unsigned char* buffer = image->data();
         ossimRefPtr<ossimImageData> imageData = new ossimImageData(0,OSSIM_UINT8, 4, image->s(), image->t());
         imageData->initialize();
         
         imageData->loadTile(image->data(), ossimIrect(0,0,image->s()-1, image->t()-1), OSSIM_BIP);
         imageData->validate();
         ossimRefPtr<ossimMemoryImageSource> memSource = new ossimMemoryImageSource();
         memSource->setImage(imageData.get());
         ossimRefPtr<ossimJpegWriter> jpegWriter = new ossimJpegWriter();
         jpegWriter->connectMyInputTo(0, memSource.get());
         jpegWriter->setFilename(ossimFilename("/tmp/output.jpg"));
         jpegWriter->execute();
         
         delta = osg::Timer::instance()->delta_s(frameTick, osg::Timer::instance()->tick());
         
         std::cout << "SAVED /tmp/output.jpg in " << delta << " seconds" <<std::endl;
      }
   }
}