<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

/// deplate.cc
///
/// Converts a plate file to GeoTIFF tiles on disk.

#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Plate/PlateView.h>
#include <vw/Plate/PlateCarreePlateManager.h>

using namespace vw;
using namespace vw::platefile;

#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;

struct Options {
  Options() : west(0), east(0), north(0), south(0), tile_size(0),
              tile_size_deg(0), pds_dem_mode(false), pds_imagery_mode(false) {}

  // Input for project file
  std::string plate_file_name;

  // Settings
  int west, east, north, south, tile_size, tile_size_deg;
  double tile_ppd;
  bool pds_dem_mode, pds_imagery_mode;

  // Output
  std::string output_datum, output_prefix;
};

// ConvertToPDSImagery
//  .. coverts an image into the range of 1-254 where 0 is invalid and 255 is reserved.
template <class PixelT>
class ConvertToPDSImagery : public ReturnFixedType<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type> {
  typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type return_type;
  typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,double>::type return_double_type;
  typedef typename CompoundChannelType<PixelT>::type input_channel_type;
public:
  return_type operator()( PixelT value ) const {
    if ( is_transparent(value) ) {
      return return_type();
    } else {
      return_double_type result
        = channel_cast<double>(non_alpha_channels(value))*253.0/ChannelRange<input_channel_type>::max();
      for ( uint8 i = 0; i < CompoundNumChannels<return_double_type>::value; i++ ) {
        if (result[i] < 0)
          result[i] = 0;
        if (result[i] > 253)
          result[i] = 253;
      }
      return channel_cast<uint8>(result)+1;
    }
  }
};

template <class ImageT>
UnaryPerPixelView<ImageT, ConvertToPDSImagery<typename ImageT::pixel_type> >
inline convert_to_pds_imagery( ImageViewBase<ImageT> const& image ) {
  typedef ConvertToPDSImagery<typename ImageT::pixel_type> func_type;
  return UnaryPerPixelView<ImageT, func_type>( image.impl(), func_type() );
}

template <class PixelT>
void do_tiles(boost::shared_ptr<PlateFile> platefile, Options& opt) {

  PlateCarreePlateManager<PixelT> pm(platefile);
  cartography::GeoReference output_georef = pm.georeference(platefile->num_levels()-1);
  cartography::Datum datum;
  datum.set_well_known_datum( opt.output_datum );
  output_georef.set_datum( datum );

  PlateView<PixelT> plate_view(opt.plate_file_name);
  ImageViewRef<PixelT> plate_view_ref = plate_view;
  double scale_change = 1;
  if ( opt.tile_ppd > 0 ) {
    // Finding out our current PPD and attempting to match
    double curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))-
                             output_georef.lonlat_to_pixel(Vector2(1,0)));
    scale_change = opt.tile_ppd / curr_ppd;
    plate_view_ref = resample( plate_view, scale_change, scale_change,
                               ZeroEdgeExtension());
    Matrix3x3 scale;
    scale.set_identity();
    scale(0,0) /= scale_change;
    scale(1,1) /= scale_change;
    output_georef.set_transform( output_georef.transform()*scale );

    // Double check
    curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))-
                      output_georef.lonlat_to_pixel(Vector2(1,0)));
  }
  std::cout << "Converting " << opt.plate_file_name << " to " << opt.output_prefix << "\n";
  std::cout << output_georef << "\n";

  // Get the output georeference.
  vw::BBox2i output_bbox;
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.north)));
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.north)));
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.south)));
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.south)));
  std::cout << "\t--> Output bbox: " << output_bbox << "\n";

  if ( opt.tile_size_deg > 0 ) {
    if ( opt.tile_ppd > 0 ) {
      opt.tile_size = opt.tile_size_deg * opt.tile_ppd;
    } else {
      // User must have specified out to be sized in degrees
      opt.tile_size = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0)) -
                             output_georef.lonlat_to_pixel(Vector2(opt.tile_size_deg,0)));
    }
  }

  // Compute the bounding box for each tile.
  std::vector<BBox2i> crop_bboxes = image_blocks(crop(plate_view_ref, output_bbox),
                                                 opt.tile_size, opt.tile_size);

  for (unsigned i = 0; i < crop_bboxes.size(); ++i) {
    // The crop bboxes start at (0,0), and we want them to start at
    // the upper left corner of the output_bbox.
    crop_bboxes[i].min() += output_bbox.min();
    crop_bboxes[i].max() += output_bbox.min();

    { // Checking to see if this section is transparent
      std::list<TileHeader> theaders =
        plate_view.search_for_tiles( crop_bboxes[i] / scale_change );
      if (theaders.empty())
        continue;
    }

    cartography::GeoReference tile_georef = output_georef;
    Vector2 top_left_ll = output_georef.pixel_to_lonlat(crop_bboxes[i].min());
    Matrix3x3 T = tile_georef.transform();
    T(0,2) = top_left_ll(0);
    T(1,2) = top_left_ll(1);
    tile_georef.set_transform(T);

    std::cout << "\t--> Generating tile " << (i+1) << " / " << crop_bboxes.size()
              << " : " << crop_bboxes[i] << "\n"
              << "\t    with transform  "
              << tile_georef.transform() << "\n";

    std::ostringstream output_filename;
    output_filename << opt.output_prefix << "_"
                    << abs(round(top_left_ll[0]));
    if ( top_left_ll[0] < 0 )
      output_filename << "W_";
    else
      output_filename << "E_";
    output_filename << abs(round(top_left_ll[1]));
    if ( top_left_ll[1] >= 0 )
      output_filename << "N.tif";
    else
      output_filename << "S.tif";

    ImageView<PixelT> cropped_view = crop(plate_view_ref, crop_bboxes[i]);
    DiskImageResourceGDAL::Options gdal_options;
    gdal_options["COMPRESS"] = "LZW";

    if ( opt.pds_dem_mode ) {
      ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,int16>::type > dem_image = apply_mask(alpha_to_mask(channel_cast<int16>(cropped_view)),-32767);
      DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(),
                                 Vector2i(256,256), gdal_options);
      write_georeference(rsrc, tile_georef);
      write_image(rsrc, dem_image,
                  TerminalProgressCallback( "plate.tools", "\t    Writing: "));
    } else if ( opt.pds_imagery_mode ) {
      ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,uint8>::type > dem_image = convert_to_pds_imagery( cropped_view );
      DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(),
                                 Vector2i(256,256), gdal_options);
      write_georeference(rsrc, tile_georef);
      write_image(rsrc, dem_image,
                  TerminalProgressCallback( "plate.tools", "\t    Writing: "));
    } else {
      DiskImageResourceGDAL rsrc(output_filename.str(), cropped_view.format(),
                                 Vector2i(256,256), gdal_options);
      write_georeference(rsrc, tile_georef);
      write_image(rsrc, cropped_view,
                  TerminalProgressCallback( "plate.tools", "\t    Writing: "));
    }

  }
}

void handle_arguments( int argc, char *argv[], Options& opt ) {
  po::options_description general_options("Chops platefile into georeferenced squares.\n\nGeneral Options");
  general_options.add_options()
    ("output-prefix,o", po::value(&opt.output_prefix), "Specify the base output directory")
    ("west,w", po::value(&opt.west)->default_value(-180), "Specify west edge of the region to extract (deg).")
    ("east,e", po::value(&opt.east)->default_value(180), "Specify east edge of the region to extract (deg).")
    ("north,n", po::value(&opt.north)->default_value(90), "Specify north edge of the region to extract (deg).")
    ("south,s", po::value(&opt.south)->default_value(-90), "Specify south edge of the region to extract (deg).")
    ("tile-size-px,t", po::value(&opt.tile_size)->default_value(4096), "Specify the size of each output dem in pixels.")
    ("tile-size-deg,d", po::value(&opt.tile_size_deg), "Specify the size of each output dem in degrees.")
    ("tile-px-per-degree,p", po::value(&opt.tile_ppd), "Specify the output tiles' pixel per degrees.")
    ("output-datum", po::value(&opt.output_datum)->default_value("WGS84"), "Specify the output datum to use, [WGS84, WGS72, D_MOON, D_MARS]")
    ("export-pds-dem", "Export using int16 channel value with a -32767 nodata value")
    ("export-pds-imagery", "Export using uint8 channel value with a 0 nodata value")
    ("help", "Display this help message");

  po::options_description positional("");
  positional.add_options()
    ("plate-file", po::value(&opt.plate_file_name));

  po::positional_options_description positional_desc;
  positional_desc.add("plate-file", 1);

  po::options_description all_options;
  all_options.add(general_options).add(positional);

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
    po::notify( vm );
  } catch (po::error &e) {
    vw_throw( ArgumentErr() << "Error parsing input:\n\t"
              << e.what() << general_options );
  }

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " <platefile-url> <optional project settings> \n";

  if ( vm.count("help") )
    vw_throw( ArgumentErr() << usage.str() << general_options );
  if ( opt.plate_file_name.empty() )
    vw_throw( ArgumentErr() << "Missing input platefile!\n"
              << usage.str() << general_options );

  opt.pds_dem_mode = vm.count("export-pds-dem");
  opt.pds_imagery_mode = vm.count("export-pds-imagery");

  if( opt.output_prefix == "" ) {
    opt.output_prefix = fs::path(opt.plate_file_name).stem();
    int indx = opt.output_prefix.rfind("/");
    if ( indx > 0 )
      opt.output_prefix = opt.output_prefix.substr(indx+1);
  }
}

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

  Options opt;
  try {
    handle_arguments( argc, argv, opt );

    boost::shared_ptr<PlateFile> platefile(new PlateFile(opt.plate_file_name));

    std::cout << "Opened " << opt.plate_file_name << ".     Depth: "
              << platefile->num_levels() << " levels.\n";

    PixelFormatEnum pixel_format = platefile->pixel_format();
    ChannelTypeEnum channel_type = platefile->channel_type();

    switch(pixel_format) {
    case VW_PIXEL_GRAYA:
      switch(channel_type) {
      case VW_CHANNEL_UINT8:
        do_tiles<PixelGrayA<uint8> >(platefile, opt);
        break;
      case VW_CHANNEL_INT16:
        do_tiles<PixelGrayA<int16> >(platefile, opt);
        break;
      case VW_CHANNEL_FLOAT32:
        do_tiles<PixelGrayA<float32> >(platefile, opt);
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n");
      }
      break;
    case VW_PIXEL_RGB:
    case VW_PIXEL_RGBA:
    default:
      switch(channel_type) {
      case VW_CHANNEL_UINT8:
        do_tiles<PixelRGBA<uint8> >(platefile, opt);
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n");
      }
      break;
    }

  } catch ( const ArgumentErr& e ) {
    vw_out() << e.what() << std::endl;
    return 1;
  } catch ( const Exception& e ) {
    std::cerr << "VW Error: " << e.what() << std::endl;
    return 1;
  } catch ( const std::bad_alloc& e ) {
    std::cerr << "Error: Ran out of Memory!" << std::endl;
    return 1;
  } catch ( const std::exception& e ) {
    std::cerr << "Error: " << e.what() <<  std::endl;
    return 1;
  }
}
<commit_msg>Added the ability to operate with a specific level of the platefile<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

/// deplate.cc
///
/// Converts a plate file to GeoTIFF tiles on disk.

#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Plate/PlateView.h>
#include <vw/Plate/PlateCarreePlateManager.h>

using namespace vw;
using namespace vw::platefile;

#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;

struct Options {
  Options() : west(0), east(0), north(0), south(0), tile_size(0),
              tile_size_deg(0), pds_dem_mode(false), pds_imagery_mode(false) {}

  // Input for project file
  std::string plate_file_name;

  // Settings
  int west, east, north, south, tile_size, tile_size_deg;
  double tile_ppd;
  bool pds_dem_mode, pds_imagery_mode;
  int level;

  // Output
  std::string output_datum, output_prefix;
};

// ConvertToPDSImagery
//  .. coverts an image into the range of 1-254 where 0 is invalid and 255 is reserved.
template <class PixelT>
class ConvertToPDSImagery : public ReturnFixedType<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type> {
  typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type return_type;
  typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,double>::type return_double_type;
  typedef typename CompoundChannelType<PixelT>::type input_channel_type;
public:
  return_type operator()( PixelT value ) const {
    if ( is_transparent(value) ) {
      return return_type();
    } else {
      return_double_type result
        = channel_cast<double>(non_alpha_channels(value))*253.0/ChannelRange<input_channel_type>::max();
      for ( uint8 i = 0; i < CompoundNumChannels<return_double_type>::value; i++ ) {
        if (result[i] < 0)
          result[i] = 0;
        if (result[i] > 253)
          result[i] = 253;
      }
      return channel_cast<uint8>(result)+1;
    }
  }
};

template <class ImageT>
UnaryPerPixelView<ImageT, ConvertToPDSImagery<typename ImageT::pixel_type> >
inline convert_to_pds_imagery( ImageViewBase<ImageT> const& image ) {
  typedef ConvertToPDSImagery<typename ImageT::pixel_type> func_type;
  return UnaryPerPixelView<ImageT, func_type>( image.impl(), func_type() );
}

template <class PixelT>
void do_tiles(boost::shared_ptr<PlateFile> platefile, Options& opt) {

  PlateCarreePlateManager<PixelT> pm(platefile);
  cartography::GeoReference output_georef;
  output_georef = pm.georeference(platefile->num_levels()-1);

  cartography::Datum datum;
  datum.set_well_known_datum( opt.output_datum );
  output_georef.set_datum( datum );

  PlateView<PixelT> plate_view(opt.plate_file_name);
  if ( opt.level != -1 )
    plate_view.set_level( opt.level );
  ImageViewRef<PixelT> plate_view_ref = plate_view;
  double scale_change = 1;
  if ( opt.tile_ppd > 0 ) {
    // Finding out our current PPD and attempting to match
    double curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))-
                             output_georef.lonlat_to_pixel(Vector2(1,0)));
    scale_change = opt.tile_ppd / curr_ppd;
    plate_view_ref = resample( plate_view, scale_change, scale_change,
                               ZeroEdgeExtension());
    Matrix3x3 scale;
    scale.set_identity();
    scale(0,0) /= scale_change;
    scale(1,1) /= scale_change;
    output_georef.set_transform( output_georef.transform()*scale );

    // Double check
    curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))-
                      output_georef.lonlat_to_pixel(Vector2(1,0)));
  }
  std::cout << "Converting " << opt.plate_file_name << " to " << opt.output_prefix << "\n";
  std::cout << output_georef << "\n";

  // Get the output georeference.
  vw::BBox2i output_bbox;
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.north)));
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.north)));
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.south)));
  output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.south)));
  std::cout << "\t--> Output bbox: " << output_bbox << "\n";

  if ( opt.tile_size_deg > 0 ) {
    if ( opt.tile_ppd > 0 ) {
      opt.tile_size = opt.tile_size_deg * opt.tile_ppd;
    } else {
      // User must have specified out to be sized in degrees
      opt.tile_size = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0)) -
                             output_georef.lonlat_to_pixel(Vector2(opt.tile_size_deg,0)));
    }
  }

  // Compute the bounding box for each tile.
  std::vector<BBox2i> crop_bboxes = image_blocks(crop(plate_view_ref, output_bbox),
                                                 opt.tile_size, opt.tile_size);

  for (unsigned i = 0; i < crop_bboxes.size(); ++i) {
    // The crop bboxes start at (0,0), and we want them to start at
    // the upper left corner of the output_bbox.
    crop_bboxes[i].min() += output_bbox.min();
    crop_bboxes[i].max() += output_bbox.min();

    { // Checking to see if this section is transparent
      std::list<TileHeader> theaders =
        plate_view.search_for_tiles( crop_bboxes[i] / scale_change );
      if (theaders.empty())
        continue;
    }

    cartography::GeoReference tile_georef = output_georef;
    Vector2 top_left_ll = output_georef.pixel_to_lonlat(crop_bboxes[i].min());
    Matrix3x3 T = tile_georef.transform();
    T(0,2) = top_left_ll(0);
    T(1,2) = top_left_ll(1);
    tile_georef.set_transform(T);

    std::cout << "\t--> Generating tile " << (i+1) << " / " << crop_bboxes.size()
              << " : " << crop_bboxes[i] << "\n"
              << "\t    with transform  "
              << tile_georef.transform() << "\n";

    std::ostringstream output_filename;
    output_filename << opt.output_prefix << "_"
                    << abs(round(top_left_ll[0]));
    if ( top_left_ll[0] < 0 )
      output_filename << "W_";
    else
      output_filename << "E_";
    output_filename << abs(round(top_left_ll[1]));
    if ( top_left_ll[1] >= 0 )
      output_filename << "N.tif";
    else
      output_filename << "S.tif";

    ImageView<PixelT> cropped_view = crop(plate_view_ref, crop_bboxes[i]);
    DiskImageResourceGDAL::Options gdal_options;
    gdal_options["COMPRESS"] = "LZW";

    if ( opt.pds_dem_mode ) {
      ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,int16>::type > dem_image = apply_mask(alpha_to_mask(channel_cast<int16>(cropped_view)),-32767);
      DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(),
                                 Vector2i(256,256), gdal_options);
      write_georeference(rsrc, tile_georef);
      write_image(rsrc, dem_image,
                  TerminalProgressCallback( "plate.tools", "\t    Writing: "));
    } else if ( opt.pds_imagery_mode ) {
      ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,uint8>::type > dem_image = convert_to_pds_imagery( cropped_view );
      DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(),
                                 Vector2i(256,256), gdal_options);
      write_georeference(rsrc, tile_georef);
      write_image(rsrc, dem_image,
                  TerminalProgressCallback( "plate.tools", "\t    Writing: "));
    } else {
      DiskImageResourceGDAL rsrc(output_filename.str(), cropped_view.format(),
                                 Vector2i(256,256), gdal_options);
      write_georeference(rsrc, tile_georef);
      write_image(rsrc, cropped_view,
                  TerminalProgressCallback( "plate.tools", "\t    Writing: "));
    }

  }
}

void handle_arguments( int argc, char *argv[], Options& opt ) {
  po::options_description general_options("Chops platefile into georeferenced squares.\n\nGeneral Options");
  general_options.add_options()
    ("output-prefix,o", po::value(&opt.output_prefix), "Specify the base output directory")
    ("level,l", po::value(&opt.level)->default_value(-1), "Level inside the plate in which to process. -1 will error out at show the number of levels available.")
    ("west,w", po::value(&opt.west)->default_value(-180), "Specify west edge of the region to extract (deg).")
    ("east,e", po::value(&opt.east)->default_value(180), "Specify east edge of the region to extract (deg).")
    ("north,n", po::value(&opt.north)->default_value(90), "Specify north edge of the region to extract (deg).")
    ("south,s", po::value(&opt.south)->default_value(-90), "Specify south edge of the region to extract (deg).")
    ("tile-size-px,t", po::value(&opt.tile_size)->default_value(4096), "Specify the size of each output dem in pixels.")
    ("tile-size-deg,d", po::value(&opt.tile_size_deg), "Specify the size of each output dem in degrees.")
    ("tile-px-per-degree,p", po::value(&opt.tile_ppd), "Specify the output tiles' pixel per degrees.")
    ("output-datum", po::value(&opt.output_datum)->default_value("WGS84"), "Specify the output datum to use, [WGS84, WGS72, D_MOON, D_MARS]")
    ("export-pds-dem", "Export using int16 channel value with a -32767 nodata value")
    ("export-pds-imagery", "Export using uint8 channel value with a 0 nodata value")
    ("help", "Display this help message");

  po::options_description positional("");
  positional.add_options()
    ("plate-file", po::value(&opt.plate_file_name));

  po::positional_options_description positional_desc;
  positional_desc.add("plate-file", 1);

  po::options_description all_options;
  all_options.add(general_options).add(positional);

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
    po::notify( vm );
  } catch (po::error &e) {
    vw_throw( ArgumentErr() << "Error parsing input:\n\t"
              << e.what() << general_options );
  }

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " <platefile-url> <optional project settings> \n";

  if ( vm.count("help") )
    vw_throw( ArgumentErr() << usage.str() << general_options );
  if ( opt.plate_file_name.empty() )
    vw_throw( ArgumentErr() << "Missing input platefile!\n"
              << usage.str() << general_options );

  opt.pds_dem_mode = vm.count("export-pds-dem");
  opt.pds_imagery_mode = vm.count("export-pds-imagery");

  if( opt.output_prefix == "" ) {
    opt.output_prefix = fs::path(opt.plate_file_name).stem();
    int indx = opt.output_prefix.rfind("/");
    if ( indx > 0 )
      opt.output_prefix = opt.output_prefix.substr(indx+1);
  }
}

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

  Options opt;
  try {
    handle_arguments( argc, argv, opt );

    boost::shared_ptr<PlateFile> platefile(new PlateFile(opt.plate_file_name));

    std::cout << "Opened " << opt.plate_file_name << ".     Depth: "
              << platefile->num_levels() << " levels.\n";

    PixelFormatEnum pixel_format = platefile->pixel_format();
    ChannelTypeEnum channel_type = platefile->channel_type();

    switch(pixel_format) {
    case VW_PIXEL_GRAYA:
      switch(channel_type) {
      case VW_CHANNEL_UINT8:
        do_tiles<PixelGrayA<uint8> >(platefile, opt);
        break;
      case VW_CHANNEL_INT16:
        do_tiles<PixelGrayA<int16> >(platefile, opt);
        break;
      case VW_CHANNEL_FLOAT32:
        do_tiles<PixelGrayA<float32> >(platefile, opt);
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n");
      }
      break;
    case VW_PIXEL_RGB:
    case VW_PIXEL_RGBA:
    default:
      switch(channel_type) {
      case VW_CHANNEL_UINT8:
        do_tiles<PixelRGBA<uint8> >(platefile, opt);
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n");
      }
      break;
    }

  } catch ( const ArgumentErr& e ) {
    vw_out() << e.what() << std::endl;
    return 1;
  } catch ( const Exception& e ) {
    std::cerr << "VW Error: " << e.what() << std::endl;
    return 1;
  } catch ( const std::bad_alloc& e ) {
    std::cerr << "Error: Ran out of Memory!" << std::endl;
    return 1;
  } catch ( const std::exception& e ) {
    std::cerr << "Error: " << e.what() <<  std::endl;
    return 1;
  }
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * PokerTH - The open source texas holdem engine                             *
 * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May          *
 *                                                                           *
 * This program is free software: you can redistribute it and/or modify      *
 * it under the terms of the GNU Affero General Public License as            *
 * published by the Free Software Foundation, either version 3 of the        *
 * License, or (at your option) any later version.                           *
 *                                                                           *
 * This program is distributed in the hope that it will be useful,           *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 * GNU Affero General Public License for more details.                       *
 *                                                                           *
 * You should have received a copy of the GNU Affero General Public License  *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *****************************************************************************/
#include "sdlplayer.h"

#if (defined __APPLE__)
#include <SDL.h>
#else
#include <SDL/SDL.h>
#endif

using namespace std;

SDLPlayer::SDLPlayer(ConfigFile *c)
	: soundData(NULL), currentChannel(0) , audioEnabled(0), myConfig(c)
{
	SDL_Init(SDL_INIT_AUDIO);
	initAudio();

	myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str());
}

SDLPlayer::~SDLPlayer()
{
	closeAudio();
	SDL_Quit();
}

void SDLPlayer::initAudio()
{

	if (!audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {
		int		audio_rate = 44100;
		Uint16	audio_format = AUDIO_S16; /* 16-bit stereo */
		int		audio_channels = 2;
		int		audio_buffers = 4096;
		sound = NULL;

		if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == 0) {
			Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
			audioEnabled = 1;
		}
	}
}

void SDLPlayer::playSound(string audioString, int playerID)
{

	if(audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {

		QFile myFile(myAppDataPath + "sounds/default/" + QString::fromStdString(audioString)+".wav");

		if(myFile.open(QIODevice::ReadOnly)) {

			//set 3d position for player
			int position = 0;
			int distance = 0;

			switch (playerID) {

			case 0: {
				position = 180;
				distance = 10;
			}
			break;
			case 1: {
				position = 281;
				distance = 50;
			}
			break;
			case 2: {
				position = 315;
				distance = 120;
			}
			break;
			case 3: {
				position = 338;
				distance = 160;
			}
			break;
			case 4: {
				position = 23;
				distance = 160;
			}
			break;
			case 5: {
				position = 45;
				distance = 120;
			}
			break;
			case 6: {
				position = 79;
				distance = 50;
			}
			break;
			default: {
				position = 0;
				distance = 0;
			}
			break;
			}

			audioDone();

			QDataStream in(&myFile);
			soundData = new Uint8[(int)myFile.size()];
			in.readRawData( (char*)soundData, (int)myFile.size() );

			sound = Mix_QuickLoad_WAV(soundData);

			// set channel 0 to settings volume
			Mix_Volume(0,myConfig->readConfigInt("SoundVolume")*10);

			// set 3d effect
			if(!Mix_SetPosition(0, position, distance)) {
				printf("Mix_SetPosition: %s\n", Mix_GetError());
				// no position effect, is it ok?
			}
			currentChannel = Mix_PlayChannel(-1, sound,0);
		}
		// 	else cout << "could not load " << audioString << ".wav" << endl;

		//test
		//	audioDone();
		//	sound = Mix_LoadWAV( QString(QString::fromStdString(audioString)+QString(".wav")).toStdString().c_str() );
		//	currentChannel = Mix_PlayChannel(-1, sound,0);

	}
}

void SDLPlayer::audioDone()
{

	if(audioEnabled) {
		Mix_HaltChannel(currentChannel);
		Mix_FreeChunk(sound);
		sound = NULL;
		delete[] soundData;
		soundData = NULL;
	}
}

void SDLPlayer::closeAudio()
{

	if(audioEnabled) {
		audioDone();
		Mix_CloseAudio();
		audioEnabled = false;
	}
}
<commit_msg>some audio system tweaks to fix stop playing longer tracks for a new one instead of overlaying<commit_after>/*****************************************************************************
 * PokerTH - The open source texas holdem engine                             *
 * Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May          *
 *                                                                           *
 * This program is free software: you can redistribute it and/or modify      *
 * it under the terms of the GNU Affero General Public License as            *
 * published by the Free Software Foundation, either version 3 of the        *
 * License, or (at your option) any later version.                           *
 *                                                                           *
 * This program is distributed in the hope that it will be useful,           *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 * GNU Affero General Public License for more details.                       *
 *                                                                           *
 * You should have received a copy of the GNU Affero General Public License  *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *****************************************************************************/
#include "sdlplayer.h"

#if (defined __APPLE__)
#include <SDL.h>
#else
#include <SDL/SDL.h>
#endif

using namespace std;

SDLPlayer::SDLPlayer(ConfigFile *c)
	: soundData(NULL), currentChannel(0) , audioEnabled(0), myConfig(c)
{
	SDL_Init(SDL_INIT_AUDIO);
	initAudio();

	myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str());
}

SDLPlayer::~SDLPlayer()
{
	closeAudio();
	SDL_Quit();
}

void SDLPlayer::initAudio()
{

	if (!audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {
		int		audio_rate = 44100;
		Uint16	audio_format = AUDIO_S16; /* 16-bit stereo */
		int		audio_channels = 2;
		int		audio_buffers = 4096;
		sound = NULL;

		if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == 0) {
			Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
			audioEnabled = 1;
		}
	}
}

void SDLPlayer::playSound(string audioString, int playerID)
{

	if(audioEnabled && myConfig->readConfigInt("PlaySoundEffects")) {

		QFile myFile(myAppDataPath + "sounds/default/" + QString::fromStdString(audioString)+".wav");

		if(myFile.open(QIODevice::ReadOnly)) {

			//set 3d position for player
			int position = 0;
			int distance = 0;

			switch (playerID) {

			case 0: {
				position = 180;
				distance = 10;
			}
			break;
			case 1: {
				position = 281;
				distance = 50;
			}
			break;
			case 2: {
				position = 315;
				distance = 120;
			}
			break;
			case 3: {
				position = 338;
				distance = 160;
			}
			break;
			case 4: {
				position = 23;
				distance = 160;
			}
			break;
			case 5: {
				position = 45;
				distance = 120;
			}
			break;
			case 6: {
				position = 79;
				distance = 50;
			}
			break;
			default: {
				position = 0;
				distance = 0;
			}
			break;
			}

//			audioDone();

			QDataStream in(&myFile);
			soundData = new Uint8[(int)myFile.size()];
			in.readRawData( (char*)soundData, (int)myFile.size() );

			sound = Mix_QuickLoad_WAV(soundData);

			// set channel 0 to settings volume
			Mix_Volume(0,myConfig->readConfigInt("SoundVolume")*10);

			// set 3d effect
			if(!Mix_SetPosition(0, position, distance)) {
				printf("Mix_SetPosition: %s\n", Mix_GetError());
				// no position effect, is it ok?
			}
			currentChannel = Mix_PlayChannel(-1, sound,0);
		}
		// 	else cout << "could not load " << audioString << ".wav" << endl;

		//test
		//	audioDone();
		//	sound = Mix_LoadWAV( QString(QString::fromStdString(audioString)+QString(".wav")).toStdString().c_str() );
		//	currentChannel = Mix_PlayChannel(-1, sound,0);

	}
}

void SDLPlayer::audioDone()
{

	if(audioEnabled) {
		Mix_HaltChannel(currentChannel);
		Mix_FreeChunk(sound);
		sound = NULL;
		delete[] soundData;
		soundData = NULL;
	}
}

void SDLPlayer::closeAudio()
{

	if(audioEnabled) {
		audioDone();
		Mix_CloseAudio();
		audioEnabled = false;
	}
}
<|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2005-2008.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : contains XML Log formatter definition
// ***************************************************************************

#ifndef BOOST_TEST_XML_LOG_FORMATTER_020105GER
#define BOOST_TEST_XML_LOG_FORMATTER_020105GER

// Boost.Test
#include <boost/test/detail/global_typedef.hpp>
#include <boost/test/unit_test_log_formatter.hpp>

// STL
#include <cstddef> // std::size_t

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {

namespace unit_test {

namespace output {

// ************************************************************************** //
// **************               xml_log_formatter              ************** //
// ************************************************************************** //

class xml_log_formatter : public unit_test_log_formatter {
public:
    // Formatter interface
    void    log_start( std::ostream&, counter_t test_cases_amount );
    void    log_finish( std::ostream& );
    void    log_build_info( std::ostream& );

    void    test_unit_start( std::ostream&, test_unit const& tu );
    void    test_unit_finish( std::ostream&, test_unit const& tu, unsigned long elapsed );
    void    test_unit_skipped( std::ostream&, test_unit const& tu );

    void    log_exception( std::ostream&, log_checkpoint_data const&, const_string explanation );

    void    log_entry_start( std::ostream&, log_entry_data const&, log_entry_types let );
    void    log_entry_value( std::ostream&, const_string value );
    void    log_entry_finish( std::ostream& );

private:
    // Data members
    const_string    m_curr_tag;
};

} // namespace output

} // namespace unit_test

} // namespace boost

//____________________________________________________________________________//

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_XML_LOG_FORMATTER_020105GER
<commit_msg>bring the base class function into the overload set<commit_after>//  (C) Copyright Gennadiy Rozental 2005-2008.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : contains XML Log formatter definition
// ***************************************************************************

#ifndef BOOST_TEST_XML_LOG_FORMATTER_020105GER
#define BOOST_TEST_XML_LOG_FORMATTER_020105GER

// Boost.Test
#include <boost/test/detail/global_typedef.hpp>
#include <boost/test/unit_test_log_formatter.hpp>

// STL
#include <cstddef> // std::size_t

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {

namespace unit_test {

namespace output {

// ************************************************************************** //
// **************               xml_log_formatter              ************** //
// ************************************************************************** //

class xml_log_formatter : public unit_test_log_formatter {
public:
    // Formatter interface
    void    log_start( std::ostream&, counter_t test_cases_amount );
    void    log_finish( std::ostream& );
    void    log_build_info( std::ostream& );

    void    test_unit_start( std::ostream&, test_unit const& tu );
    void    test_unit_finish( std::ostream&, test_unit const& tu, unsigned long elapsed );
    void    test_unit_skipped( std::ostream&, test_unit const& tu );

    void    log_exception( std::ostream&, log_checkpoint_data const&, const_string explanation );

    void    log_entry_start( std::ostream&, log_entry_data const&, log_entry_types let );
    using   unit_test_log_formatter::log_entry_value; // bring base class functions into overload set
    void    log_entry_value( std::ostream&, const_string value );
    void    log_entry_finish( std::ostream& );

private:
    // Data members
    const_string    m_curr_tag;
};

} // namespace output

} // namespace unit_test

} // namespace boost

//____________________________________________________________________________//

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_XML_LOG_FORMATTER_020105GER
<|endoftext|>


<commit_before>#pragma once
#ifndef OPENGM_GRIDSEARCH_LEARNER_HXX
#define OPENGM_GRIDSEARCH_LEARNER_HXX

#include <vector>

namespace opengm {
   namespace learning {

      template<class DATASET>
      class GridSearchLearner
      {
      public:
         typedef DATASET DatasetType;
         typedef typename DATASET::GMType   GMType;
         typedef typename DATASET::LossType LossType;
         typedef typename GMType::ValueType ValueType;
         typedef typename GMType::IndexType IndexType;
         typedef typename GMType::LabelType LabelType;

         class Parameter{
         public:
            std::vector<double> parameterUpperbound_;
            std::vector<double> parameterLowerbound_;
            std::vector<size_t> testingPoints_;
            Parameter(){;}
         };

         GridSearchLearner(DATASET&, const Parameter& );

         template<class INF>
         void learn(const typename INF::Parameter& para);
         //template<class INF, class VISITOR>
         //void learn(typename INF::Parameter para, VITITOR vis);

         const opengm::learning::Weights<double>& getWeights(){return weights_;}
         Parameter& getLerningParameters(){return para_;}

      private:
         DATASET& dataset_;
         opengm::learning::Weights<double> weights_;
         Parameter para_;
      };

      template<class DATASET>
      GridSearchLearner<DATASET>::GridSearchLearner(DATASET& ds, const Parameter& p )
         : dataset_(ds), para_(p)
      {
         weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());
         if(para_.parameterUpperbound_.size() != ds.getNumberOfWeights())
            para_.parameterUpperbound_.resize(ds.getNumberOfWeights(),10.0);
         if(para_.parameterLowerbound_.size() != ds.getNumberOfWeights())
            para_.parameterLowerbound_.resize(ds.getNumberOfWeights(),0.0);
         if(para_.testingPoints_.size() != ds.getNumberOfWeights())
            para_.testingPoints_.resize(ds.getNumberOfWeights(),10);
      }

      template<class DATASET>
      template<class INF>
      void GridSearchLearner<DATASET>::learn(const typename INF::Parameter& para){
         // generate model Parameters
         opengm::learning::Weights<double> modelPara( dataset_.getNumberOfWeights() );
         opengm::learning::Weights<double> bestModelPara( dataset_.getNumberOfWeights() );
         double                            bestLoss = 100000000.0;
         std::vector<size_t> itC(dataset_.getNumberOfWeights(),0);

         LossType lossFunction;
         bool search=true;
         while(search){
            // Get Parameter
            for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
               modelPara.setWeight(p, para_.parameterLowerbound_[p] + double(itC[p])/double(para_.testingPoints_[p]-1)*(para_.parameterUpperbound_[p]-para_.parameterLowerbound_[p]) );
            }
            // Evaluate Loss
            opengm::learning::Weights<double>& mp =  dataset_.getWeights();
            mp = modelPara;
            std::vector< std::vector<typename INF::LabelType> > confs( dataset_.getNumberOfModels() );
            double loss = 0;
            for(size_t m=0; m<dataset_.getNumberOfModels(); ++m){
               INF inf( dataset_.getModel(m),para);
               inf.infer();
               inf.arg(confs[m]);
               const std::vector<typename INF::LabelType>& gt =  dataset_.getGT(m);
               loss += lossFunction.loss(dataset_.getModel(m),confs[m].begin(), confs[m].end(), gt.begin(), gt.end());
            }

            // **************

            if(loss<bestLoss){

                 // *call visitor*
                for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
                   std::cout << modelPara[p] <<" ";
                }
                std::cout << " ==> ";
                std::cout << loss << std::endl;

                bestLoss=loss;
                bestModelPara=modelPara;
                if(loss<=0.000000001){
                    search = false;
                }
            }
            //Increment Parameter
            for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
               if(itC[p]<para_.testingPoints_[p]-1){
                  ++itC[p];
                  break;
               }
               else{
                  itC[p]=0;
                  if (p==dataset_.getNumberOfWeights()-1)
                     search = false;
               }
            }

         }
         std::cout << "Best"<<std::endl;
         for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
            std::cout << bestModelPara[p] <<" ";
         }
         std::cout << " ==> ";
         std::cout << bestLoss << std::endl;
         weights_ = bestModelPara;

         // save best weights in dataset
         for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
            dataset_.getWeights().setWeight(p, weights_[p]);
         }
      };
   }
}
#endif
<commit_msg>fixed bug in gridesearchlearning<commit_after>#pragma once
#ifndef OPENGM_GRIDSEARCH_LEARNER_HXX
#define OPENGM_GRIDSEARCH_LEARNER_HXX

#include <vector>

namespace opengm {
   namespace learning {

      template<class DATASET>
      class GridSearchLearner
      {
      public:
         typedef DATASET DatasetType;
         typedef typename DATASET::GMType   GMType;
         typedef typename DATASET::LossType LossType;
         typedef typename GMType::ValueType ValueType;
         typedef typename GMType::IndexType IndexType;
         typedef typename GMType::LabelType LabelType;

         class Parameter{
         public:
            std::vector<double> parameterUpperbound_;
            std::vector<double> parameterLowerbound_;
            std::vector<size_t> testingPoints_;
            Parameter(){;}
         };

         GridSearchLearner(DATASET&, const Parameter& );

         template<class INF>
         void learn(const typename INF::Parameter& para);
         //template<class INF, class VISITOR>
         //void learn(typename INF::Parameter para, VITITOR vis);

         const opengm::learning::Weights<double>& getWeights(){return weights_;}
         Parameter& getLerningParameters(){return para_;}

      private:
         DATASET& dataset_;
         opengm::learning::Weights<double> weights_;
         Parameter para_;
      };

      template<class DATASET>
      GridSearchLearner<DATASET>::GridSearchLearner(DATASET& ds, const Parameter& p )
         : dataset_(ds), para_(p)
      {
         weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());
         if(para_.parameterUpperbound_.size() != ds.getNumberOfWeights())
            para_.parameterUpperbound_.resize(ds.getNumberOfWeights(),10.0);
         if(para_.parameterLowerbound_.size() != ds.getNumberOfWeights())
            para_.parameterLowerbound_.resize(ds.getNumberOfWeights(),0.0);
         if(para_.testingPoints_.size() != ds.getNumberOfWeights())
            para_.testingPoints_.resize(ds.getNumberOfWeights(),10);
      }

      template<class DATASET>
      template<class INF>
      void GridSearchLearner<DATASET>::learn(const typename INF::Parameter& para){
         // generate model Parameters
         opengm::learning::Weights<double> modelPara( dataset_.getNumberOfWeights() );
         opengm::learning::Weights<double> bestModelPara( dataset_.getNumberOfWeights() );
         double bestLoss = std::numeric_limits<double>::infinity();
         std::vector<size_t> itC(dataset_.getNumberOfWeights(),0);

         bool search=true;
         while(search){
            // Get Parameter
            for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
               modelPara.setWeight(p, para_.parameterLowerbound_[p] + double(itC[p])/double(para_.testingPoints_[p]-1)*(para_.parameterUpperbound_[p]-para_.parameterLowerbound_[p]) );
            }
            // Evaluate Loss
            opengm::learning::Weights<double>& mp =  dataset_.getWeights();
            mp = modelPara;
            const double loss = dataset_. template getTotalLoss<INF>(para);

            // **************

            if(loss<bestLoss){
                 // *call visitor*
                for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
                   std::cout << modelPara[p] <<" ";
                }
                std::cout << " ==> ";
                std::cout << loss << std::endl;

                bestLoss=loss;
                bestModelPara=modelPara;
                if(loss<=0.000000001){
                    search = false;
                }
            }
            //Increment Parameter
            for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
               if(itC[p]<para_.testingPoints_[p]-1){
                  ++itC[p];
                  break;
               }
               else{
                  itC[p]=0;
                  if (p==dataset_.getNumberOfWeights()-1)
                     search = false;
               }
            }
         }
         std::cout << "Best"<<std::endl;
         for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
            std::cout << bestModelPara[p] <<" ";
         }
         std::cout << " ==> ";
         std::cout << bestLoss << std::endl;
         weights_ = bestModelPara;

         // save best weights in dataset
         for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){
            dataset_.getWeights().setWeight(p, weights_[p]);
         }
      };
   }
}
#endif
<|endoftext|>


<commit_before>// Copyright 2014, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de)

#include <getopt.h>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <iomanip>
#include <iostream>
#include <sstream>

#include "../util/File.h"
#include "../global/Constants.h"
#include "../util/ReadableNumberFact.h"
#include "./Index.h"

using std::string;
using std::cout;
using std::endl;
using std::flush;
using std::cerr;

#define EMPH_ON  "\033[1m"
#define EMPH_OFF "\033[21m"

// Available options.
struct option options[] = {
    {"tsv-file",          required_argument, NULL, 't'},
    {"ntriples-file",     required_argument, NULL, 'n'},
    {"index-basename",    required_argument, NULL, 'i'},
    {"words-by-contexts", required_argument, NULL, 'w'},
    {"docs-by-contexts",  required_argument, NULL, 'd'},
    {"all-permutations",  no_argument,       NULL, 'a'},
    {"on-disk-literals",  no_argument,       NULL, 'l'},
    {NULL, 0,                                NULL, 0}
};

string getStxxlDiskFileName(const string& location, const string& tail) {
  std::ostringstream os;
  os << location << tail << "-stxxl.disk";
  return os.str();
}

// Write a .stxxl config-file.
// All we want is sufficient space somewhere with enough space.
// We can use the location of input files and use a constant size for now.
// The required size can only ben estimation anyway, since index size
// depends on the structure of words files rather than their size only,
// because of the "multiplications" performed.
void writeStxxlConfigFile(const string& location, const string& tail) {
  ad_utility::File stxxlConfig(".stxxl", "w");
  std::ostringstream config;
  config << "disk=" << getStxxlDiskFileName(location, tail) << ","
         << STXXL_DISK_SIZE_INDEX_BUILDER << ",syscall";
  stxxlConfig.writeLine(config.str());
}

// Main function.
int main(int argc, char** argv) {
  std::cout << std::endl << EMPH_ON
            << "IndexBuilderMain, version " << __DATE__
            << " " << __TIME__ << EMPH_OFF << std::endl << std::endl;

  char* locale = setlocale(LC_CTYPE, "en_US.utf8");
  cout << "Set locale LC_CTYPE to: " << locale << endl;

  std::locale loc;
  ad_utility::ReadableNumberFacet facet(1);
  std::locale locWithNumberGrouping(loc, &facet);
  ad_utility::Log::imbue(locWithNumberGrouping);

  string tsvFile;
  string ntFile;
  string baseName;
  string wordsfile;
  string docsfile;
  bool allPermutations = false;
  bool onDiskLiterals = false;
  optind = 1;
  // Process command line arguments.
  while (true) {
    int c = getopt_long(argc, argv, "t:n:i:w:d:al", options, NULL);
    if (c == -1) { break; }
    switch (c) {
      case 't':
        tsvFile = optarg;
        break;
      case 'n':
        ntFile = optarg;
        break;
      case 'i':
        baseName = optarg;
        break;
      case 'w':
        wordsfile = optarg;
        break;
      case 'd':
        docsfile = optarg;
        break;
      case 'a':
        allPermutations = true;
        break;
      case 'l':
        onDiskLiterals = true;
        break;
      default:
        cout << endl
             << "! ERROR in processing options (getopt returned '" << c
             << "' = 0x" << std::setbase(16) << c << ")"
             << endl << endl;
        exit(1);
    }
  }

  if (baseName.size() == 0) {
    cout << "Missing required argument --index-basename (-i)..." << endl;
    exit(1);
  }

  if (tsvFile.size() == 0 && ntFile.size() == 0 && wordsfile.size() == 0) {
    cout << "Missing required argument --tsv-file (-t) or "
        "--ntriples-file (-n) or --words-by-contexts (-w) ..." << endl;
    exit(1);
  }

  LOG(DEBUG) << "Configuring STXXL..." << std::endl;
  string stxxlFileName;
  size_t posOfLastSlash = baseName.rfind('/');
  string location = baseName.substr(0, posOfLastSlash + 1);
  string tail = baseName.substr(posOfLastSlash + 1);
  writeStxxlConfigFile(location, tail);
  stxxlFileName = getStxxlDiskFileName(location, tail);
  LOG(DEBUG) << "done." << std::endl;

  try {
    Index index;
    if (ntFile.size() > 0) {
      index.createFromNTriplesFile(ntFile, baseName, allPermutations,
                                   onDiskLiterals);
    } else if (tsvFile.size() > 0) {
      index.createFromTsvFile(tsvFile, baseName, allPermutations,
                              onDiskLiterals);
    } else {
      index.createFromOnDiskIndex(baseName, onDiskLiterals);
    }

    if (wordsfile.size() > 0) {
      index.addTextFromContextFile(wordsfile);
    }

    if (docsfile.size() > 0) {
      index.buildDocsDB(docsfile);
    }
  } catch (ad_semsearch::Exception& e) {
    LOG(ERROR) << e.getFullErrorMessage() << std::endl;
  }
  std::remove(stxxlFileName.c_str());
  return 0;
}
<commit_msg>Fixed a bug in the IndexBuilderMain when adding text to prebuild kb index<commit_after>// Copyright 2014, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de)

#include <getopt.h>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <iomanip>
#include <iostream>
#include <sstream>

#include "../util/File.h"
#include "../global/Constants.h"
#include "../util/ReadableNumberFact.h"
#include "./Index.h"

using std::string;
using std::cout;
using std::endl;
using std::flush;
using std::cerr;

#define EMPH_ON  "\033[1m"
#define EMPH_OFF "\033[21m"

// Available options.
struct option options[] = {
    {"tsv-file",          required_argument, NULL, 't'},
    {"ntriples-file",     required_argument, NULL, 'n'},
    {"index-basename",    required_argument, NULL, 'i'},
    {"words-by-contexts", required_argument, NULL, 'w'},
    {"docs-by-contexts",  required_argument, NULL, 'd'},
    {"all-permutations",  no_argument,       NULL, 'a'},
    {"on-disk-literals",  no_argument,       NULL, 'l'},
    {NULL, 0,                                NULL, 0}
};

string getStxxlDiskFileName(const string& location, const string& tail) {
  std::ostringstream os;
  os << location << tail << "-stxxl.disk";
  return os.str();
}

// Write a .stxxl config-file.
// All we want is sufficient space somewhere with enough space.
// We can use the location of input files and use a constant size for now.
// The required size can only ben estimation anyway, since index size
// depends on the structure of words files rather than their size only,
// because of the "multiplications" performed.
void writeStxxlConfigFile(const string& location, const string& tail) {
  ad_utility::File stxxlConfig(".stxxl", "w");
  std::ostringstream config;
  config << "disk=" << getStxxlDiskFileName(location, tail) << ","
         << STXXL_DISK_SIZE_INDEX_BUILDER << ",syscall";
  stxxlConfig.writeLine(config.str());
}

// Main function.
int main(int argc, char** argv) {
  std::cout << std::endl << EMPH_ON
            << "IndexBuilderMain, version " << __DATE__
            << " " << __TIME__ << EMPH_OFF << std::endl << std::endl;

  char* locale = setlocale(LC_CTYPE, "en_US.utf8");
  cout << "Set locale LC_CTYPE to: " << locale << endl;

  std::locale loc;
  ad_utility::ReadableNumberFacet facet(1);
  std::locale locWithNumberGrouping(loc, &facet);
  ad_utility::Log::imbue(locWithNumberGrouping);

  string tsvFile;
  string ntFile;
  string baseName;
  string wordsfile;
  string docsfile;
  bool allPermutations = false;
  bool onDiskLiterals = false;
  optind = 1;
  // Process command line arguments.
  while (true) {
    int c = getopt_long(argc, argv, "t:n:i:w:d:al", options, NULL);
    if (c == -1) { break; }
    switch (c) {
      case 't':
        tsvFile = optarg;
        break;
      case 'n':
        ntFile = optarg;
        break;
      case 'i':
        baseName = optarg;
        break;
      case 'w':
        wordsfile = optarg;
        break;
      case 'd':
        docsfile = optarg;
        break;
      case 'a':
        allPermutations = true;
        break;
      case 'l':
        onDiskLiterals = true;
        break;
      default:
        cout << endl
             << "! ERROR in processing options (getopt returned '" << c
             << "' = 0x" << std::setbase(16) << c << ")"
             << endl << endl;
        exit(1);
    }
  }

  if (baseName.size() == 0) {
    cout << "Missing required argument --index-basename (-i)..." << endl;
    exit(1);
  }

  if (tsvFile.size() == 0 && ntFile.size() == 0 && wordsfile.size() == 0) {
    cout << "Missing required argument --tsv-file (-t) or "
        "--ntriples-file (-n) or --words-by-contexts (-w) ..." << endl;
    exit(1);
  }

  LOG(DEBUG) << "Configuring STXXL..." << std::endl;
  string stxxlFileName;
  size_t posOfLastSlash = baseName.rfind('/');
  string location = baseName.substr(0, posOfLastSlash + 1);
  string tail = baseName.substr(posOfLastSlash + 1);
  writeStxxlConfigFile(location, tail);
  stxxlFileName = getStxxlDiskFileName(location, tail);
  LOG(DEBUG) << "done." << std::endl;

  try {
    Index index;
    if (ntFile.size() > 0) {
      index.createFromNTriplesFile(ntFile, baseName, allPermutations,
                                   onDiskLiterals);
    } else if (tsvFile.size() > 0) {
      index.createFromTsvFile(tsvFile, baseName, allPermutations,
                              onDiskLiterals);
    } else {
      index.createFromOnDiskIndex(baseName, allPermutations, onDiskLiterals);
    }

    if (wordsfile.size() > 0) {
      index.addTextFromContextFile(wordsfile);
    }

    if (docsfile.size() > 0) {
      index.buildDocsDB(docsfile);
    }
  } catch (ad_semsearch::Exception& e) {
    LOG(ERROR) << e.getFullErrorMessage() << std::endl;
  }
  std::remove(stxxlFileName.c_str());
  return 0;
}
<|endoftext|>


<commit_before>#ifndef TWISTEDCPP_BASIC_PROTOCOL
#define TWISTEDCPP_BASIC_PROTOCOL

namespace twisted {

template<typename ChildProtocol>
class basic_protocol : public std::enable_shared_from_this<ChildProtocol> {
public:
    typedef boost::asio::ip::tcp::socket socket_type;
    typedef boost::asio::steady_timer timer_type;
    typedef boost::asio::io_service::strand strand_type;
    typedef std::vector<char> buffer_type;
    typedef buffer_type::iterator buffer_iterator;
    typedef buffer_type::const_iterator const_buffer_iterator;

    basic_protocol()
        : _read_buffer(1024),
            _read_index(_read_buffer.begin()) {}

    void set_socket(socket_type socket) {
        _socket.reset(new socket_type(std::move(socket)));
        _strand = boost::in_place(boost::ref(_socket->get_io_service()));
        _timer =  boost::in_place(boost::ref(_socket->get_io_service()));
    }

    void run_protocol() {
        auto self = this_protocol().shared_from_this();
        boost::asio::spawn(*_strand, [this, self] (boost::asio::yield_context yield) {
            _yield = boost::in_place(yield);

            try {
                for(;_socket->is_open();) {
                    expand_buffer();
                    auto bytes_read = _socket->async_read_some(read_buffer(), yield);
                    checked_on_message(_read_index, std::next(_read_index, bytes_read));
                }
            } catch(boost::system::system_error& connection_error) { // network errors
                print_connection_error(connection_error);
                this_protocol().on_disconnect();
            } catch(const std::exception& excep) { // errors from user protocols
                print_exception_what(excep);
            }
        });
    }

    boost::asio::mutable_buffers_1 read_buffer() {
        return boost::asio::buffer(&*_read_index, std::distance(_read_index, _read_buffer.end()));
    }

    template<typename Iter>
    void send_message(Iter begin, Iter end) {
        boost::asio::async_write(
            *_socket,
            boost::asio::buffer(&*begin, std::distance(begin, end)),
            *_yield);
    }

    template<typename BuffersType>
    void send_buffers(const BuffersType& buffers) {
        boost::asio::async_write(
            *_socket,
            buffers,
            *_yield);
    }

    void on_disconnect() {}

    void on_error(std::exception_ptr eptr) {
        std::rethrow_exception(eptr);
    }

    void lose_connection() {
        _socket->close();
        std::cout << "Closing connection to client" << std::endl;
    }

private:
    void print_connection_error(const boost::system::system_error& connection_error) const {
        std::cerr << "Client disconnected with code "
                  << connection_error.what()
                  << std::endl;
    }

    void print_exception_what(const std::exception& excep) {
        std::cerr << "Killing connection, exception in client handler: "
                  << excep.what()
                  << std::endl;
    }

    void expand_buffer() {
        auto range = std::distance(_read_buffer.begin(), _read_index);
        if(range < 1024) {
            _read_buffer.resize(_read_buffer.size() * 2);
            _read_index = std::next(_read_buffer.begin(), range);
        }
    }

    template<typename Iter>
    void checked_on_message(Iter begin, Iter end) {
        try {
            this_protocol().on_message(begin, end);
        } catch (...) {
            this_protocol().on_error(std::current_exception());
        }
    }

protected:
    /*
     * @brief CRTP wrapper for derived class access
     */
    ChildProtocol& this_protocol() {
        return *static_cast<ChildProtocol*>(this);
    }

    /*
     * @brief CRTP wrapper for derived class access
     */
    const ChildProtocol& this_protocol() const {
        return *static_cast<ChildProtocol*>(this);
    }

    buffer_type _read_buffer;
    buffer_iterator _read_index;
private:
    boost::optional<boost::asio::yield_context> _yield;
    std::unique_ptr<socket_type> _socket; // unique_ptr as boost::optional has no move support
    boost::optional<timer_type> _timer;
    boost::optional<strand_type> _strand;
};

}

#endif
<commit_msg>added missing includes to basic_protocol<commit_after>#ifndef TWISTEDCPP_BASIC_PROTOCOL
#define TWISTEDCPP_BASIC_PROTOCOL

#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/optional.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/write.hpp>

namespace twisted {

template<typename ChildProtocol>
class basic_protocol : public std::enable_shared_from_this<ChildProtocol> {
public:
    typedef boost::asio::ip::tcp::socket socket_type;
    typedef boost::asio::steady_timer timer_type;
    typedef boost::asio::io_service::strand strand_type;
    typedef std::vector<char> buffer_type;
    typedef buffer_type::iterator buffer_iterator;
    typedef buffer_type::const_iterator const_buffer_iterator;

    basic_protocol()
        : _read_buffer(1024),
            _read_index(_read_buffer.begin()) {}

    void set_socket(socket_type socket) {
        _socket.reset(new socket_type(std::move(socket)));
        _strand = boost::in_place(boost::ref(_socket->get_io_service()));
        _timer =  boost::in_place(boost::ref(_socket->get_io_service()));
    }

    void run_protocol() {
        auto self = this_protocol().shared_from_this();
        boost::asio::spawn(*_strand, [this, self] (boost::asio::yield_context yield) {
            _yield = boost::in_place(yield);

            try {
                for(;_socket->is_open();) {
                    expand_buffer();
                    auto bytes_read = _socket->async_read_some(read_buffer(), yield);
                    checked_on_message(_read_index, std::next(_read_index, bytes_read));
                }
            } catch(boost::system::system_error& connection_error) { // network errors
                print_connection_error(connection_error);
                this_protocol().on_disconnect();
            } catch(const std::exception& excep) { // errors from user protocols
                print_exception_what(excep);
            }
        });
    }

    boost::asio::mutable_buffers_1 read_buffer() {
        return boost::asio::buffer(&*_read_index, std::distance(_read_index, _read_buffer.end()));
    }

    template<typename Iter>
    void send_message(Iter begin, Iter end) {
        boost::asio::async_write(
            *_socket,
            boost::asio::buffer(&*begin, std::distance(begin, end)),
            *_yield);
    }

    template<typename BuffersType>
    void send_buffers(const BuffersType& buffers) {
        boost::asio::async_write(
            *_socket,
            buffers,
            *_yield);
    }

    void on_disconnect() {}

    void on_error(std::exception_ptr eptr) {
        std::rethrow_exception(eptr);
    }

    void lose_connection() {
        _socket->close();
        std::cout << "Closing connection to client" << std::endl;
    }

private:
    void print_connection_error(const boost::system::system_error& connection_error) const {
        std::cerr << "Client disconnected with code "
                  << connection_error.what()
                  << std::endl;
    }

    void print_exception_what(const std::exception& excep) {
        std::cerr << "Killing connection, exception in client handler: "
                  << excep.what()
                  << std::endl;
    }

    void expand_buffer() {
        auto range = std::distance(_read_buffer.begin(), _read_index);
        if(range < 1024) {
            _read_buffer.resize(_read_buffer.size() * 2);
            _read_index = std::next(_read_buffer.begin(), range);
        }
    }

    template<typename Iter>
    void checked_on_message(Iter begin, Iter end) {
        try {
            this_protocol().on_message(begin, end);
        } catch (...) {
            this_protocol().on_error(std::current_exception());
        }
    }

protected:
    /*
     * @brief CRTP wrapper for derived class access
     */
    ChildProtocol& this_protocol() {
        return *static_cast<ChildProtocol*>(this);
    }

    /*
     * @brief CRTP wrapper for derived class access
     */
    const ChildProtocol& this_protocol() const {
        return *static_cast<ChildProtocol*>(this);
    }

    buffer_type _read_buffer;
    buffer_iterator _read_index;
private:
    boost::optional<boost::asio::yield_context> _yield;
    std::unique_ptr<socket_type> _socket; // unique_ptr as boost::optional has no move support
    boost::optional<timer_type> _timer;
    boost::optional<strand_type> _strand;
};

}

#endif
<|endoftext|>


<commit_before>/****************************************************************************
 *		directlight.cc: an integrator for direct lighting only
 *		This is part of the yafaray package
 *		Copyright (C) 2006  Mathias Wein (Lynx)
 *		Copyright (C) 2009  Rodrigo Placencia (DarkTide)
 *
 *		This library is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU Lesser General Public
 *      License as published by the Free Software Foundation; either
 *      version 2.1 of the License, or (at your option) any later version.
 *
 *      This library is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *      Lesser General Public License for more details.
 *
 *      You should have received a copy of the GNU Lesser General Public
 *      License along with this library; if not, write to the Free Software
 *      Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <yafray_config.h>
#include <core_api/environment.h>
#include <core_api/material.h>
#include <core_api/mcintegrator.h>
#include <core_api/background.h>
#include <core_api/light.h>
#include <sstream>

__BEGIN_YAFRAY

class YAFRAYPLUGIN_EXPORT directLighting_t: public mcIntegrator_t
{
	public:
		directLighting_t(bool transpShad=false, int shadowDepth=4, int rayDepth=6);
		virtual bool preprocess();
		virtual colorA_t integrate(renderState_t &state, diffRay_t &ray) const;
		static integrator_t* factory(paraMap_t &params, renderEnvironment_t &render);
};

directLighting_t::directLighting_t(bool transpShad, int shadowDepth, int rayDepth)
{
	type = SURFACE;
	causRadius = 0.25;
	causDepth = 10;
	nCausPhotons = 100000;
	nCausSearch = 100;
	trShad = transpShad;
	usePhotonCaustics = false;
	sDepth = shadowDepth;
	rDepth = rayDepth;
	intpb = 0;
	integratorName = "DirectLight";
	integratorShortName = "DL";
}

bool directLighting_t::preprocess()
{
	bool success = true;
	std::stringstream set;
	settings = "";

	if(trShad)
	{
		set << "ShadowDepth: [" << sDepth << "]";
	}
	if(!set.str().empty()) set << "+";
	set << "RayDepth: [" << rDepth << "]";

	background = scene->getBackground();
	lights = scene->lights;

	if(usePhotonCaustics)
	{
		success = createCausticMap();
		if(!set.str().empty()) set << "+";
		set << "Caustics:" << nCausPhotons << " photons. ";
	}

	if(useAmbientOcclusion)
	{
		if(!set.str().empty()) set << "+";
		set << "AO";
	}

	settings = set.str();

	return success;
}

colorA_t directLighting_t::integrate(renderState_t &state, diffRay_t &ray) const
{
	color_t col(0.0);
	float alpha = 0.0;
	surfacePoint_t sp;
	void *o_udat = state.userdata;
	bool oldIncludeLights = state.includeLights;

	// Shoot ray into scene

	if(scene->intersect(ray, sp)) // If it hits
	{
		unsigned char userdata[USER_DATA_SIZE];
		const material_t *material = sp.material;
		BSDF_t bsdfs;

		state.userdata = (void *) userdata;
		vector3d_t wo = -ray.dir;
		if(state.raylevel == 0) state.includeLights = true;

		material->initBSDF(state, sp, bsdfs);

		if(bsdfs & BSDF_EMIT) col += material->emit(state, sp, wo);

		if(bsdfs & BSDF_DIFFUSE)
		{
			col += estimateAllDirectLight(state, sp, wo);
			col += estimateCausticPhotons(state, sp, wo);
			if(useAmbientOcclusion) col += sampleAmbientOcclusion(state, sp, wo);
		}

		recursiveRaytrace(state, ray, bsdfs, sp, wo, col, alpha);

		float m_alpha = material->getAlpha(state, sp, wo);
		alpha = m_alpha + (1.f - m_alpha) * alpha;
	}
	else // Nothing hit, return background if any
	{
		if(background) col += (*background)(ray, state, false);
	}

	state.userdata = o_udat;
	state.includeLights = oldIncludeLights;
	return colorA_t(col, alpha);
}

integrator_t* directLighting_t::factory(paraMap_t &params, renderEnvironment_t &render)
{
	bool transpShad=false;
	bool caustics=false;
	bool do_AO=false;
	int shadowDepth=5;
	int raydepth=5, cDepth=10;
	int search=100, photons=500000;
	int AO_samples = 32;
	double cRad = 0.25;
	double AO_dist = 1.0;
	color_t AO_col(1.f);

	params.getParam("raydepth", raydepth);
	params.getParam("transpShad", transpShad);
	params.getParam("shadowDepth", shadowDepth);
	params.getParam("caustics", caustics);
	params.getParam("photons", photons);
	params.getParam("caustic_mix", search);
	params.getParam("caustic_depth", cDepth);
	params.getParam("caustic_radius", cRad);
	params.getParam("do_AO", do_AO);
	params.getParam("AO_samples", AO_samples);
	params.getParam("AO_distance", AO_dist);
	params.getParam("AO_color", AO_col);

	directLighting_t *inte = new directLighting_t(transpShad, shadowDepth, raydepth);
	// caustic settings
	inte->usePhotonCaustics = caustics;
	inte->nCausPhotons = photons;
	inte->nCausSearch = search;
	inte->causDepth = cDepth;
	inte->causRadius = cRad;
	// AO settings
	inte->useAmbientOcclusion = do_AO;
	inte->aoSamples = AO_samples;
	inte->aoDist = (PFLOAT)AO_dist;
	inte->aoCol = AO_col;
	return inte;
}

extern "C"
{

	YAFRAYPLUGIN_EXPORT void registerPlugin(renderEnvironment_t &render)
	{
		render.registerFactory("directlighting",directLighting_t::factory);
	}

}

__END_YAFRAY
<commit_msg>- DirectLight: Removed useless cast<commit_after>/****************************************************************************
 *		directlight.cc: an integrator for direct lighting only
 *		This is part of the yafaray package
 *		Copyright (C) 2006  Mathias Wein (Lynx)
 *		Copyright (C) 2009  Rodrigo Placencia (DarkTide)
 *
 *		This library is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU Lesser General Public
 *      License as published by the Free Software Foundation; either
 *      version 2.1 of the License, or (at your option) any later version.
 *
 *      This library is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *      Lesser General Public License for more details.
 *
 *      You should have received a copy of the GNU Lesser General Public
 *      License along with this library; if not, write to the Free Software
 *      Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <yafray_config.h>
#include <core_api/environment.h>
#include <core_api/material.h>
#include <core_api/mcintegrator.h>
#include <core_api/background.h>
#include <core_api/light.h>
#include <sstream>

__BEGIN_YAFRAY

class YAFRAYPLUGIN_EXPORT directLighting_t: public mcIntegrator_t
{
	public:
		directLighting_t(bool transpShad=false, int shadowDepth=4, int rayDepth=6);
		virtual bool preprocess();
		virtual colorA_t integrate(renderState_t &state, diffRay_t &ray) const;
		static integrator_t* factory(paraMap_t &params, renderEnvironment_t &render);
};

directLighting_t::directLighting_t(bool transpShad, int shadowDepth, int rayDepth)
{
	type = SURFACE;
	causRadius = 0.25;
	causDepth = 10;
	nCausPhotons = 100000;
	nCausSearch = 100;
	trShad = transpShad;
	usePhotonCaustics = false;
	sDepth = shadowDepth;
	rDepth = rayDepth;
	intpb = 0;
	integratorName = "DirectLight";
	integratorShortName = "DL";
}

bool directLighting_t::preprocess()
{
	bool success = true;
	std::stringstream set;
	settings = "";

	if(trShad)
	{
		set << "ShadowDepth: [" << sDepth << "]";
	}
	if(!set.str().empty()) set << "+";
	set << "RayDepth: [" << rDepth << "]";

	background = scene->getBackground();
	lights = scene->lights;

	if(usePhotonCaustics)
	{
		success = createCausticMap();
		if(!set.str().empty()) set << "+";
		set << "Caustics:" << nCausPhotons << " photons. ";
	}

	if(useAmbientOcclusion)
	{
		if(!set.str().empty()) set << "+";
		set << "AO";
	}

	settings = set.str();

	return success;
}

colorA_t directLighting_t::integrate(renderState_t &state, diffRay_t &ray) const
{
	color_t col(0.0);
	float alpha = 0.0;
	surfacePoint_t sp;
	void *o_udat = state.userdata;
	bool oldIncludeLights = state.includeLights;

	// Shoot ray into scene

	if(scene->intersect(ray, sp)) // If it hits
	{
		unsigned char userdata[USER_DATA_SIZE];
		const material_t *material = sp.material;
		BSDF_t bsdfs;

		state.userdata = (void *) userdata;
		vector3d_t wo = -ray.dir;
		if(state.raylevel == 0) state.includeLights = true;

		material->initBSDF(state, sp, bsdfs);

		if(bsdfs & BSDF_EMIT) col += material->emit(state, sp, wo);

		if(bsdfs & BSDF_DIFFUSE)
		{
			col += estimateAllDirectLight(state, sp, wo);
			col += estimateCausticPhotons(state, sp, wo);
			if(useAmbientOcclusion) col += sampleAmbientOcclusion(state, sp, wo);
		}

		recursiveRaytrace(state, ray, bsdfs, sp, wo, col, alpha);

		float m_alpha = material->getAlpha(state, sp, wo);
		alpha = m_alpha + (1.f - m_alpha) * alpha;
	}
	else // Nothing hit, return background if any
	{
		if(background) col += (*background)(ray, state, false);
	}

	state.userdata = o_udat;
	state.includeLights = oldIncludeLights;
	return colorA_t(col, alpha);
}

integrator_t* directLighting_t::factory(paraMap_t &params, renderEnvironment_t &render)
{
	bool transpShad=false;
	bool caustics=false;
	bool do_AO=false;
	int shadowDepth=5;
	int raydepth=5, cDepth=10;
	int search=100, photons=500000;
	int AO_samples = 32;
	double cRad = 0.25;
	double AO_dist = 1.0;
	color_t AO_col(1.f);

	params.getParam("raydepth", raydepth);
	params.getParam("transpShad", transpShad);
	params.getParam("shadowDepth", shadowDepth);
	params.getParam("caustics", caustics);
	params.getParam("photons", photons);
	params.getParam("caustic_mix", search);
	params.getParam("caustic_depth", cDepth);
	params.getParam("caustic_radius", cRad);
	params.getParam("do_AO", do_AO);
	params.getParam("AO_samples", AO_samples);
	params.getParam("AO_distance", AO_dist);
	params.getParam("AO_color", AO_col);

	directLighting_t *inte = new directLighting_t(transpShad, shadowDepth, raydepth);
	// caustic settings
	inte->usePhotonCaustics = caustics;
	inte->nCausPhotons = photons;
	inte->nCausSearch = search;
	inte->causDepth = cDepth;
	inte->causRadius = cRad;
	// AO settings
	inte->useAmbientOcclusion = do_AO;
	inte->aoSamples = AO_samples;
	inte->aoDist = AO_dist;
	inte->aoCol = AO_col;
	return inte;
}

extern "C"
{

	YAFRAYPLUGIN_EXPORT void registerPlugin(renderEnvironment_t &render)
	{
		render.registerFactory("directlighting",directLighting_t::factory);
	}

}

__END_YAFRAY
<|endoftext|>


<commit_before>/*
 * BaseConnectionProbe.hpp
 *
 *  Created on: Oct 20, 2011
 *      Author: pschultz
 */

#ifndef BASECONNECTIONPROBE_HPP_
#define BASECONNECTIONPROBE_HPP_

#include "../connections/HyPerConn.hpp"

enum PatchIDMethod { INDEX_METHOD, COORDINATE_METHOD };

namespace PV {

class BaseConnectionProbe {

// Methods
public:
   virtual ~BaseConnectionProbe();
   virtual int outputState(double timef) = 0;
   const char * getName()               {return name;}
   const char * getFilename()           {return filename;}
   FILE * getFilePtr()                  {return fp;}
   HyPerConn * getTargetConn()          {return targetConn;}

protected:
   BaseConnectionProbe(); // Default constructor, can only be called by derived classes
   int initialize(const char * probename, const char * filename, HyPerConn * conn);
   int initialize(const char * probename, const char * filename, HyPerConn * conn, int k, bool postProbeFlag);
   int initialize(const char * probename, const char * filename, HyPerConn * conn, int kx, int ky, int kf, bool postProbeFlag);

private:
   int initialize_base();

// Member variables
private:
   char * name; // Name of the probe; corresponds to the group name in the params file
   char * filename; // Name of the output file.  Can be NULL if output goes to stdout
   FILE * fp; // pointer to output file; NULL except for root process.  If filename is NULL, fp will be stdout.
   HyPerConn * targetConn;
   bool isPostProbe;

}; // end of class BaseConnectionProbe block

}  // end of namespace PV block

#endif /* BASECONNECTIONPROBE_HPP_ */
<commit_msg>Changing member variables in BaseConnectionProbe from private to protected, to make it easier for write subclasses.<commit_after>/*
 * BaseConnectionProbe.hpp
 *
 *  Created on: Oct 20, 2011
 *      Author: pschultz
 */

#ifndef BASECONNECTIONPROBE_HPP_
#define BASECONNECTIONPROBE_HPP_

#include "../connections/HyPerConn.hpp"

enum PatchIDMethod { INDEX_METHOD, COORDINATE_METHOD };

namespace PV {

class BaseConnectionProbe {

// Methods
public:
   virtual ~BaseConnectionProbe();
   virtual int outputState(double timef) = 0;
   const char * getName()               {return name;}
   const char * getFilename()           {return filename;}
   FILE * getFilePtr()                  {return fp;}
   HyPerConn * getTargetConn()          {return targetConn;}

protected:
   BaseConnectionProbe(); // Default constructor, can only be called by derived classes
   int initialize(const char * probename, const char * filename, HyPerConn * conn);
   int initialize(const char * probename, const char * filename, HyPerConn * conn, int k, bool postProbeFlag);
   int initialize(const char * probename, const char * filename, HyPerConn * conn, int kx, int ky, int kf, bool postProbeFlag);

private:
   int initialize_base();

// Member variables
protected:
   char * name; // Name of the probe; corresponds to the group name in the params file
   char * filename; // Name of the output file.  Can be NULL if output goes to stdout
   FILE * fp; // pointer to output file; NULL except for root process.  If filename is NULL, fp will be stdout.
   HyPerConn * targetConn;
   bool isPostProbe;

}; // end of class BaseConnectionProbe block

}  // end of namespace PV block

#endif /* BASECONNECTIONPROBE_HPP_ */
<|endoftext|>


<commit_before><commit_msg>FOGL-1552 Fix escaping in where clause<commit_after><|endoftext|>