Beispiel #1
0
// Note: throws ossimException on error.
void ossimRpfUtil::writeDotRpfFiles( const ossimFilename& aDotTocFile,
                                     const ossimFilename& outputDir )
{
   static const char MODULE[] = "ossimRpfUtil::writeDotRpfFiles";

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered..."
         << "\na.toc file:        " << aDotTocFile
         << "\noutput directory:  " << outputDir
         << "\n";
   }
   
   // Parse the a.toc file:
   ossimRefPtr<ossimRpfToc> toc = new ossimRpfToc();
   
   if ( toc->parseFile(aDotTocFile) != ossimErrorCodes::OSSIM_OK )
   {
      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e+= aDotTocFile.string();
      throw ossimException(e);
   }

   if ( outputDir.expand().exists() == false )
   {
      if ( !outputDir.createDirectory(true, 0775) )
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not create directory: ";
         e+= outputDir.c_str();
         throw ossimException(e);
      }
   }

   //---
   // Go through the entries...
   //---
   ossim_uint32 entries = toc->getNumberOfEntries();
   for (ossim_uint32 entry = 0; entry < entries; ++entry)
   {
      const ossimRpfTocEntry* tocEntry = toc->getTocEntry(entry);
      if (tocEntry)
      {
         if ( tocEntry->isEmpty() == false )
         {
            writeDotRpfFile(toc.get(), tocEntry, outputDir, entry);
         }
      }
      else
      {
         std::string e = MODULE;
         e += " ERROR:  Null entry: ";
         e += ossimString::toString(entry).string();
         throw ossimException(e);
      }
   }
   
} // End: ossimRpfUtil::writeDotRpfFiles
Beispiel #2
0
//*************************************************************************************************
//! Throws an exception if datum code is not handled yet.
//*************************************************************************************************
void ossimEpsgProjectionDatabase::checkForUnhandledDatum(const ProjRecord& record) const
{
   if (!record.datumValid)
   {
      ossimString errMsg ("ossimEpsgProjectionDatabase -- "
         "EPSG database parsing of datum code has not been implemented for EPSG code=");
      errMsg += ossimString::toString(record.code);
      throw(ossimException(errMsg));
   }
}
void ossimOpjCompressor::openJp2Codestream()
{
   //---
   // Start compression...
   // Matching "opj_end_compress" is in ossimOpjCompressor::finish().
   //---
   if ( !opj_start_compress(m_codec, m_image, m_stream) )
   {
      std::string errMsg = "ossimOpjCompressor::openJp2Codestream ERROR: opj_start_compress failed!";
      throw ossimException(errMsg);
   }
}
void ossimNmeaMessage::parseMessage(std::istream& in)throw(ossimException)
{
    ossim::skipws(in);
    m_validCheckSum = false;
    m_message = "";
    if(!isValidStartChar(static_cast<char>(in.peek())))
    {
        throw ossimException(ossimString("Starting NMEA messsage indicator not found, expected one of ") +
                             m_startChars + " but found " +
                             ossimString((char)in.peek()));
    }

    char c = static_cast<char>(in.get());
    while(((c!='\n')&&(c!='\r'))&&
            !in.eof()&&!in.bad())
    {
        m_message += c;
        c = static_cast<char>(in.get());
    }
    std::string::iterator iter = std::find(m_message.begin(), m_message.end(), '*');

    if(iter != m_message.end())
    {
        setFields(m_message.begin()+1, m_message.end());
        ossim_uint32 check = checksum(m_message.begin()+1, iter);
        std::ostringstream out;
        out << std::setw(2) << std::setfill('0') << std::hex << check;
        std::string::iterator endChecksumIter = iter+1;
        while((endChecksumIter!= m_message.end())&&(*endChecksumIter!=',')) ++endChecksumIter;
        if(out.str() == ossimString(iter+1, endChecksumIter).downcase())
        {
            m_validCheckSum = true;
        }
    }
    else
    {
        throw ossimException("Terminating * indicator for cbecksum not found in NMEA message format");
    }
}
Beispiel #5
0
const ossimDatum* ossimFgdcXmlDoc::createOssimDatum(const ossimString& s) const
{
   ossimString horizdn = s.downcase();
   ossimString datumCode;
   if ( horizdn == "north american datum of 1983" )
   {
      datumCode = "NAR-C";
   }
   else if ( horizdn == "north american datum of 1927" )
   {
      datumCode = "NAS-C";
   }
   else if ( horizdn == "wgs84")
   {
      datumCode = "WGE";
   }
   else
   {
      std::string errMsg = "ossimFgdcXmlDoc::createOssimDatum ERROR: Unhandled datum: ";
      errMsg += horizdn.string();
      throw ossimException(errMsg);
   }
   return ossimDatumFactoryRegistry::instance()->create(datumCode);   
}
// Takes a codestream and decompresses band at a time.
bool ossim::copyRegionToTile(kdu_core::kdu_codestream& codestream,
                             int discard_levels,
                             kdu_core::kdu_thread_env* threadEnv,
                             kdu_core::kdu_thread_queue* threadQueue,
                             ossimImageData* destTile)
{
   bool result = true;

   if ( destTile && codestream.exists())// && threadEnv && threadQueue )
   {
      try // Kakadu throws exceptions...
      {
         kdu_core::kdu_dims region;
         getDims(destTile->getImageRectangle(), region);

         kdu_core::kdu_dims clipRegion;
         if ( clipRegionToImage(codestream,
                                region,
                                discard_levels,
                                clipRegion) )
         {
            if (region != clipRegion)
            {
               // Not filling whole tile.
               destTile->makeBlank();
            }
            
            const ossimScalarType SCALAR = destTile->getScalarType();
            const ossim_uint32 BANDS = destTile->getNumberOfBands();
            
            kdu_supp::kdu_channel_mapping* mapping = 0;
            int max_layers = INT_MAX;
            kdu_core::kdu_coords expand_numerator(1,1);
            kdu_core::kdu_coords expand_denominator(1,1);
            bool precise = true;
            kdu_core::kdu_component_access_mode access_mode =
               kdu_core::KDU_WANT_OUTPUT_COMPONENTS;
            bool fastest = false;
            
            //---
            // band loop:
            // Note: At some point we may want to be a band selector;
            // in which case, we would loop through the band list.
            // For now just go through all bands and let the ossimBandSelector
            // weed them out.
            //---
            for (ossim_uint32 band = 0; band < BANDS; ++band)
            {
               int single_component = band;
            
               // Start the kdu_region_decompressor.
               kdu_supp::kdu_region_decompressor krd;
               
               if ( krd.start( codestream,
                               mapping,
                               single_component,
                               discard_levels,
                               max_layers,
                               clipRegion,
                               expand_numerator,
                               expand_denominator,
                               precise,
                               access_mode,
                               fastest,
                               threadEnv,
                               threadQueue )
                    == false)
               {
                  std::string e = "kdu_region_decompressor::start error!";
                  throw(ossimException(e));
               }
               
               vector<int> channel_offsets(1);
               channel_offsets[0] = 0;
               int pixel_gap = 1;
               kdu_core::kdu_coords buffer_origin;
               buffer_origin.x = destTile->getImageRectangle().ul().x;
               buffer_origin.y = destTile->getImageRectangle().ul().y;
               int row_gap = region.size.x;
               int suggested_increment = static_cast<int>(destTile->getSize());
               int max_region_pixels = suggested_increment;
               kdu_core::kdu_dims incomplete_region = clipRegion;
               kdu_core::kdu_dims new_region;
               bool measure_row_gap_in_pixels = true;
               
               // For signed int set precision bit to 0 for kakadu.
               int precision_bits = (SCALAR != OSSIM_SINT16) ? codestream.get_bit_depth(0, true) : 0;
               
               switch (SCALAR)
               {
                  case OSSIM_UINT8:
                  {
                     // Get pointer to the tile buffer.
                     kdu_core::kdu_byte* buffer = destTile->getUcharBuf(band);
                     
                     while ( !incomplete_region.is_empty() )
                     {
                        if ( krd.process( buffer,
                                          &channel_offsets.front(),
                                          pixel_gap,
                                          buffer_origin,
                                          row_gap,
                                          suggested_increment,
                                          max_region_pixels,
                                          incomplete_region,
                                          new_region,
                                          precision_bits,
                                          measure_row_gap_in_pixels ) )
                        {
                           break;
                        }
                     }

                     if( threadEnv && threadQueue)
                     {
                        //---
                        // Wait for all queues descended from `root_queue' to identify themselves
                        // as "finished" via the `kdu_thread_queue::all_done' function.
                        //---
                        threadEnv->join(threadQueue, true);
                     }
                     
                     // Validate the tile.
                     destTile->validate();

                     break;
                  }
                  case OSSIM_USHORT11:
                  case OSSIM_UINT16:
                  case OSSIM_SINT16:   
                  {
                     // Get pointer to the tile buffer.
                     kdu_core::kdu_uint16* buffer =
                        static_cast<kdu_core::kdu_uint16*>(destTile->getBuf(band));
                     
                     while ( !incomplete_region.is_empty() )
                     {
                        //---
                        // Note: precision_bits set to 0 to indicate "signed" data
                        // for the region decompressor.
                        //---
                        if ( krd.process( buffer,
                                          &channel_offsets.front(),
                                          pixel_gap,
                                          buffer_origin,
                                          row_gap,
                                          suggested_increment,
                                          max_region_pixels,
                                          incomplete_region,
                                          new_region,
                                          precision_bits,
                                          measure_row_gap_in_pixels ) == false )
                        {
                           break;
                        }
                     }
                     
                     //---
                     // Wait for all queues descended from `root_queue' to identify themselves
                     // as "finished" via the `kdu_thread_queue::all_done' function.
                     //---
                     if( threadEnv && threadQueue)
                     {
                        threadEnv->join(threadQueue, true);
                     }
                     
                     // Validate the tile.
                     destTile->validate();
                  
                     break;
                  }
                  case OSSIM_SINT32:
                  case OSSIM_FLOAT32:
                  {
                     //---
                     // NOTES:
                     // 1) Signed 32 bit integer data gets normalized when compressed
                     //    so use the same code path as float data.
                     // 2) Cannot call "ossimImageData::getFloatBuf" as it will return a
                     //    null pointer if the destination tile is OSSIM_SINT32 scalar type.
                     //---
                     
                     // Get pointer to the tile buffer.
                     ossim_float32* buffer = static_cast<ossim_float32*>(destTile->getBuf(band));
                     
                     while ( !incomplete_region.is_empty() )
                     {
                        //---
                        // Note: precision_bits set to 0 to indicate "signed" data
                        // for the region decompressor.
                        //---
                        if ( krd.process( buffer,
                                          &channel_offsets.front(),
                                          pixel_gap,
                                          buffer_origin,
                                          row_gap,
                                          suggested_increment,
                                          max_region_pixels,
                                          incomplete_region,
                                          new_region,
                                          true, // normalize
                                          measure_row_gap_in_pixels ) == false )
                        {
                           break;
                        }
                     }
               
                     if( threadEnv && threadQueue)
                     {
                        //---
                        // Wait for all queues descended from `root_queue' to identify themselves
                        // as "finished" via the `kdu_thread_queue::all_done' function.
                        //---
                        threadEnv->join(threadQueue, true);
                     }
               
                     // Un-normalize.
                     ossim::unNormalizeTile(destTile);
                     
                     // Validate the tile.
                     destTile->validate();
                     
                     break;
                  }
                  
                  default:
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << __FILE__ << " " << __LINE__ << " Unhandle scalar: "
                        << destTile->getScalarType() << "\n";
                     result = false;
                     break;
                  }
         
               } // End of:  switch (theScalarType)
            
               // Every call to kdu_region_decompressor::start has a finish.
               if ( krd.finish() == false )
               {
                  result = false;
                  ossimNotify(ossimNotifyLevel_WARN)
                     << __FILE__ << " " << __LINE__
                     << " kdu_region_decompressor::proces error!" << std::endl;
               }
               
         
            } // End of band loop.
         }
         else // No region intersect with image.
         {
            destTile->makeBlank();
         }
         
      } // Matches: try{ ...

      // Catch and rethrow exceptions.
      catch( const ossimException& /* e */ )
      {
         throw;
      }
      catch ( kdu_core::kdu_exception exc )
      {
         // kdu_exception is an int typedef.
         if ( threadEnv != 0 )
         {
            threadEnv->handle_exception(exc);
         }
         ostringstream e;
         e << "Caught exception from kdu_region_decompressor: " << exc << "\n";
         throw ossimException( e.str() );
         
      }
      catch ( std::bad_alloc& )
      {
         if ( threadEnv != 0 )
         {
            threadEnv->handle_exception(KDU_MEMORY_EXCEPTION);
         }
         std::string e =
            "Caught exception from kdu_region_decompressor: std::bad_alloc";
         throw ossimException( e );
      }
      catch( ... )
      {
         std::string e =
            "Caught unhandled exception from kdu_region_decompressor";
         throw ossimException(e);
      }
   }
   else  // no codestream
   {
      result = false;
   }

#if 0  /* Please leave for serious debug. (drb) */
   if (destTile)
   {
      static int tileNumber = 0;
      if (destTile)
      {
         ossimFilename f = "tile-dump";
         f += ossimString::toString(tileNumber);
         f += ".ras";
         if (destTile->write(f))
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "wrote: " << f << std::endl;
            ++tileNumber;
         }
      }
   }
#endif
   
   return result;

} // End: ossim::copyRegionToTile
Beispiel #7
0
bool ossim::opj_decode( std::ifstream* in,
                        const ossimIrect& rect,
                        ossim_uint32 resLevel,
                        ossim_int32 format, // OPJ_CODEC_FORMAT
                        std::streamoff fileOffset,
                        ossimImageData* tile)
{
   static const char MODULE[] = "ossimOpjDecoder::decode";

   bool status = false;

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << "entered...\nrect: " << rect
         << "\nresLevel: " << resLevel << std::endl;
   }
   
   // Need to check for NAN in rect
   if ( in && tile && !rect.hasNans())
   {
      in->seekg( fileOffset, std::ios_base::beg );

      opj_dparameters_t param;
      opj_codec_t*      codec = 0;
      opj_image_t*      image = 0;;
      opj_stream_t*     stream = 0;

      opj_user_istream* userStream = new opj_user_istream();
      userStream->m_str = in;
      userStream->m_offset = fileOffset;

      /* Set the length to avoid an assert */
      in->seekg(0, std::ios_base::end);

      // Fix: length must be passed in for nift blocks.
      userStream->m_length = in->tellg();

      // Set back to front:
      in->clear();
      in->seekg(fileOffset, std::ios_base::beg);
      
      stream = opj_stream_default_create(OPJ_TRUE);
      if (!stream)
      {
         opj_stream_destroy(stream);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_setup_decoder failed!";
         throw ossimException(errMsg);
      }
      
      opj_stream_set_read_function(stream, ossim_opj_istream_read);
      opj_stream_set_skip_function(stream, ossim_opj_istream_skip);
      opj_stream_set_seek_function(stream, ossim_opj_istream_seek);

      // Fix: length must be passed in for nift blocks.
      opj_stream_set_user_data_length(stream, userStream->m_length);
      
      opj_stream_set_user_data(stream, userStream,
                               ossim_opj_free_user_istream_data);

      opj_stream_set_user_data_length(stream, userStream->m_length);

      
      /* Set the default decoding parameters */
      opj_set_default_decoder_parameters(&param);

      param.decod_format = format;

      /** you may here add custom decoding parameters */
      /* do not use layer decoding limitations */
      param.cp_layer = 0;

      /* do not use resolutions reductions */
      param.cp_reduce = resLevel;

      codec = opj_create_decompress( (CODEC_FORMAT)format );

      // catch events using our callbacks and give a local context
      //opj_set_info_handler   (codec, ossim::opj_info_callback,   00);
      opj_set_info_handler   (codec, NULL,   00);
      opj_set_warning_handler(codec, ossim::opj_warning_callback,00);
      opj_set_error_handler  (codec, ossim::opj_error_callback,  00);

      // Setup the decoder decoding parameters using user parameters
      if ( opj_setup_decoder(codec, &param) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_setup_decoder failed!";
         throw ossimException(errMsg);
      }

      // Read the main header of the codestream and if necessary the JP2 boxes.
      if ( opj_read_header(stream, codec, &image) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);         
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_read_header failed!";
         throw ossimException(errMsg);
      }

      // tmp drb:
      // opj_stream_destroy(stream);
      // return;
      
      if ( opj_set_decoded_resolution_factor(codec, resLevel) == false)
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR:  opj_set_decoded_resolution_factor failed!";
         throw ossimException(errMsg);
      }

      //ossim_float32 res = resLevel;
      ossimIrect resRect = rect * (1 << resLevel);

      //std::cout << "resRect.ul(): " << resRect.ul()
      //          << "\nresRect.lr(): " << resRect.lr()
      //          << std::endl;

//      if ( opj_set_decode_area(codec, image, rect.ul().x, rect.ul().y,
//                               rect.lr().x+1, rect.lr().y+1) == false )
      if ( opj_set_decode_area(codec, image, resRect.ul().x, resRect.ul().y,
                               resRect.lr().x+1, resRect.lr().y+1) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_set_decode_area failed!";
         throw ossimException(errMsg);
      }

      // Get the decoded image:
      if ( opj_decode(codec, stream, image) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_decode failed!";
         throw ossimException(errMsg);
      }
      
      // ossim::print(std::cout, *image);
      if(image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
          color_apply_icc_profile(image); /* FIXME */
#endif
          free(image->icc_profile_buf);
          image->icc_profile_buf = NULL; image->icc_profile_len = 0;
      }

      status = ossim::copyOpjImage(image, tile);
      
#if 0
      ossim_uint32 tile_index      = 0;
      ossim_uint32 data_size       = 0;
      ossim_int32  current_tile_x0 = 0;
      ossim_int32  current_tile_y0 = 0;
      ossim_int32  current_tile_x1 = 0;
      ossim_int32  current_tile_y1 = 0;
      ossim_uint32 nb_comps        = 0;
      OPJ_BOOL go_on = 1;

      if ( opj_read_tile_header( codec,
                                 stream,
                                 &tile_index,
                                 &data_size,
                                 &current_tile_x0,
                                 &current_tile_y0,
                                 &current_tile_x1,
                                 &current_tile_y1,
                                 &nb_comps,
                                 &go_on) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_read_tile_header failed!";
         throw ossimException(errMsg);
      }
#endif

#if 0
      std::cout << "tile_index:      " << tile_index
                << "\ndata_size:       " << data_size
                << "\ncurrent_tile_x0: " << current_tile_x0
                << "\ncurrent_tile_y0: " << current_tile_y0
                << "\ncurrent_tile_x1: " << current_tile_x1
                << "\ncurrent_tile_y1: " << current_tile_y1
                << "\nnb_comps:        " << nb_comps
                << std::endl;
#endif

#if 0
      if ( opj_decode_tile_data(codec, tile_index,l_data,l_data_size,l_stream) == false)
      {
         opj_stream_destroy(l_stream);
         opj_destroy_codec(l_codec);
         opj_image_destroy(l_image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_read_tile_header failed!";
         throw ossimException(errMsg);
      }
#endif

#if 0
      
      if (opj_end_decompress(codec,stream) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_end_decompress failed!";
         throw ossimException(errMsg);
      } 

#endif
      
      /* Free memory */
      opj_stream_destroy(stream);
      opj_destroy_codec(codec);
      opj_image_destroy(image);

      // Tmp drb:
      if ( in->eof() )
      {
         in->clear();
      }
      in->seekg(fileOffset, std::ios_base::beg );
      
   } // Matches: if ( in && tile )

   return status;
   
} // End: ossim::opj_decode( ... )
Beispiel #8
0
ossimRefPtr<ossimProjection> ossimFgdcXmlDoc::getGridCoordSysProjection()
{
   static const char M[] = "ossimFgdcXmlDoc::getGridCoordSysProjection";
   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n";
   }

   if ( m_projection.valid() == false )
   {
      ossimString s;
      if ( getGridCoordinateSystem(s) )
      {
         ossimString gridsysn = s.downcase();
         if ( getHorizontalDatum(s) )
         {
            ossimString horizdn = s.downcase();
            const ossimDatum* datum = createOssimDatum(s); // throws exception
            
            if ( gridsysn == "universal transverse mercator" )
            {
               // Get the zone:
               if ( getUtmZone(s) )
               {
                  ossim_int32 zone = s.toInt32();

                  //---
                  // Note: Contruct with an origin with our datum.
                  // "proj->setDatum" does not change the origin's datum.
                  // This ensures theossimEpsgProjectionDatabase::findProjectionCode
                  // sets the psc code correctly down the line.
                  //---
                  ossimRefPtr<ossimUtmProjection> utmProj =
                     new ossimUtmProjection( *(datum->ellipsoid()), ossimGpt(0.0,0.0,0.0,datum) );
                  utmProj->setDatum(datum);
                  utmProj->setZone(zone);
                  
                  // Hemisphere( North false easting = 0.0, South = 10000000):
                  bool tmpResult = getUtmFalseNorthing(s);
                  if ( tmpResult && ( s != "0.0" ) )
                  {
                     utmProj->setHemisphere('S');
                  }
                  else
                  {
                     utmProj->setHemisphere('N');
                  }
                  utmProj->setPcsCode(0);

                  ossim_float64 xRes = 0.0;
                  ossim_float64 yRes = 0.0;
                  if (getXRes(xRes) && getYRes(yRes))
                  {
                     ossimDrect rect;
                     getBoundingBox(rect);

                     ossimDpt gsd(std::fabs(xRes), std::fabs(yRes));
                     ossimUnitType unitType = getUnitType();
                   
                     if (m_boundInDegree)
                     {
                        ossimGpt tieg(rect.ul().lat, rect.ul().lon);
                        utmProj->setUlTiePoints(tieg);
                     }
                     else
                     {
                        ossimDpt tie(rect.ul().x, rect.ul().y);
                        if ( unitType == OSSIM_US_SURVEY_FEET)
                        {
                           tie = tie * US_METERS_PER_FT;
                        }
                        else if ( unitType == OSSIM_FEET )
                        {
                           tie = tie * MTRS_PER_FT;
                        }
                        utmProj->setUlTiePoints(tie);
                     }

                     if ( unitType == OSSIM_US_SURVEY_FEET)
                     {
                        gsd = gsd * US_METERS_PER_FT;
                     }
                     else if ( unitType == OSSIM_FEET )
                     {
                        gsd = gsd * MTRS_PER_FT;
                     }
                     utmProj->setMetersPerPixel(gsd);
                  }
                  m_projection = utmProj.get(); // Capture projection.
               }
               else
               {
                  std::string errMsg = M;
                  errMsg += " ERROR: Could not determine utm zone!";
                  throw ossimException(errMsg);
               }
            }
         }
      }
   }
   
   if ( traceDebug() )
   {
      if ( m_projection.valid() )
      {
         m_projection->print(ossimNotify(ossimNotifyLevel_DEBUG));
      }
      ossimNotify(ossimNotifyLevel_DEBUG) << M << " exiting...\n";
   }
   return m_projection;
}
void ossimTiledElevationDatabase::mapRegion()
{
   static const char M[] = "ossimTiledElevationDatabase::mapRegion";
   
   if ( m_entries.size() && ( m_requestedRect.isLonLatNan() == false ) )
   {
      ossimRefPtr<ossimOrthoImageMosaic> mosaic = new ossimOrthoImageMosaic();
      std::vector<ossimTiledElevationEntry>::iterator i = m_entries.begin();
      while ( i != m_entries.end() )
      {
         mosaic->connectMyInputTo( (*i).m_sic.get() );
         ++i;
      }

      // Compute the requested rectangle in view space.
      ossimRefPtr<ossimImageGeometry> geom = mosaic->getImageGeometry();
      if ( geom.valid() )
      {
         ossimDpt ulDpt;
         ossimDpt lrDpt;
         geom->worldToLocal(m_requestedRect.ul(), ulDpt);
         geom->worldToLocal(m_requestedRect.lr(), lrDpt);

         // Expand out to fall on even view coordinates.
         ulDpt.x = std::floor(ulDpt.x);
         ulDpt.y = std::floor(ulDpt.y);
         lrDpt.x = std::ceil(lrDpt.x);
         lrDpt.y = std::floor(lrDpt.y);

         // Get new(expanded) corners in ground space.
         ossimGpt ulGpt;
         ossimGpt lrGpt;
         geom->localToWorld(ulDpt, ulGpt);
         geom->localToWorld(lrDpt, lrGpt);
         theGroundRect = ossimGrect(ulGpt, lrGpt);
            
         // Expanded requested rect in view space.
         ossimIpt ulIpt = ulDpt;
         ossimIpt lrIpt = lrDpt;
         const ossimIrect VIEW_RECT(ulIpt, lrIpt);

         // Get the data.
         ossimRefPtr<ossimImageData> data = mosaic->getTile(VIEW_RECT, 0);
         if ( data.valid() )
         {
            // Initialize the grid:
            const ossimIpt SIZE( data->getWidth(), data->getHeight() );
            const ossimDpt ORIGIN(ulGpt.lon, lrGpt.lat); // SouthWest corner
            const ossimDpt SPACING( (lrGpt.lon-ulGpt.lon)/(SIZE.x-1),
                                    (ulGpt.lat-lrGpt.lat)/(SIZE.y-1) );
            if ( !m_grid ) m_grid = new ossimDblGrid();
            m_grid->initialize(SIZE, ORIGIN, SPACING, ossim::nan());

            if ( traceDebug() )
            {
               ossimNotify(ossimNotifyLevel_DEBUG)
                  << M
                  << "\nrequested view rect: " << VIEW_RECT
                  << "\nexpanded ground rect: " << theGroundRect
                  << "\norigin:  " << ORIGIN
                  << "\nsize:    " << SIZE
                  << "\nspacing: " << SPACING << std::endl;
            }

            // Fill the grid:
            switch( data->getScalarType() )
            {
               case OSSIM_SINT16:
               {
                  fillGrid(ossim_sint16(0), data);
                  break;
               }
               case OSSIM_SINT32:
               {
                  fillGrid(ossim_sint32(0), data);
                  break;
               }
               case OSSIM_FLOAT32:
               {
                  fillGrid(ossim_float32(0), data);
                  break;
               }
               case OSSIM_FLOAT64:
               {
                  fillGrid(ossim_float64(0), data);
                  break;
               }
               case OSSIM_UINT8:
               case OSSIM_SINT8:
               case OSSIM_USHORT11:
               case OSSIM_UINT16:
               case OSSIM_UINT32:
               case OSSIM_NORMALIZED_DOUBLE:
               case OSSIM_NORMALIZED_FLOAT:
               case OSSIM_SCALAR_UNKNOWN:
               default:
               {
                  std::string errMsg = M;
                  errMsg += " ERROR:\nUnhandled scalar type: ";
                  errMsg += data->getScalarTypeAsString().string();
                  throw ossimException(errMsg);
               }
            }
            
         } // if ( data.valid() )

      } // if ( geom.valid() )

   } // if ( m_entries.size() && ...
}
Beispiel #10
0
void ossimRpfToc::createTocAndCopyFrames( const ossimFilename& dotRpfFile,
                                          const ossimFilename& outputDir )
{
   static const char MODULE[] = "ossimRpfToc::createTocAndCopyFrames";

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered..."
         << "\ndot rpf file:      " << dotRpfFile
         << "\noutput directory:  " << outputDir
         << "\n";
   }

   if ( outputDir.expand().exists() == false )
   {
      if ( !outputDir.createDirectory(true, 0775) )
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not create directory: ";
         e+= outputDir.c_str();
         throw ossimException(e);
      }
   }

   // Open the dot rpf file.
   std::ifstream* dotRpfStr = new std::ifstream;
   dotRpfStr->open(dotRpfFile, ios_base::in);
   if ( !dotRpfStr->good() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += dotRpfFile.c_str();
      throw ossimException(e);
   }

   ossimFilename sourceADotTocFile = getSourceTocFile(*dotRpfStr);
   if ( sourceADotTocFile.empty() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not deduce source a.toc file!";
      throw ossimException(e);
   }
   
   // Open the source a.toc file. Note the true flag is to keep the file header.
   ossimRefPtr<ossimRpfToc> sourceADotToc = new ossimRpfToc;
   if ( sourceADotToc->parseFile(sourceADotTocFile, true) != ossimErrorCodes::OSSIM_OK )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
 
      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   ossimRefPtr<const ossimNitfFileHeader> sourceNitfFileHdr = sourceADotToc->getNitfFileHeader();
   if ( !sourceNitfFileHdr.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;        

      std::string e = MODULE;
      e += " ERROR:\nCould not get nitf file header from: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }
   
   ossimRefPtr<const ossimRpfHeader> sourceRpfHdr = sourceADotToc->getRpfHeader();
   if ( !sourceRpfHdr.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      
      std::string e = MODULE;
      e += " ERROR:\nCould not get rpf header from: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   // Get the boundary rect sub header from the source a.toc.
   ossimRefPtr<ossimRpfBoundaryRectSectionSubheader> boundaryRectSectionSubheader =
      sourceRpfHdr->getNewBoundaryRectSectSubheader(sourceADotTocFile);
   if ( !boundaryRectSectionSubheader.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull boundary rect sub header from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }   

   // Get the boundary rect table from the source a.toc.
   ossimRefPtr<ossimRpfBoundaryRectTable> boundaryRectTable =
      sourceRpfHdr->getNewBoundaryRectTable(sourceADotTocFile);
   if ( !boundaryRectTable.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      
      std::string e = MODULE;
      e += " ERROR:\nCould not pull boundary rect table from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }
   
   // Get the frame file subheader from the source a.toc.
   ossimRefPtr<ossimRpfFrameFileIndexSectionSubheader> frameFileSubHeader =
      sourceRpfHdr->getNewFrameFileIndexSectionSubheader(sourceADotTocFile);
   if ( !frameFileSubHeader.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull frame file sub header from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e);
   }

   // Get the frame file subsection from the source a.toc.
   ossimRefPtr<ossimRpfFrameFileIndexSubsection> frameFileSubSection =
      sourceRpfHdr->getNewFileIndexSubsection(sourceADotTocFile);
   if ( !frameFileSubSection.valid() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;

      std::string e = MODULE;
      e += " ERROR:\nCould not pull frame file sub section from source file: ";
      e += sourceADotTocFile.c_str();
      throw ossimException(e); 
   }
   
   // Open the output file to write to.
   const ossimFilename A_DOT_TOC_FILE = "a.toc";
   ossimFilename dotTocFile = outputDir.dirCat(A_DOT_TOC_FILE);
   std::ofstream* dotTocStr = new std::ofstream;
   dotTocStr->open( dotTocFile.c_str(), ios::out|ios::binary );
   if ( !dotTocStr->good() )
   {
      delete dotRpfStr;
      dotRpfStr = 0;
      delete dotTocStr;
      dotTocStr =0;

      std::string e = MODULE;
      e += " ERROR:\nCould not open: ";
      e += dotTocFile.c_str();
      throw ossimException(e);
   }
   
   // Variables used throughout:
   ossimRefPtr<ossimProperty> prop = new ossimStringProperty();
   ossimString field;
   ossimString s;
   std::streampos fileHeaderLength = 0;
   std::streampos fileLength = 0;
      
   ossimRefPtr<ossimNitfFileHeaderV2_0> fileHdr = new ossimNitfFileHeaderV2_0();
   
   // Set the CLEVEL:
   s = "01";
   fileHdr->setComplexityLevel(s);
   
   // Set the OSTAID:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OSTAID_KW);
   fileHdr->setProperty(prop);
   
   // Set the FDT (date):
   fileHdr->setDate();
   
   // Set the FTITLE:
   s = "a.toc";
   fileHdr->setTitle(s);
   
   // Set the FSCLAS:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCLAS_KW);
   fileHdr->setProperty(prop);
   
   // Set the FSCODE:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCODE_KW);
   fileHdr->setProperty(prop);
   
   // Set the FSCTLH:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::FSCTLH_KW);
   fileHdr->setProperty(prop);
   
   // Set the ONAME:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::ONAME_KW);
   fileHdr->setProperty(prop);
   
   // Set the OPHONE:
   prop = sourceNitfFileHdr->getProperty(ossimNitfFileHeaderV2_X::OPHONE_KW);
   fileHdr->setProperty(prop);
   
   // Add the rpf header.
   ossimRpfHeader* rpfHdr = new ossimRpfHeader( *(sourceRpfHdr.get()) );
   
   ossimRefPtr<ossimNitfRegisteredTag> rpfHdrRp = rpfHdr;
   ossimNitfTagInformation rpfHdrInfo(rpfHdrRp);
   fileHdr->addTag(rpfHdrInfo);
   
   //---
   // Write it out...
   // The first write will be with an rpfheader with no location sections just
   // to see where the end of the file header is.
   //---
   fileHdr->writeStream(*dotTocStr);
   
   //---
   // End of file header. Get the header length. This will also be the
   // start of the location section.
   //---
   std::streampos pos = dotTocStr->tellp();
   std::streamoff locationSectionOffset = pos;
   
   // Set the header length:
   fileHdr->setHeaderLength( static_cast<ossim_uint64>(locationSectionOffset) );
   
   // Set the location of the location section.
   rpfHdr->setLocationSectionPos(locationSectionOffset);

   // Set the file name.
   rpfHdr->setFilename(A_DOT_TOC_FILE);
   
   // Add the component location records to the header.
   ossimRpfLocationSection* locSec = rpfHdr->getLocationSection();
   
   // Clear the records copied from the source a.toc.
   locSec->clearFields();
   
   //---
   // Set the length of the locSec to 74.  The record itself is 14 bytes plus
   // an additional 60 bytes for six location records ten bytes each.
   //---
   const ossim_uint16 LOCATION_SECTION_SIZE = 74;
   locSec->setLocationSectionLength(LOCATION_SECTION_SIZE);
   
   // Set the offset which 14 bytes to get to the first record.
   locSec->setLocationTableOffset(14);
   
   // Six records:
   locSec->setNumberOfComponentLocationRecords(6);
   
   // Each record 10 bytes:
   locSec->setLocationRecordLength(10);
   
   // Don't know the aggregate length yet.
   
   ossimRpfComponentLocationRecord locRec;
   
   // Note: See ossimRpfConstants for enum ossimRpfComponentId
   
   const ossim_uint32 RPFHDR_SIZE = 48;
   const ossim_uint32 LOCATION_SECTION_OFFSET = static_cast<ossim_uint32>(locationSectionOffset);
   const ossim_uint32 BOUNDARY_SUBHEADER_SIZE = 8;
   const ossim_uint32 BOUNDARY_RECORD_SIZE = 132;
   const ossim_uint32 FILE_SUBHEADER_SIZE = 13;
   // const ossim_uint32 = ;
   
   // Record 1 RPFHDR location:
   ossim_uint32 rpfHdrOffset = 0;
   if ( fileHdr->getTag(rpfHdrInfo, "RPFHDR") )
   {
      rpfHdrOffset = rpfHdrInfo.getTagDataOffset();
   }

   locRec.m_componentId = OSSIM_RPF_HEADER_COMPONENT; // 128
   locRec.m_componentLength = RPFHDR_SIZE;
   locRec.m_componentLocation = static_cast<ossim_uint32>(rpfHdrInfo.getTagDataOffset());
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)<< "rpf hdr offset: " << rpfHdrOffset << "\n";
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 2 location section:
   locRec.m_componentId = OSSIM_RPF_LOCATION_COMPONENT; // 129
   locRec.m_componentLength = LOCATION_SECTION_SIZE;
   locRec.m_componentLocation = LOCATION_SECTION_OFFSET;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 3 boundary rect sub header section:
   locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_SECTION_SUBHEADER; // 148
   locRec.m_componentLength = BOUNDARY_SUBHEADER_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + LOCATION_SECTION_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Capture the location.
   std::streamoff boundaryRectPosition = locRec.m_componentLocation;
   
   // Record 4 boundary rect table:
   locRec.m_componentId = OSSIM_RPF_BOUNDARY_RECT_TABLE; // 149
   locRec.m_componentLength = BOUNDARY_RECORD_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_SUBHEADER_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Record 5 file index sub header:
   locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SECTION_SUBHEADER; // 150
   locRec.m_componentLength = FILE_SUBHEADER_SIZE;
   locRec.m_componentLocation = locRec.m_componentLocation + BOUNDARY_RECORD_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
    
   // Record 6 file index sub header:
   locRec.m_componentId = OSSIM_RPF_FRAME_FILE_INDEX_SUBSECTION; // 151
   locRec.m_componentLength = 0;  // need to calculate.
   locRec.m_componentLocation = locRec.m_componentLocation + FILE_SUBHEADER_SIZE;
   locSec->addComponentRecord(locRec);

   if ( traceDebug() )
   {
      locRec.print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   
   // Seek back and re-write...
   dotTocStr->seekp(0, ios::beg);
   fileHdr->writeStream(*dotTocStr);
   
   dotTocStr->seekp(boundaryRectPosition, ios::beg);

   // Only writing one entry:
   boundaryRectSectionSubheader->setNumberOfEntries(1);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "writing boundaryRectSectionSubheader:\n" << *(boundaryRectSectionSubheader.get())
         << "\n";
   }

   //---
   // Write the boundary rectangle section.  This includes the subheader and subsection.
   // These coorespond to location records 3 and 4 above.
   //---
   boundaryRectSectionSubheader->writeStream(*dotTocStr);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) 
         << "Original boundaryRectTable:\n" << *(boundaryRectTable.get()) << "\n";
   }

   ossim_uint32 entry;
   if ( getCorespondingEntry( frameFileSubSection.get(), *dotRpfStr, entry ) )
   {
      ossimRpfBoundaryRectRecord boundaryRectRecord;
      if ( boundaryRectTable->getEntry( entry, boundaryRectRecord) )
      {
         if ( traceDebug() )
         {
            ossimNotify(ossimNotifyLevel_DEBUG) 
               << "writing boundaryRectTable:\n" << boundaryRectRecord << "\n";
         }
         
         boundaryRectRecord.writeStream(*dotTocStr);
      }
      else
      {
         std::string e = MODULE;
         e += " ERROR:\nCould not get bounding rect record for entry: ";
         e += ossimString::toString(entry).c_str();
         throw ossimException(e);
      }
   }
   else
   {
      std::string e = MODULE;
      e += " ERROR:\nCould not deduce entry from frame list!";
      throw ossimException(e);
   }

   frameFileSubHeader->setNumberOfIndexRecords( getNumberOfFrames(*dotRpfStr) );
   frameFileSubHeader->setNumberOfPathnameRecords(1);
   const ossim_uint16 FRAME_FILE_INDEX_RECORD_LENGTH = 33;
   frameFileSubHeader->setIndexRecordLength( FRAME_FILE_INDEX_RECORD_LENGTH );

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "writing frameFileSubHeader:\n" << *(frameFileSubHeader.get()) << "\n";
   }
   frameFileSubHeader->writeStream( *dotTocStr );

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "writing frameFileSubSection:\n";
   }

   std::streamoff frameFileIndexSectionStartPos = dotTocStr->tellp();
   
   writeFrameFileIndexSection(frameFileSubSection.get(), *dotRpfStr, *dotTocStr);
   
   std::streamoff endOfFilePos = dotTocStr->tellp();

   // Update the location section length for the frame file index section.
   locSec->getLocationRecordList()[5].m_componentLength =
      static_cast<ossim_uint32>(endOfFilePos - frameFileIndexSectionStartPos);

   // Update the length of all location sections.
   locSec->setComponentAggregateLength(
      static_cast<ossim_uint32>(endOfFilePos) - rpfHdr->getLocationSectionLocation() );
   

   fileHdr->setFileLength(static_cast<ossim_uint64>(endOfFilePos));
   dotTocStr->seekp(0, ios::beg);
   fileHdr->writeStream(*dotTocStr);

   ossimNotify(ossimNotifyLevel_DEBUG) << "Wrote file: " << dotTocFile << "\n";

   // Copy the frames to the output directory.
   copyFrames(*dotRpfStr, outputDir);

   // Cleanup:
   delete dotRpfStr;
   dotRpfStr = 0;
   delete dotTocStr;
   dotTocStr =0;
}
Beispiel #11
0
bool ossimImageUtil::initialize(ossimArgumentParser& ap)
{
   static const char M[] = "ossimImageUtil::initialize(ossimArgumentParser&)";
   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << M << " entered...\n";
   }

   bool result = true;

   if ( (ap.argc() == 1) || ap.read("-h") || ap.read("--help") )
   {
      usage(ap);

      // continue_after_init to false
      result = false;
   }
   else
   {
      //---
      // Start with clean options keyword list.
      //---
      m_kwl->clear();

      while ( 1 ) //  While forever loop...
      {
         // Used throughout below:
         std::string ts1;
         ossimArgumentParser::ossimParameter sp1(ts1);
         std::string ts2;
         ossimArgumentParser::ossimParameter sp2(ts2);

         if( ap.read("-a") || ap.read("--include-fullres") )
         {
            setCopyAllFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--compression-quality", sp1) )
         {
            if ( ts1.size() )
            {
               setCompressionQuality( ts1 );
            }
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--compression-type", sp1) )
         {
            if ( ts1.size() )
            {
               setCompressionType( ts1 );
            }
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("--ch") || ap.read("--create-histogram") )
         {
            setCreateHistogramFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("--chf") || ap.read("--create-histogram-fast") )
         {
            setCreateHistogramFastFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("--create-histogram-r0") )
         {
            setCreateHistogramR0Flag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("-d", sp1) )
         {
            setOutputDirectory( ts1 );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--dump-filtered-image-list") )
         {
            setDumpFilteredImageListFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("-i") || ap.read("--internal-overviews") )
         {
            setInternalOverviewsFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--of") || ap.read("--output-files") )
         {
            setOutputFileNamesFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("-o") )
         {
            setCreateOverviewsFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }        
         
         if( ap.read("--ot", sp1) )
         {
            setOverviewType( ts1 );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--override-filtered-images") )
         {
            setOverrideFilteredImagesFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("-r") || ap.read("--rebuild-overviews") )
         {
            setRebuildOverviewsFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--rebuild-histogram") )
         {
            setRebuildHistogramFlag( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         while(ap.read("--reader-prop", sp1))
         {
            if (ts1.size())
            {
               std::string key = READER_PROP_KW;
               key += ossimString::toString( getNextReaderPropIndex() ).string();
               addOption( key, ts1 );
            }
         }
         if ( ap.argc() < 2 )
         {
            break;
         }
         
         if( ap.read("--scanForMinMax" ) )
         {
            setScanForMinMax( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--scanForMinMaxNull" ) )
         {
            setScanForMinMaxNull( true );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }
         
         if( ap.read("-s", sp1) )
         {
            setOverviewStopDimension( ts1 );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if ( ap.read("-tile-size", sp1))
         {
            setTileSize( ossimString(ts1).toInt32() );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         if( ap.read("--threads", sp1) )
         {
            m_kwl->addPair( THREADS_KW, ts1 );
            if ( ap.argc() < 2 )
            {
               break;
            }
         }

         while(ap.read("--writer-prop", sp1))
         {
            if (ts1.size())
            {
               std::string key = WRITER_PROP_KW;
               key += ossimString::toString( getNextWriterPropIndex() ).string();
               addOption( key, ts1 );
            }
         }
         if ( ap.argc() < 2 )
         {
            break;
         }

         // End of arg parsing.
         ap.reportRemainingOptionsAsUnrecognized();
         if ( ap.errors() )
         {
            ap.writeErrorMessages(ossimNotify(ossimNotifyLevel_NOTICE));
            std::string errMsg = "Unknown option...";
            throw ossimException(errMsg);
         }

         break; // Break from while forever.
         
      } // End while (forever) loop.

      if(ap.argc() > 1)
      {
         for (ossim_int32 i = 0; i < (ap.argc()-1); ++i)
         {
            ossimString kw = "file";
            kw += ossimString::toString(i);
            std::string value = ap[i+1];
            m_kwl->addPair(kw.string(), value, true);
         }
      }
      else
      {
         if ( getDumpFilterImagesFlag() )
         {
            // Caller wants to see filtered image names:
            dumpFilteredImageList();
         }
         else
         {
            usage(ap);
            result = false;
         }
      }

   } // not usage

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "m_kwl:\n" << *(m_kwl.get()) << "\n"
         << M << " exit result = " << (result?"true":"false")
         << "\n";
   }
   
   return result;
}
void ossimOpjCompressor::create(std::ostream* os,
                                ossimScalarType scalar,
                                ossim_uint32 bands,
                                const ossimIrect& imageRect,
                                const ossimIpt& tileSize,
                                bool jp2)
{
   static const char MODULE[] = "ossimOpjCompressor::create";
   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_WARN) << MODULE << " entered...\n";
   }
   
#if 0 /* Please leave for debug. (drb) */
   cout << "levels:      " << m_levels
        << "\nreversible:  " << m_reversible
        << "\nthreads:     " << m_threads
        << "\nscalar:    " << scalar
        << "\nbands:     " << bands
        << "\nimageRect: " << imageRect
        << "\ntileSize:  " << tileSize
        << "\njp2:       " << jp2
        << endl;
#endif

   // In case we were reused.
   finish();

   if ( !os )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: Null stream passed to method!";
      throw ossimException(errMsg);
   }
   
   if ( !os->good() )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: Stream state has error!";
      throw ossimException(errMsg);
   }
   
   if ( ossim::getActualBitsPerPixel(scalar) > 31 )
   {
      // Data is not reversible.
      if ( m_reversible )
      {
         std::string errMsg = MODULE;
         errMsg += " ERROR: Reversible processing not possible with 32 bit data!";
         throw ossimException(errMsg);
      }
   }
   
   // Store for tile clip.
   m_imageRect = imageRect;

   m_stream = createOpjStream( os );
   if ( !m_stream )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: OPJ stream creation failed!";
      throw ossimException(errMsg); 
   }

   // Requests the insertion of TLM (tile-part-length) marker.
   // setTlmTileCount(tilesToWrite);
   
   // Set up stream:
   initOpjCodingParams( jp2, tileSize, imageRect );
   if ( !m_params )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: coding parameters creation failed!";
      throw ossimException(errMsg);
   }

   m_codec = createOpjCodec( jp2 );
   if ( !m_codec )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: code creation failed!";
      throw ossimException(errMsg);
   }   

   // Set rates rates/distorsion
   // parameters->cp_disto_alloc = 1;

   // ossim::print( cout, *m_params );
   
   if (m_alpha)
   {
      if ( (bands != 1) && (bands != 3) )
      {
         m_alpha = false;
         if ( traceDebug() )
         {
            ossimNotify(ossimNotifyLevel_WARN)
               << "Alpha channel being unset! Can only be used with "
               << "one or three band data.\n"
               << "Source image bands: " << bands << "\n";
         }
      }
   }

   // Create an image without allocating memory(for tile based).
   m_image = createOpjImage( scalar, bands, imageRect );
   if ( !m_image )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: Unsupported input image type!";
      throw ossimException(errMsg);
   }

   if ( !opj_setup_encoder( m_codec, m_params, m_image) )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR: opj_setup_encoder failed!";
      throw ossimException(errMsg); 
   }

   // openJp2Codestream();
   
   if ( traceDebug() )
   {
      ossim::print( ossimNotify(ossimNotifyLevel_DEBUG), *m_params );
      
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " exiting...\n";
   }
}
Beispiel #13
0
void ossimNitfFileHeaderV2_0::parseStream(std::istream &in)
{
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimNitfFileHeaderV2_0::parseStream:   entered ......."
         << std::endl;
   }
   
   clearFields();
   
   // identification and origination group
   in.read(theFileTypeVersion, 9);
   theHeaderSize+=9;
   in.read(theComplexityLevel, 2);
   theHeaderSize+=2;
   in.read(theSystemType, 4);
   theHeaderSize+=4;
   in.read(theOriginatingStationId, 10);
   theHeaderSize+=10;
   in.read(theDateTime, 14);
   theHeaderSize+=14;
   in.read(theFileTitle, 80);
   theHeaderSize+=80;
   
   // read security group
   in.read(theSecurityClassification, 1);
   theHeaderSize++;
   in.read(theCodewords, 40);
   theHeaderSize+=40;
   in.read(theControlAndHandling, 40);
   theHeaderSize+=40;
   in.read(theReleasingInstructions, 40);
   theHeaderSize+=40;
   in.read(theClassificationAuthority, 20);
   theHeaderSize+=20;
   in.read(theSecurityControlNumber, 20);
   theHeaderSize+=20;
   in.read(theSecurityDowngrade, 6);
   theHeaderSize+=6;
   if(ossimString(theSecurityDowngrade) == "999998")
   {
      in.read(theDowngradingEvent, 40);
      theHeaderSize+=40;
   }      
   in.read(theCopyNumber, 5);
   theHeaderSize+=5;
   in.read(theNumberOfCopies, 5);
   theHeaderSize+=5;
   in.read(theEncryption, 1);
   theHeaderSize++;
   in.read(theOriginatorsName, 27);
   theHeaderSize+=27;
   in.read(theOriginatorsPhone, 18);
   theHeaderSize+=18;
   
   in.read(theFileLength, 12);
   theHeaderSize+=12;
   in.read(theHeaderLength, 6);
   theHeaderSize+=6;
   
   // image description group
   in.read(theNumberOfImageInfoRecords, 3);
   theHeaderSize+=3;
   readImageInfoRecords(in);

   // symbol description group
   in.read(theNumberOfSymbolInfoRecords, 3);
   theHeaderSize+=3;
   readSymbolInfoRecords(in);
   
   // label description group
   in.read(theNumberOfLabelInfoRecords, 3);
   theHeaderSize+=3;
   readLabelInfoRecords(in);
   
   // text file information group
   in.read(theNumberOfTextFileInfoRecords, 3);
   theHeaderSize+=3;
   readTextFileInfoRecords(in);
   
   // Data extension group
   in.read(theNumberOfDataExtSegInfoRecords, 3);
   theHeaderSize+=3;
   readDataExtSegInfoRecords(in);
   
   // Reserve Extension Segment group
   in.read(theNumberOfResExtSegInfoRecords, 3);
   theHeaderSize+=3;
   readResExtSegInfoRecords(in);
   
   in.read(theUserDefinedHeaderDataLength, 5);
   theHeaderSize+=5;
   
   theTagList.clear();
   // only get the header overflow if there even exists
   // user defined data.
   ossim_int32 userDefinedHeaderLength = ossimString(theUserDefinedHeaderDataLength).toInt32();
   
   ossimNitfTagInformation         headerTag;
   
   std::streampos start   = in.tellg();
   std::streampos current = in.tellg();

   theHeaderSize+=userDefinedHeaderLength;
   if(userDefinedHeaderLength > 0)
   {
      in.read(theUserDefinedHeaderOverflow, 3);
      
      while((current - start) < userDefinedHeaderLength)
      {
         headerTag.parseStream(in);
         theTagList.push_back(headerTag);
         // in.ignore(headerTag.getTagLength());
         // headerTag.clearFields();

         //---
         // We will check the stream here as there have been instances of
         // rpf's with bad stream offsets.
         //---
         if (!in)
         {
            std::string e =
               "ossimNitfFileHeaderV2_0::parseStream stream error!";
            throw ossimException(e);
         }

         current = in.tellg();
      }
   }
   in.read(theExtendedHeaderDataLength, 5);
   theHeaderSize+=5;
   ossim_int32 extendedHeaderDataLength = ossimString(theExtendedHeaderDataLength).toInt32();
   theHeaderSize+=extendedHeaderDataLength;
   
   start   = in.tellg();
   current = in.tellg();
   // for now let's just ignore it
   if(extendedHeaderDataLength > 0)
   {
      in.read(theExtendedHeaderOverflow, 3);
      
      while((current - start) < extendedHeaderDataLength)
      {
         headerTag.parseStream(in);
         theTagList.push_back(headerTag);
         in.ignore(headerTag.getTagLength());
         headerTag.clearFields();
         current = in.tellg();
      }
   }
   
   // this need to be re-thought
   initializeAllOffsets();

   if(traceDebug())
   {
      ossimNitfFileHeader::print( ossimNotify(ossimNotifyLevel_DEBUG) );
   }
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "ossimNitfFileHeaderV2_0::parseStream:   Leaving......."
         << std::endl;
   }
//      initializeDisplayLevels(in);

}
Beispiel #14
0
std::streamoff ossimJp2Info::getBox( const ossim_uint32& type,
                                     bool includeAll,
                                     std::ifstream& str,
                                     std::vector<ossim_uint8>& box ) const
{
    std::streamoff boxPos = 0;
    std::streamoff boxPosOfType = 0;
    box.clear();

    if ( str.good() )
    {
        ossim_uint32   lbox   = 0;
        ossim_uint32   tbox   = 0;
        ossim_uint64   xlbox  = 0;
        std::streamoff offsetToDbox = 0;

        while ( str.good() )
        {
            boxPos = str.tellg();

            readUInt32( lbox, str );
            readUInt32( tbox, str );

            if ( lbox == 1 )
            {
                readUInt64( xlbox, str );
                offsetToDbox = 16;
            }

            if ( !includeAll )
            {
                if ( lbox == 1 )
                {
                    offsetToDbox = 16;
                }
                else
                {
                    offsetToDbox = 8;
                }
            }

            if ( traceDebug() )
            {
                ossimNotify(ossimNotifyLevel_DEBUG)
                        << "jp2.lbox: " << std::dec << lbox << "\n"
                        << "jp2.tbox: " << std::hex << tbox << std::dec << "\n";
                printTboxType( tbox, ossimNotify(ossimNotifyLevel_DEBUG)  );

                if ( 1 == lbox )
                {
                    ossimNotify(ossimNotifyLevel_DEBUG) << "jp2.xlbox: " << xlbox << std::endl;
                }
            }


            if ( tbox == type )
            {
                //---
                // This is our box, copy it to box.
                // Not copying the lbox,tbox or xlbox
                std::streamoff boxSize = 0;
                if ( lbox == 0 )
                {
                    // Last box, goes to end of file.
                    str.seekg( 0, std::ios_base::end );
                    boxSize = str.tellg() - boxPos;
                }
                else if ( lbox == 1 )
                {
                    boxSize = xlbox;
                }
                else
                {
                    boxSize = lbox;
                }
                boxSize -= offsetToDbox;

                // Seek to box data start
                str.seekg( boxPos + offsetToDbox, std::ios_base::beg );

                // std::vector::resize can throw a std::bad_alloc so wrap it...
                try
                {
                    box.resize( boxSize );
                    str.read( (char*)&box.front(), boxSize );
                }
                catch( std::exception& e )
                {
                    std::ostringstream errMsg;
                    errMsg << "ossimJp2Info::getBox caught exception on resize:\n"
                           << "Buffer size in bytes: " << boxSize
                           << "\n" << e.what() << std::endl;
                    throw ossimException( errMsg.str() );
                }

                boxPosOfType = boxPos; // set up return value
                break; // done...
            }

            if (lbox == 0) // last box?
            {
                break;
            }

            // Seek to the next box.
            std::streamoff nextBoxPos = boxPos;
            if (lbox == 1)
            {
                nextBoxPos+= (std::streamoff)xlbox;
            }
            else
            {
                nextBoxPos+= (std::streamoff)lbox;
            }

            // Go to next box:
            str.seekg(nextBoxPos, std::ios_base::beg);

        } // matches: while ( str.good() )

    } // matches: if ( str.good() )

    return boxPosOfType;

} // End: ossimJp2Info::getBox( type, includeAll, str, box ) const
bool ossimH5GridModel::setGridNodes( H5::DataSet* latDataSet,
                                     H5::DataSet* lonDataSet,
                                     const ossimIrect& validRect )
{
   bool status = false;

   if ( latDataSet && lonDataSet )
   {
      m_crossesDateline = ossim_hdf5::crossesDateline( *lonDataSet, validRect );
      
      if ( m_crossesDateline )
      {
         theLonGrid.setDomainType(ossimDblGrid::WRAP_360);
      }
      else
      {
         theLonGrid.setDomainType(ossimDblGrid::WRAP_180);
      }

      // Get dataspace of the dataset.
      H5::DataSpace latDataSpace = latDataSet->getSpace();
      H5::DataSpace lonDataSpace = lonDataSet->getSpace();
      const ossim_int32 LAT_DIM_COUNT = latDataSpace.getSimpleExtentNdims();
      const ossim_int32 LON_DIM_COUNT = lonDataSpace.getSimpleExtentNdims();
      
      // Number of dimensions of the input dataspace:
      if ( ( LAT_DIM_COUNT == 2 ) && ( LON_DIM_COUNT == 2 ) )
      {
         const ossim_uint32 ROWS = validRect.height();
         const ossim_uint32 COLS = validRect.width();
         const ossim_uint32 GRID_SIZE = 4; // Only grab every 4th value.

         //---
         // Get the extents:
         // dimsOut[0] is height, dimsOut[1] is width:
         //---
         std::vector<hsize_t> latDimsOut(LAT_DIM_COUNT);
         latDataSpace.getSimpleExtentDims( &latDimsOut.front(), 0 );
         std::vector<hsize_t> lonDimsOut(LON_DIM_COUNT);
         lonDataSpace.getSimpleExtentDims( &lonDimsOut.front(), 0 );
         
         // Verify valid rect within our bounds:
         if ( (ROWS <= latDimsOut[0] ) && (ROWS <= lonDimsOut[0] ) &&
              (COLS <= latDimsOut[1] ) && (COLS <= lonDimsOut[1] ) )
         {
            //----
            // Initialize the ossimDblGrids:
            //---
            ossimDpt dspacing (GRID_SIZE, GRID_SIZE);
            
            ossim_uint32 gridRows = ROWS / GRID_SIZE + 1;
            ossim_uint32 gridCols = COLS / GRID_SIZE + 1;
            
            // Round up if size doesn't fall on end pixel.
            if ( ROWS % GRID_SIZE) ++gridRows;
            if ( COLS % GRID_SIZE) ++gridCols;

            ossimIpt gridSize (gridCols, gridRows);
            
            // The grid as used in base class, has UV-space always at 0,0 origin            
            ossimDpt gridOrigin(0.0,0.0);

            const ossim_float64 NULL_VALUE = -999.0;
            
            theLatGrid.setNullValue(ossim::nan());
            theLonGrid.setNullValue(ossim::nan());
            theLatGrid.initialize(gridSize, gridOrigin, dspacing);
            theLonGrid.initialize(gridSize, gridOrigin, dspacing);            
            
            std::vector<hsize_t> inputCount(LAT_DIM_COUNT);
            std::vector<hsize_t> inputOffset(LAT_DIM_COUNT);
            
            inputOffset[0] = 0; // row is set below.
            inputOffset[1] = validRect.ul().x; // col
            
            inputCount[0] = 1; // row
            inputCount[1] = (hsize_t)COLS; // col
            
            // Output dataspace dimensions. Reading a line at a time.
            const ossim_int32 OUT_DIM_COUNT = 3;
            std::vector<hsize_t> outputCount(OUT_DIM_COUNT);
            outputCount[0] = 1;    // band
            outputCount[1] = 1;    // row
            outputCount[2] = COLS; // col
            
            // Output dataspace offset.
            std::vector<hsize_t> outputOffset(OUT_DIM_COUNT);
            outputOffset[0] = 0;
            outputOffset[1] = 0;
            outputOffset[2] = 0;
            
            ossimScalarType scalar = ossim_hdf5::getScalarType( latDataSet );
            if ( scalar == OSSIM_FLOAT32 )
            {
               // Set the return status to true if we get here...
               status = true;
               
               // See if we need to swap bytes:
               ossimEndian* endian = 0;
               if ( ( ossim::byteOrder() != ossim_hdf5::getByteOrder( latDataSet ) ) )
               {
                  endian = new ossimEndian();
               }
               
               // Native type:
               H5::DataType latDataType = latDataSet->getDataType();
               H5::DataType lonDataType = lonDataSet->getDataType();

               // Output dataspace always the same, width of one line.
               H5::DataSpace bufferDataSpace( OUT_DIM_COUNT, &outputCount.front());
               bufferDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                &outputCount.front(),
                                                &outputOffset.front() );

               //  Arrays to hold a single line of latitude longitude values.
               vector<ossim_float32> latValue(COLS);
               vector<ossim_float32> lonValue(COLS);
               hsize_t row = 0;

               // Line loop:
               for ( ossim_uint32 y = 0; y < gridRows; ++y )
               {
                  // row = line in image space
                  row = y*GRID_SIZE;

                  if ( row < ROWS )
                  {
                     inputOffset[0] = row + validRect.ul().y;

                     latDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                   &inputCount.front(),
                                                   &inputOffset.front() );
                     lonDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                   &inputCount.front(),
                                                   &inputOffset.front() );
                  
                     // Read data from file into the buffer.
                     latDataSet->read( &(latValue.front()), latDataType,
                                       bufferDataSpace, latDataSpace );
                     lonDataSet->read( &(lonValue.front()), lonDataType,
                                       bufferDataSpace, lonDataSpace );
                  
                     if ( endian )
                     {
                        // If the endian pointer is initialized(not zero) swap the bytes.
                        endian->swap( &(latValue.front()), COLS );
                        endian->swap( &(lonValue.front()), COLS );  
                     }
                  
                     // Sample loop:
                     hsize_t col = 0;
                     
                     for ( ossim_uint32 x = 0; x < gridCols; ++x )
                     {
                        ossim_float32 lat = ossim::nan();
                        ossim_float32 lon = ossim::nan();
                        
                        // col = sample in image space
                        col = x*GRID_SIZE;

                        if ( col < COLS )
                        {
                           if ( (latValue[col] > NULL_VALUE)&&(lonValue[col] > NULL_VALUE) )
                           {
                              lat = latValue[col];
                              lon = lonValue[col];
                              if ( m_crossesDateline )
                              {
                                 if ( lon < 0.0 ) lon += 360;
                              }
                           }
                           else // Nulls in grid!
                           {
                              std::string errMsg =
                                 "ossimH5GridModel::setGridNodes encountered nans!";
                              throw ossimException(errMsg); 
                           }
                        }
                        else // Last column is outside of image bounds.
                        {
                           // Get the last two latitude values:
                           ossim_float32 lat1 = theLatGrid.getNode( x-2, y );
                           ossim_float32 lat2 = theLatGrid.getNode( x-1, y );

                           // Get the last two longitude values
                           ossim_float32 lon1 = theLonGrid.getNode( x-2, y );
                           ossim_float32 lon2 = theLonGrid.getNode( x-1, y );
                           
                           if ( ( lat1 > NULL_VALUE ) && ( lat2 > NULL_VALUE ) )
                           {
                              // Delta between last two latitude grid values.
                              ossim_float32 latSpacing = lat2 - lat1;
                           
                              // Compute:
                              lat = lat2 + latSpacing;
                           }
                           else // Nulls in grid!
                           {
                              std::string errMsg =
                                 "ossimH5GridModel::setGridNodes encountered nans!";
                              throw ossimException(errMsg);
                           }

                           if ( ( lon1 > NULL_VALUE ) && ( lon2 > NULL_VALUE ) )
                           {
                              // Delta between last two longitude values.
                              ossim_float32 lonSpacing = lon2 - lon1;
                           
                              // Compute:
                              lon = lon2 + lonSpacing;

                              // Check for wrap:
                              if ( !m_crossesDateline && ( lon > 180 ) )
                              {
                                 lon -= 360.0;
                              }
                           }
                           else // Nulls in grid!
                           {
                              std::string errMsg =
                                 "ossimH5GridModel::setGridNodes encountered nans!";
                              throw ossimException(errMsg);
                           }

#if 0 /* Please leave for debug. (drb) */                        
                           cout << "lat1: " << lat1 << " lat2 " << lat2
                                << " lon1 " << lon1  << " lon2 " << lon2
                                << "\n";
#endif
                        }
                        
                        // Assign the latitude and longitude.
                        theLatGrid.setNode( x, y, lat );
                        theLonGrid.setNode( x, y, lon );
                        
#if 0 /* Please leave for debug. (drb) */ 
                        cout << "x,y,col,row,lat,lon:" << x << "," << y << ","
                             << col << "," << row << ","
                             << theLatGrid.getNode(x, y)
                             << "," << theLonGrid.getNode( x, y) << "\n";
#endif
                        
                     } // End sample loop.
                     
                  }
                  else // Row is outside of image bounds:
                  {
                     // Sample loop:
                     for ( ossim_uint32 x = 0; x < gridCols; ++x )
                     {
                        ossim_float32 lat        = ossim::nan();
                        ossim_float32 lon        = ossim::nan();
                        
                        ossim_float32 lat1 = theLatGrid.getNode( x, y-2 );
                        ossim_float32 lat2 = theLatGrid.getNode( x, y-1 );
                        ossim_float32 lon1 = theLonGrid.getNode( x, y-2 );
                        ossim_float32 lon2 = theLonGrid.getNode( x, y-1 );
                        
                        if ( ( lon1 > NULL_VALUE ) && ( lon2 > NULL_VALUE ) )
                        {
                           // Delta between last two longitude values.
                           ossim_float32 lonSpacing = lon2 - lon1;
                           
                           // Compute:
                           lon = lon2 + lonSpacing;
                           
                           // Check for wrap:
                           if ( !m_crossesDateline && ( lon > 180 ) )
                           {
                              lon -= 360.0;
                           }
                        }
                        else // Nulls in grid!
                        {
                           std::string errMsg =
                              "ossimH5GridModel::setGridNodes encountered nans!";
                           throw ossimException(errMsg);
                        }
                        
                        if ( ( lat1 > NULL_VALUE ) && ( lat2 > NULL_VALUE ) )
                        {
                           // Delta between last two latitude values.
                           ossim_float32 latSpacing = lat2 - lat1;

                           lat = lat2 + latSpacing;
                        }
                        else // Nulls in grid!
                        {
                           std::string errMsg =
                              "ossimH5GridModel::setGridNodes encountered nans!";
                           throw ossimException(errMsg);
                        }
                        
#if 0 /* Please leave for debug. (drb) */
                        hsize_t col = x*GRID_SIZE; // Sample in image space
                        cout << "lat1: " << lat1 << " lat2 " << lat2
                             << " lon1 " << lon1  << " lon2 " << lon2
                             << "\nx,y,col,row,lat,lon:" << x << "," << y << ","
                             << col << "," << row << "," << lat << "," << lon << "\n";
#endif
                        // Assign the latitude::
                        theLatGrid.setNode( x, y, lat );

                        // Assign the longitude.
                        theLonGrid.setNode( x, y, lon );
                     
                     } // End sample loop.
                  
                  } // Matches if ( row < imageRows ){...}else{
                  
               } // End line loop.

               latDataSpace.close();
               lonDataSpace.close();

               if ( status )
               {
                  theSeedFunction = ossim_hdf5::getBilinearProjection(
                     *latDataSet,*lonDataSet, validRect );
                  
                  // Bileaner projection to handle
                  ossimDrect imageRect(validRect);
                  initializeModelParams(imageRect);

                  // debugDump();
               }

               if ( endian )
               {
                  delete endian;
                  endian = 0;
               }
               
            } // Matches: if ( scalar == OSSIM_FLOAT32 )
            
         } // Matches: if ( (latDimsOut[0] == imageRows) ...
         
      } // Matches: if ( ( LAT_DIM_COUNT == 2 ) ...

   } // Matches: if ( latDataSet && lonDataSet

   return status;
   
} // End: bool ossimH5GridModel::setGridNodes( H5::DataSet* latDataSet, ... )
Beispiel #16
0
//---
// Writer a dot rpf file for entry to output directory.
// 
// NOTES:
//
// 1) All coordinate written out in AREA or edge to edge format.
// 2) Throws ossimException on error.
//---
void ossimRpfUtil::writeDotRpfFile( const ossimRpfToc* toc,
                                    const ossimRpfTocEntry* tocEntry,
                                    const ossimFilename& outputDir,
                                    ossim_uint32 entry)
{
   static const char MODULE[] = "ossimRpfUtil::writeDotRpfFile";

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered..."
         << "\noutput directory:  " << outputDir
         << "\nentry: " << entry << "\n";
   }

   if ( !toc )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR toc pointer null!";
      throw ossimException(errMsg);
   }
   if ( !tocEntry )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR toc entry pointer null!";
      throw ossimException(errMsg);
   }

   // Get the file name.
   ossimFilename outFile;
   if ( outputDir.expand().isDir() )
   {
      getDotRfpFilenameForEntry(outputDir, entry, outFile);
   }
   else
   {
      outFile = outputDir;
   }
   
   // Open the file to write.
   std::ofstream os;
   os.open(outFile.c_str(), ios::out);
   if ( os.good() == false )
   {
      std::string errMsg = MODULE;
      errMsg += "ERROR could not open: ";
      errMsg += outFile.string();
      throw ossimException(errMsg);
   }
   
   // Set up the output stream fix with full precision for ground points.
   os << setiosflags(std::ios_base::fixed) << setprecision(15);
   
   //---
   // Overall TOC entry bounds:
   // 
   // Write the first line which is the bounding box of the entry in the form of:
   // "89.9850464205332, 23.9892538162654|90.5085823882692, 24.5002602501599|1"
   //      lr-lon            lr-lat           ul-lon            ul-lat
   //---
   ossimRefPtr<ossimImageGeometry> geom = tocEntry->getImageGeometry();
   if( geom.valid() == false)
   {
      std::string errMsg = "ERROR could not get geometry.";
      errMsg += outFile.string();
      throw ossimException(errMsg);  
   }

   // Rectangle in image space.
   ossimIrect outputRect;
   tocEntry->getBoundingRect(outputRect);

   // bands:
   ossim_uint32 bands = tocEntry->getNumberOfBands();

   // scale:
   ossimDpt scale;
   tocEntry->getDecimalDegreesPerPixel(scale);
   ossimDpt halfPix = scale / 2.0;

   ossimGpt llg;
   ossimGpt urg;
   geom->localToWorld(outputRect.ur(), urg);
   geom->localToWorld(outputRect.ll(), llg);

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << "outputRect: " << outputRect
         << "\nbands: " << bands
         << "\nscale: " << scale
         << "\nllg:   " << llg
         << "\nurg:   " << urg
         << std::endl;
   }

   // Expand coordinates to edge:
   llg.lon -= halfPix.x;
   llg.lat -= halfPix.y;
   urg.lon += halfPix.x;
   urg.lat += halfPix.y;
   
   // Test for 360 degrees apart.
   checkLongitude(llg, urg);
   
   os << llg.lon << "," // lower left longitude
      << llg.lat << "|" // lower left latitude
      << urg.lon << "," // upper right longitude
      << urg.lat << "|" // upper right latitude
      << bands << "\n";

   // Frame loop:
   const ossim_int32 FRAMESIZE = 1536;
   const ossim_int32 ROWS = static_cast<ossim_int32>(tocEntry->getNumberOfFramesVertical());
   if( ROWS == 0 )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR no rows!";
      throw ossimException(errMsg);  
   }
   const ossim_int32 COLS = static_cast<ossim_int32>(tocEntry->getNumberOfFramesHorizontal());
   if( COLS == 0 )
   {
      std::string errMsg = MODULE;
      errMsg += " ERROR no columns!";
      throw ossimException(errMsg);  
   }

   // Set the initial lower left and upper right image points for localToWorld call.
   //ossimDpt urd( ( (ROWS-1)*FRAMESIZE) -1, 0.0);
   //ossimDpt lld(0.0, (ROWS*FRAMESIZE)-1);
   ossimDpt urd( FRAMESIZE-1, 0.0);
   ossimDpt lld(0.0, FRAMESIZE-1);
   
   for (ossim_int32 row = ROWS-1; row > -1; --row)
   {
      for (ossim_int32 col = 0; col < COLS; ++col)
      {
         //---
         // Example format (only with 15 digit precision):
         // /data/spadac/rpf/world/cb01/ng467a1/0xslpk1a.i41|90.0448,24.3621|90.0598,24.3750
         //---
         
         // Get the path to the frame.
         ossimFilename path;
         toc->getRootDirectory(path);
         
         path = path.dirCat( toc->getRelativeFramePath(entry, row, col) );

         // Not sure if this is backwards:
         geom->localToWorld(urd, urg);
         geom->localToWorld(lld, llg);

         // Expand coordinates to edge:
         llg.lon -= halfPix.x;
         llg.lat -= halfPix.y;
         urg.lon += halfPix.x;
         urg.lat += halfPix.y;
         
         // Test for 360 degrees apart.
         checkLongitude(llg, urg);

         os << path.c_str() << "|"
            << llg.lon << "," // lower left longitude
            << llg.lat << "|" // lower left latitude
            << urg.lon << "," // upper right longitude
            << urg.lat        // upper right latitude
            << "\n";

         if ( traceDebug() )
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "row[" << row << "]col[" << col << "]path: " << path
               << "\nlld: " << lld
               << "\nllg: " << llg
               << "\nurd: " << urd
               << "\nurg: " << urg
               << std::endl;
         }

         // Go to next col.
         urd.x += FRAMESIZE;
         lld.x += FRAMESIZE;
            
      } // End column loop.

      // Go to nex row.
      urd.y += FRAMESIZE;
      urd.x = FRAMESIZE-1;
      lld.y += FRAMESIZE;
      lld.x = 0;
      
   } // End row loop.

   // Close the file.
   os.close();

   ossimNotify(ossimNotifyLevel_DEBUG) << "wrote file: " << outFile << std::endl;
   
} // End: ossimRpfUtil::writeDotRpfFile
bool ossimTiledElevationDatabase::processFile(const ossimFilename& file,
                                              bool& recurseFlag)
{
   static const char M[] = "ossimTiledElevationDatabase::processFile";
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << M << " entered...\n" << "file: " << file << "\n";
   }
   bool continueFlag = true;

   ossimRefPtr<ossimSingleImageChain> sic = new ossimSingleImageChain();
   if ( sic->open(file, false) ) // False for do not open overviews.
   {
      // Set the directory walker flag.
      recurseFlag = !(isDirectoryBasedImage(sic->getImageHandler()));
     
      ossimRefPtr<ossimImageHandler> ih = sic->getImageHandler();
      if ( ih.valid() && (m_requestedRect.isLonLatNan() == false) )
      {
         ossimRefPtr<ossimImageGeometry> geom = ih->getImageGeometry();
         if ( geom.valid() == false )
         {
            std::string errMsg = M;
            errMsg += " ERROR:\nNo image geometry for image: ";
            errMsg += ih->getFilename().string();
            throw ossimException(errMsg);
         }
         
         ossimRefPtr<ossimProjection> proj = geom->getProjection();
         if ( proj.valid() == false )
         {
            std::string errMsg = M;
            errMsg += " ERROR:\nNo image projection for image: ";
            errMsg += ih->getFilename().string();
            throw ossimException(errMsg);
         }
         
         // Get the bounding rect:
         ossimGrect boundingRect;
         getBoundingRect(geom, boundingRect);
         
         if ( boundingRect.isLonLatNan() )
         {
            std::string errMsg = M;
            errMsg += " ERROR:\nBounding rect has nans for image: ";
            errMsg += ih->getFilename().string();
            throw ossimException(errMsg); 
         }
         
         if ( boundingRect.intersects(m_requestedRect) )
         {
            bool addEntryToList = false;
            
            if ( m_entries.size() == 0 ) // First time through.
            {
               addEntryToList = true;
               m_entryListRect = boundingRect;
               m_referenceProj = proj;
               m_meanSpacing = (geom->getMetersPerPixel().x + geom->getMetersPerPixel().y) / 2.0;
            }
            else 
            {
               addEntryToList = isCompatible( ih.get(), geom.get(), proj.get() );
               if ( addEntryToList )
               {
                  // Expand the rectangle.
                  m_entryListRect.combine(boundingRect);
               }
            }
            
            if ( addEntryToList )
            {
               // If we're keeping it add a cache to the chain.
               sic->addCache();
               
               //---
               // Create the entry and give to addEntry which checks for duplicates in case
               // mapRegion was called consecutively.
               //---
               ossimTiledElevationEntry entry(boundingRect, sic);
               addEntry(entry);

               continueFlag = m_requestedRect.completely_within(m_entryListRect);
            }
         }
      }
      else
      {
         std::string errMsg = M;
         errMsg += " ERROR:\nNo image geometry for image: ";
         errMsg += ih->getFilename().string();
         throw ossimException(errMsg);
      }
   }
   
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << M << " recurseFlag=" << recurseFlag
         << " continueFlag=" << continueFlag << "\n";
   }

   return continueFlag;
}
Beispiel #18
0
bool ossimHdfGridModel::setGridNodes( H5::DataSet* latDataSet,
                                      H5::DataSet* lonDataSet,
                                      ossim_uint32 imageRows,
                                      ossim_uint32 imageCols )
{
    bool status = false;

    if ( latDataSet && lonDataSet )
    {
        const ossim_uint32 GRID_SIZE = 32; // Only grab every 32nd value.

        // Get dataspace of the dataset.
        H5::DataSpace latDataSpace = latDataSet->getSpace();
        H5::DataSpace lonDataSpace = lonDataSet->getSpace();
        const ossim_int32 LAT_DIM_COUNT = latDataSpace.getSimpleExtentNdims();
        const ossim_int32 LON_DIM_COUNT = latDataSpace.getSimpleExtentNdims();

        // Number of dimensions of the input dataspace:
        if ( ( LAT_DIM_COUNT == 2 ) && ( LON_DIM_COUNT == 2 ) )
        {
            //---
            // Get the extents:
            // dimsOut[0] is height, dimsOut[1] is width:         //---
            std::vector<hsize_t> latDimsOut(LAT_DIM_COUNT);
            latDataSpace.getSimpleExtentDims( &latDimsOut.front(), 0 );
            std::vector<hsize_t> lonDimsOut(LON_DIM_COUNT);
            lonDataSpace.getSimpleExtentDims( &lonDimsOut.front(), 0 );

            // Verify same as image:
            if ( (latDimsOut[0] == imageRows) &&
                    (lonDimsOut[0] == imageRows) &&
                    (latDimsOut[1] == imageCols) &&
                    (lonDimsOut[1] == imageCols) )
            {
                //---
                // Capture the rectangle:
                // dimsOut[0] is height, dimsOut[1] is width:
                //---
                ossimIrect rect = ossimIrect( 0, 0,
                                              static_cast<ossim_int32>( latDimsOut[1]-1 ),
                                              static_cast<ossim_int32>( latDimsOut[0]-1 ) );

                //----
                // Initialize the ossimDblGrids:
                //---
                ossimDpt dspacing (GRID_SIZE, GRID_SIZE);

                ossim_uint32 gridRows = imageRows / GRID_SIZE + 1;
                ossim_uint32 gridCols = imageCols / GRID_SIZE + 1;

                // Round up if size doesn't fall on end pixel.
                if ( imageRows % GRID_SIZE) ++gridRows;
                if ( imageCols % GRID_SIZE) ++gridCols;

                ossimIpt gridSize (gridCols, gridRows);

                // The grid as used in base class, has UV-space always at 0,0 origin
                ossimDpt gridOrigin(0.0,0.0);

                const ossim_float64 NULL_VALUE = -999.0;
                theLatGrid.setNullValue(ossim::nan());
                theLonGrid.setNullValue(ossim::nan());
                theLatGrid.initialize(gridSize, gridOrigin, dspacing);
                theLonGrid.initialize(gridSize, gridOrigin, dspacing);

                std::vector<hsize_t> inputCount(LAT_DIM_COUNT);
                std::vector<hsize_t> inputOffset(LAT_DIM_COUNT);

                inputOffset[0] = 0; // row
                inputOffset[1] = 0; // col

                inputCount[0] = 1; // row
                inputCount[1] = (hsize_t)imageCols; // col

                // Output dataspace dimensions. Reading a line at a time.
                const ossim_int32 OUT_DIM_COUNT = 3;
                std::vector<hsize_t> outputCount(OUT_DIM_COUNT);
                outputCount[0] = 1; // band
                outputCount[1] = 1; // row
                outputCount[2] = imageCols; // col

                // Output dataspace offset.
                std::vector<hsize_t> outputOffset(OUT_DIM_COUNT);
                outputOffset[0] = 0;
                outputOffset[1] = 0;
                outputOffset[2] = 0;

                ossimScalarType scalar = ossim_hdf5::getScalarType( latDataSet );
                if ( scalar == OSSIM_FLOAT32 )
                {
                    // Set the return status to true if we get here...
                    status = true;

                    // See if we need to swap bytes:
                    ossimEndian* endian = 0;
                    if ( ( ossim::byteOrder() != ossim_hdf5::getByteOrder( latDataSet ) ) )
                    {
                        endian = new ossimEndian();
                    }

                    // Native type:
                    H5::DataType latDataType = latDataSet->getDataType();
                    H5::DataType lonDataType = lonDataSet->getDataType();

                    // Output dataspace always the same, width of one line.
                    H5::DataSpace bufferDataSpace( OUT_DIM_COUNT, &outputCount.front());
                    bufferDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                     &outputCount.front(),
                                                     &outputOffset.front() );

                    //  Arrays to hold a single line of latitude longitude values.
                    vector<ossim_float32> latValue(imageCols);
                    vector<ossim_float32> lonValue(imageCols);
                    hsize_t row = 0;

                    // Line loop:
                    for ( ossim_uint32 y = 0; y < gridRows; ++y )
                    {
                        // row = line in image space
                        row = y*GRID_SIZE;

                        bool hitNans = false;

                        if ( row < imageRows )
                        {
                            inputOffset[0] = row;

                            latDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                          &inputCount.front(),
                                                          &inputOffset.front() );
                            lonDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                          &inputCount.front(),
                                                          &inputOffset.front() );

                            // Read data from file into the buffer.
                            latDataSet->read( &(latValue.front()), latDataType,
                                              bufferDataSpace, latDataSpace );
                            lonDataSet->read( &(lonValue.front()), lonDataType,
                                              bufferDataSpace, lonDataSpace );

                            if ( endian )
                            {
                                // If the endian pointer is initialized(not zero) swap the bytes.
                                endian->swap( &(latValue.front()), imageCols );
                                endian->swap( &(lonValue.front()), imageCols );
                            }

                            // Sample loop:
                            hsize_t col = 0;

                            for ( ossim_uint32 x = 0; x < gridCols; ++x )
                            {
                                ossim_float32 lat = ossim::nan();
                                ossim_float32 lon = ossim::nan();

                                // col = sample in image space
                                col = x*GRID_SIZE;

                                if ( col < imageCols )
                                {
                                    if ( (latValue[col] > NULL_VALUE)&&(lonValue[col] > NULL_VALUE) )
                                    {
                                        lat = latValue[col];
                                        lon = lonValue[col];
                                    }
                                    else
                                    {
                                        hitNans = true;
                                    }
                                }
                                else // Last column is outside of image bounds.
                                {
                                    ossim_float32 latSpacing = ossim::nan();
                                    ossim_float32 lonSpacing = ossim::nan();

                                    // Get the last two latitude values:
                                    ossim_float32 lat1 = latValue[imageCols-2];
                                    ossim_float32 lat2 = latValue[imageCols-1];

                                    // Get the last two longitude values
                                    ossim_float32 lon1 = lonValue[imageCols-2];
                                    ossim_float32 lon2 = lonValue[imageCols-1];

                                    if ( ( lat1 > NULL_VALUE ) && ( lat2 > NULL_VALUE ) )
                                    {
                                        // Delta between last two latitude values.
                                        latSpacing = lat2 - lat1;

                                        // Compute:
                                        lat = lat2 + ( col - (imageCols-1) ) * latSpacing;
                                    }
                                    else
                                    {
                                        hitNans = true;
                                    }

                                    if ( ( lon1 > NULL_VALUE ) && ( lon2 > NULL_VALUE ) )
                                    {
                                        // Consider dateline crossing.
                                        if ( (lon1 > 0.0) && ( lon2 < 0.0 ) )
                                        {
                                            lon2 += 360.0;
                                        }

                                        // Delta between last two longitude values.
                                        lonSpacing = lon2 - lon1;

                                        // Compute:
                                        lon = lon2 + ( col - (imageCols-1) ) * lonSpacing;

                                        // Check for wrap:
                                        if ( lon > 180 )
                                        {
                                            lon -= 360.0;
                                        }
                                    }
                                    else
                                    {
                                        hitNans = true;
                                    }

#if 0 /* Please leave for debug. (drb) */
                                    cout << "lat1: " << lat1 << " lat2 " << lat2
                                         << " lon1 " << lon1  << " lon2 " << lon2
                                         << "\n";
#endif
                                }

                                if ( hitNans )
                                {
                                    std::string errMsg =
                                        "ossimHdfGridModel::setGridNodes encountered nans!";
                                    throw ossimException(errMsg);
                                }

                                // Assign the latitude and longitude.
                                theLatGrid.setNode( x, y, lat );
                                theLonGrid.setNode( x, y, lon );

#if 0 /* Please leave for debug. (drb) */
                                cout << "x,y,col,row,lat,lon:" << x << "," << y << ","
                                     << col << "," << row << ","
                                     << theLatGrid.getNode(x, y)
                                     << "," << theLonGrid.getNode( x, y) << "\n";
#endif

                            } // End sample loop.

                        }
                        else // Row is outside of image bounds:
                        {
                            // Read the last two rows in.
                            vector<ossim_float32> latValue2(imageCols);
                            vector<ossim_float32> lonValue2(imageCols);

                            inputOffset[0] = imageRows-2; // 2nd to last line

                            latDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                          &inputCount.front(),
                                                          &inputOffset.front() );
                            lonDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                          &inputCount.front(),
                                                          &inputOffset.front() );

                            // Read data from file into the buffer.
                            latDataSet->read( &(latValue.front()), latDataType,
                                              bufferDataSpace, latDataSpace );
                            lonDataSet->read( &(lonValue.front()), lonDataType,
                                              bufferDataSpace, lonDataSpace );

                            inputOffset[0] = imageRows-1; // last line

                            latDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                          &inputCount.front(),
                                                          &inputOffset.front() );
                            lonDataSpace.selectHyperslab( H5S_SELECT_SET,
                                                          &inputCount.front(),
                                                          &inputOffset.front() );

                            // Read data from file into the buffer.
                            latDataSet->read( &(latValue2.front()), latDataType,
                                              bufferDataSpace, latDataSpace );
                            lonDataSet->read( &(lonValue2.front()), lonDataType,
                                              bufferDataSpace, lonDataSpace );

                            if ( endian )
                            {
                                // If the endian pointer is initialized(not zero) swap the bytes.
                                endian->swap( &(latValue.front()), imageCols );
                                endian->swap( &(lonValue.front()), imageCols );
                                endian->swap( &(latValue2.front()), imageCols );
                                endian->swap( &(lonValue2.front()), imageCols );
                            }

                            // Sample loop:
                            hsize_t col = 0;
                            for ( ossim_uint32 x = 0; x < gridCols; ++x )
                            {
                                col = x*GRID_SIZE; // Sample in image space.

                                ossim_float32 lat        = ossim::nan();
                                ossim_float32 lat1       = ossim::nan();
                                ossim_float32 lat2       = ossim::nan();
                                ossim_float32 latSpacing = ossim::nan();
                                ossim_float32 lon        = ossim::nan();
                                ossim_float32 lon1       = ossim::nan();
                                ossim_float32 lon2       = ossim::nan();
                                ossim_float32 lonSpacing = ossim::nan();

                                if ( col < imageCols )
                                {
                                    lat1 = latValue[col];
                                    lat2 = latValue2[col];
                                    lon1 = lonValue[col];
                                    lon2 = lonValue2[col];
                                }
                                else // Very last grid point.
                                {
                                    // Compute the missing column for the last two image lines:
                                    lat1 = latValue[imageCols-1] + ( col - (imageCols-1)) *
                                           ( latValue[imageCols-1] - latValue[imageCols-2] );

                                    lat2 = latValue2[imageCols-1] + ( col - (imageCols-1)) *
                                           ( latValue2[imageCols-1] - latValue2[imageCols-2] );

                                    lon1 = lonValue[imageCols-1] + ( col - (imageCols-1)) *
                                           ( lonValue[imageCols-1] - lonValue[imageCols-2] );

                                    lon2 = lonValue2[imageCols-1] + ( col - (imageCols-1)) *
                                           ( lonValue2[imageCols-1] - lonValue2[imageCols-2] );
                                }

#if 0 /* Please leave for debug. (drb) */
                                cout << "lat1: " << lat1 << " lat2 " << lat2
                                     << " lon1 " << lon1  << " lon2 " << lon2
                                     << "\n";
#endif

                                if ( ( lon1 > NULL_VALUE ) && ( lon2 > NULL_VALUE ) )
                                {
                                    // Consider dateline crossing.
                                    if ( (lon1 > 0.0) && ( lon2 < 0.0 ) )
                                    {
                                        lon2 += 360.0;
                                    }

                                    // Delta between last two longitude values.
                                    lonSpacing = lon2 - lon1;

                                    // Compute:
                                    lon = lon2 + ( row - (imageRows-1) ) * lonSpacing;

                                    // Check for wrap:
                                    if ( lon > 180 )
                                    {
                                        lon -= 360.0;
                                    }
                                }
                                else
                                {
                                    hitNans = true;
                                }

                                if ( ( lat1 > NULL_VALUE ) && ( lat2 > NULL_VALUE ) )
                                {
                                    // Delta between last two latitude values.
                                    latSpacing = lat2 - lat1;

                                    // Compute:
                                    lat = lat2 + ( row - (imageRows-1) ) * latSpacing;
                                }
                                else
                                {
                                    hitNans = true;
                                }

                                if ( hitNans )
                                {
                                    std::string errMsg =
                                        "ossimHdfGridModel::setGridNodes encountered nans!";
                                    throw ossimException(errMsg);
                                }

                                // Assign the latitude::
                                theLatGrid.setNode( x, y, lat );

                                // Assign the longitude.
                                theLonGrid.setNode( x, y, lon );

#if 0 /* Please leave for debug. (drb) */
                                cout << "x,y,col,row,lat,lon:" << x << "," << y << ","
                                     << col << "," << row << "," << lat << "," << lon << "\n";
#endif

                            } // End sample loop.

                        } // Matches if ( row < imageRows ){...}else{

                    } // End line loop.

                    latDataSpace.close();
                    lonDataSpace.close();

                    if ( status )
                    {
                        theLatGrid.enableExtrapolation();
                        theLonGrid.enableExtrapolation();
                        theHeightEnabledFlag = false;
                        ossimDrect imageRect(rect);
                        initializeModelParams(imageRect);
                        // debugDump();
                    }

                } // Matches: if ( scalar == OSSIM_FLOAT32 )

            } // Matches: if ( (latDimsOut[0] == imageRows) ...

        } // Matches: if ( ( LAT_DIM_COUNT == 2 ) ...

    } // Matches: if ( latDataSet && lonDataSet

    return status;

} // End: bool ossimHdfGridModel::setGridNodes( H5::DataSet* latDataSet, ... )