<commit_before>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include "cctag/utils/FileDebug.hpp"
#include "cctag/utils/VisualDebug.hpp"
#include "cctag/utils/Exceptions.hpp"
#include "cctag/Detection.hpp"
#include "CmdLine.hpp"

#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

#define PRINT_TO_CERR

using namespace cctag;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

// static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ostream & output, std::string debugFileName = "")
{

  //cv::medianBlur(src, src, 5);

    if (debugFileName == "") {
      debugFileName = "00000";
    }

    // Process markers detection
    boost::timer t;
    boost::ptr_list<CCTag> markers;

    CCTagVisualDebug::instance().initBackgroundImage(src);
    CCTagVisualDebug::instance().setImageFileName(debugFileName);
    CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());

    static cctag::logtime::Mgmt* durations = 0;
#if 0
    if( not durations ) {
        durations = new cctag::logtime::Mgmt( 25 );
    } else {
        durations->resetStartTime();
    }
#endif
    cctagDetection( markers, frameId , src, params, bank, true, durations );

    if( durations ) {
        durations->print( std::cerr );
    }

    CCTagFileDebug::instance().outPutAllSessions();
    CCTagFileDebug::instance().clearSessions();
    CCTagVisualDebug::instance().outPutAllSessions();
    CCTagVisualDebug::instance().clearSessions();

    CCTAG_COUT( markers.size() << " markers.");
    std::cout << "Total time: " << t.elapsed() << std::endl;
    CCTAG_COUT_NOENDL("Id : ");

    int i = 0;
    output << "#frame " << frameId << '\n';
    output << markers.size() << '\n';
    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
      output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
      if (i == 0) {
          CCTAG_COUT_NOENDL(marker.id() + 1);
      } else {
          CCTAG_COUT_NOENDL(", " << marker.id() + 1);
      }
      ++i;
    }
    CCTAG_COUT("");
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
  CmdLine cmdline;

  if( cmdline.parse( argc, argv ) == false ) {
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

  cmdline.print( argv[0] );

  // Check input path
  if( cmdline._filename.compare("") != 0){
    if (!boost::filesystem::exists( cmdline._filename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._filename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }
  }else{
    std::cerr << std::endl
        << "An input file is required" << std::endl;
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

#ifdef WITH_CUDA
  popart::pop_cuda_only_sync_calls( cmdline._switchSync );
#endif

  // Check the (optional) parameters path
  std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
  cctag::Parameters params(nCrowns);

  if( cmdline._paramsFilename != "" ) {
    if (!boost::filesystem::exists( cmdline._paramsFilename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }

    // Read the parameter file provided by the user
    std::ifstream ifs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_iarchive ia(ifs);
    ia >> boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT(params._nCrowns);
    CCTAG_COUT(nCrowns);
    assert( nCrowns == params._nCrowns );
  } else {
    // Use the default parameters and save them in defaultParameters.xml
    cmdline._paramsFilename = "defaultParameters.xml";
    std::ofstream ofs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_oarchive oa(ofs);
    oa << boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT("Parameter file not provided. Default parameters are used.");
  }

  CCTagMarkersBank bank(params._nCrowns);
  if ( !cmdline._cctagBankFilename.empty())
  {
    bank = CCTagMarkersBank(cmdline._cctagBankFilename);
  }

#ifdef WITH_CUDA
  if( cmdline._useCuda ) {
    params.setUseCuda( true );
  } else {
    params.setUseCuda( false );
  }

  if( cmdline._debugDir != "" ) {
    params.setDebugDir( cmdline._debugDir );
  }

  popart::device_prop_t deviceInfo( false );
#if 0
  deviceInfo.print( );
#endif
#endif // WITH_CUDA

  bfs::path myPath( cmdline._filename );
  std::string ext(myPath.extension().string());

  const bfs::path subFilenamePath(myPath.filename());
  const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path());
  std::string outputFileName;
  if (!bfs::is_directory(myPath))
  {
    CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }else
  {
    CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }
  std::ofstream outputFile;
  outputFile.open( outputFileName );

  if ( (ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG")) {

    std::cout << "******************* Image mode **********************" << std::endl;

    POP_INFO("looking at image " << myPath.string());

    // Gray scale convertion
    cv::Mat src = cv::imread(cmdline._filename);
    cv::Mat graySrc;
    cv::cvtColor( src, graySrc, CV_BGR2GRAY );

    // Upscale original image
    /*{
            rgb8_image_t simage;
            simage.recreate( 2 * image.width(), 2 * image.height() );
            rgb8_view_t osvw( view( simage ) );
            terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
    }*/

    // Call the CCTag detection
#ifdef PRINT_TO_CERR
    detection(0, graySrc, params, bank, std::cerr, myPath.stem().string());
#else
    detection(0, graySrc, params, bank, outputFile, myPath.stem().string());
#endif
} else if (ext == ".avi" )
  {
    CCTAG_COUT("*** Video mode ***");
    POP_INFO( "looking at video " << myPath.string() );

    // open video and check
    cv::VideoCapture video( cmdline._filename.c_str() );
    if(!video.isOpened())
    {
      CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1;
    }

    // play loop
    int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);

    std::list<cv::Mat*> frames;

    std::cerr << "Starting to read video frames" << std::endl;
    while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
    {
      cv::Mat frame;
      video >> frame;
      cv::Mat* imgGray = new cv::Mat;

      if( frame.channels() == 3 || frame.channels() == 4 )
        cv::cvtColor(frame, *imgGray, cv::COLOR_BGR2GRAY);
      else
        frame.copyTo(*imgGray);

      frames.push_back( imgGray );
    }
    std::cerr << "Done. Now processing." << std::endl;

    boost::timer t;
    std::size_t         frameId = 0;
#if 0
    boost::mutex        frame_mutex;
    boost::thread_group frame_processor;
    for( int proc=0; proc<1 ; proc++ ) {
      frame_processor.create_thread(
        [&frames, &frameId, &frame_mutex, &t, params, bank, &outputFile](){
            bool   empty;
            do {
                cv::Mat* imgGray;
                frame_mutex.lock();
                empty = frames.empty();
                if( not empty ) {
                    imgGray = frames.front();
                    frames.pop_front();
                    ++frameId;
                }
                frame_mutex.unlock();

                std::stringstream outFileName;
                outFileName << std::setfill('0') << std::setw(5) << frameId;

                detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
                if( frameId % 100 == 0 ) {
                    std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
                }
                delete imgGray;
            } while( not empty );
        } );
    }
    frame_processor.join_all();
#else
    for( cv::Mat* imgGray : frames ) {
        // Set the output folder
        std::stringstream outFileName;
        outFileName << std::setfill('0') << std::setw(5) << frameId;

        // Invert the image for the projection scenario
        //cv::Mat imgGrayInverted;
        //bitwise_not ( imgGray, imgGrayInverted );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, *imgGray, params, bank, std::cerr, outFileName.str());
#else
        detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
#endif
        ++frameId;
        if( frameId % 100 == 0 ) {
            std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
        }
    }
#endif
    std::cerr << std::endl;
  } else if (bfs::is_directory(myPath)) {
    CCTAG_COUT("*** Image sequence mode ***");

    std::vector<bfs::path> vFileInFolder;

    std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
    std::sort(vFileInFolder.begin(), vFileInFolder.end());

    std::size_t frameId = 0;

    for(const auto & fileInFolder : vFileInFolder) {
      const std::string subExt(bfs::extension(fileInFolder));

      if ( (subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG") ) {

        CCTAG_COUT( "Processing image " << fileInFolder.string() );

		cv::Mat src;
    	src = cv::imread(fileInFolder.string());

        cv::Mat imgGray;
        cv::cvtColor( src, imgGray, CV_BGR2GRAY );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, imgGray, params, bank, std::cerr, fileInFolder.stem().string());
#else
        detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string());
#endif
++frameId;
      }
    }
  }else
  {
      throw std::logic_error("Unrecognized input.");
  }
  outputFile.close();
  return 0;
}

<commit_msg>[application] Clean detection app.<commit_after>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include "cctag/utils/FileDebug.hpp"
#include "cctag/utils/VisualDebug.hpp"
#include "cctag/utils/Exceptions.hpp"
#include "cctag/Detection.hpp"
#include "CmdLine.hpp"

#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

#define PRINT_TO_CERR

using namespace cctag;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ostream & output, std::string debugFileName = "")
{

    if (debugFileName == "") {
      debugFileName = "00000";
    }

    // Process markers detection
    boost::timer t;
    boost::ptr_list<CCTag> markers;

    CCTagVisualDebug::instance().initBackgroundImage(src);
    CCTagVisualDebug::instance().setImageFileName(debugFileName);
    CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());

    static cctag::logtime::Mgmt* durations = 0;

    //Call the main CCTag detection function
    cctagDetection( markers, frameId , src, params, bank, true, durations );

    if( durations ) {
        durations->print( std::cerr );
    }

    CCTagFileDebug::instance().outPutAllSessions();
    CCTagFileDebug::instance().clearSessions();
    CCTagVisualDebug::instance().outPutAllSessions();
    CCTagVisualDebug::instance().clearSessions();

    CCTAG_COUT( markers.size() << " markers.");
    std::cout << "Total time: " << t.elapsed() << std::endl;
    CCTAG_COUT_NOENDL("Id : ");

    int i = 0;
    output << "#frame " << frameId << '\n';
    output << markers.size() << '\n';
    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
      output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
      if (i == 0) {
          CCTAG_COUT_NOENDL(marker.id() + 1);
      } else {
          CCTAG_COUT_NOENDL(", " << marker.id() + 1);
      }
      ++i;
    }
    CCTAG_COUT("");
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
  CmdLine cmdline;

  if( cmdline.parse( argc, argv ) == false ) {
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

  cmdline.print( argv[0] );

  // Check input path
  if( cmdline._filename.compare("") != 0){
    if (!boost::filesystem::exists( cmdline._filename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._filename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }
  }else{
    std::cerr << std::endl
        << "An input file is required" << std::endl;
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

#ifdef WITH_CUDA
  popart::pop_cuda_only_sync_calls( cmdline._switchSync );
#endif

  // Check the (optional) parameters path
  std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
  cctag::Parameters params(nCrowns);

  if( cmdline._paramsFilename != "" ) {
    if (!boost::filesystem::exists( cmdline._paramsFilename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }

    // Read the parameter file provided by the user
    std::ifstream ifs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_iarchive ia(ifs);
    ia >> boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT(params._nCrowns);
    CCTAG_COUT(nCrowns);
    assert( nCrowns == params._nCrowns );
  } else {
    // Use the default parameters and save them in defaultParameters.xml
    cmdline._paramsFilename = "defaultParameters.xml";
    std::ofstream ofs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_oarchive oa(ofs);
    oa << boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT("Parameter file not provided. Default parameters are used.");
  }

  CCTagMarkersBank bank(params._nCrowns);
  if ( !cmdline._cctagBankFilename.empty())
  {
    bank = CCTagMarkersBank(cmdline._cctagBankFilename);
  }

#ifdef WITH_CUDA
  if( cmdline._useCuda ) {
    params.setUseCuda( true );
  } else {
    params.setUseCuda( false );
  }

  if( cmdline._debugDir != "" ) {
    params.setDebugDir( cmdline._debugDir );
  }

  popart::device_prop_t deviceInfo( false );
#endif // WITH_CUDA

  bfs::path myPath( cmdline._filename );
  std::string ext(myPath.extension().string());

  const bfs::path subFilenamePath(myPath.filename());
  const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path());
  std::string outputFileName;
  if (!bfs::is_directory(myPath))
  {
    CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }else
  {
    CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }
  std::ofstream outputFile;
  outputFile.open( outputFileName );

  if ( (ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG")) {

    std::cout << "******************* Image mode **********************" << std::endl;

    POP_INFO("looking at image " << myPath.string());

    // Gray scale convertion
    cv::Mat src = cv::imread(cmdline._filename);
    cv::Mat graySrc;
    cv::cvtColor( src, graySrc, CV_BGR2GRAY );

#ifdef PRINT_TO_CERR
    detection(0, graySrc, params, bank, std::cerr, myPath.stem().string());
#else
    detection(0, graySrc, params, bank, outputFile, myPath.stem().string());
#endif
} else if (ext == ".avi" )
  {
    CCTAG_COUT("*** Video mode ***");
    POP_INFO( "looking at video " << myPath.string() );

    // open video and check
    cv::VideoCapture video( cmdline._filename.c_str() );
    if(!video.isOpened())
    {
      CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1;
    }

    // play loop
    int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);

    std::list<cv::Mat*> frames;

    std::cerr << "Starting to read video frames" << std::endl;
    while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
    {
      cv::Mat frame;
      video >> frame;
      cv::Mat* imgGray = new cv::Mat;

      if( frame.channels() == 3 || frame.channels() == 4 )
        cv::cvtColor(frame, *imgGray, cv::COLOR_BGR2GRAY);
      else
        frame.copyTo(*imgGray);

      frames.push_back( imgGray );
    }
    std::cerr << "Done. Now processing." << std::endl;

    boost::timer t;
    std::size_t         frameId = 0;

    for( cv::Mat* imgGray : frames ) {
        // Set the output folder
        std::stringstream outFileName;
        outFileName << std::setfill('0') << std::setw(5) << frameId;

        // Invert the image for the projection scenario
        //cv::Mat imgGrayInverted;
        //bitwise_not ( imgGray, imgGrayInverted );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, *imgGray, params, bank, std::cerr, outFileName.str());
#else
        detection(frameId, *imgGray, params, bank, outputFile, outFileName.str());
#endif
        ++frameId;
        if( frameId % 100 == 0 ) {
            std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") ";
        }
    }
    std::cerr << std::endl;
  } else if (bfs::is_directory(myPath)) {
    CCTAG_COUT("*** Image sequence mode ***");

    std::vector<bfs::path> vFileInFolder;

    std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
    std::sort(vFileInFolder.begin(), vFileInFolder.end());

    std::size_t frameId = 0;

    for(const auto & fileInFolder : vFileInFolder) {
      const std::string subExt(bfs::extension(fileInFolder));

      if ( (subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG") ) {

        CCTAG_COUT( "Processing image " << fileInFolder.string() );

		cv::Mat src;
    	src = cv::imread(fileInFolder.string());

        cv::Mat imgGray;
        cv::cvtColor( src, imgGray, CV_BGR2GRAY );

        // Call the CCTag detection
#ifdef PRINT_TO_CERR
        detection(frameId, imgGray, params, bank, std::cerr, fileInFolder.stem().string());
#else
        detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string());
#endif
++frameId;
      }
    }
  }else
  {
      throw std::logic_error("Unrecognized input.");
  }
  outputFile.close();
  return 0;
}

<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Computer Science Institute VI, University of Bonn
 *  Author: Joerg Stueckler, 16.09.2011
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of University of Bonn, Computer Science Institute
 *     VI nor the names of its contributors may be used to endorse or
 *     promote products derived from this software without specific
 *     prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/point_types.h>
#include <pcl/common/transforms.h>

#include <opencv2/opencv.hpp>

#include <Eigen/Core>

#include <pcl/segmentation/extract_polygonal_prism_data.h>
#include <pcl/surface/convex_hull.h>

#include <mrsmap/map/multiresolution_csurfel_map.h>
#include <mrsmap/registration/multiresolution_csurfel_registration.h>

#include <boost/thread/thread.hpp>
#include "pcl/common/common_headers.h"
#include "pcl/visualization/pcl_visualizer.h"

#include "pcl/common/centroid.h"
#include "pcl/common/eigen.h"

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

#include <mrsmap/visualization/visualization_map.h>
#include <mrsmap/utilities/utilities.h>

using namespace std;
using namespace mrsmap;

typedef MultiResolutionColorSurfelMap MultiResolutionSurfelMap;

class PoseInfo {
public:
	PoseInfo( const std::string& time, int id, const Eigen::Matrix4d tf )
	: stamp( time ), referenceID( id ), transform( tf ) {}
	~PoseInfo() {}

	std::string stamp;
	int referenceID;
	Eigen::Matrix4d transform;

	EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
};

class EvaluatePoseTracking
{
public:

	EvaluatePoseTracking( int argc, char** argv ) {

		imageAllocator_ = boost::shared_ptr< MultiResolutionSurfelMap::ImagePreAllocator >( new MultiResolutionSurfelMap::ImagePreAllocator() );
		treeNodeAllocator_ = boost::shared_ptr< spatialaggregate::OcTreeNodeDynamicAllocator< float, MultiResolutionSurfelMap::NodeValue > >( new spatialaggregate::OcTreeNodeDynamicAllocator< float, MultiResolutionSurfelMap::NodeValue >( 10000 ) );

		po::options_description desc("Allowed options");
		desc.add_options()
		    ("help,h", "help")
		    ("object,o", po::value<std::string>(&object_name_)->default_value("object"), "object map file")
		    ("inputpath,i", po::value<std::string>(&input_path_)->default_value("."), "path to input data")
		    ("startframe,s", po::value<int>(&start_frame_)->default_value(0), "start frame")
		    ("endframe,e", po::value<int>(&end_frame_)->default_value(1000), "end frame")
		    ("skippastframes,k", po::value<bool>(&skip_past_frames_)->default_value(false), "skip past frames for real-time evaluation")
		;

    	po::variables_map vm;
    	po::store(po::parse_command_line(argc, argv, desc), vm);
    	po::notify(vm);

    	if( vm.count("help") || vm.count("h") ) {
    		std::cout << desc << "\n";
    		exit(0);
    	}

    }

    void load() {

    	std::cout << "loading " << object_name_.c_str() << "\n";

    	// prepare map
		map_ = new MultiResolutionSurfelMap( 0.05f, 30.f );

		map_->load( object_name_ );
		map_->octree_->root_->establishNeighbors();
		map_->buildShapeTextureFeatures();

		map_->extents( map_mean_, map_cov_inv_ );
		map_cov_inv_ = map_cov_inv_.inverse().eval();

		std::cout << "ready\n";

		return;

    }

    void evaluate() {

    	// prepare output file
    	// memorize parameters

		// parse groundtruth.txt to get initial transform
		std::ifstream gtFile( (input_path_ + std::string("/groundtruth.txt")).c_str() );
		while( gtFile.good() ) {

			// read in line
			char lineCStr[1024];
			gtFile.getline( lineCStr, 1024, '\n' );

			std::string lineStr( lineCStr );

			// split line at blanks
			std::vector< std::string > entryStrs;
			boost::split( entryStrs, lineStr, boost::is_any_of("\t ") );

			if( entryStrs.size() != 8 )
				continue;

			std::stringstream sstr;
			sstr << entryStrs[0];
			double stamp = 0.0;
			sstr >> stamp;

			double tx,ty,tz,qx,qy,qz,qw;
			sstr.clear();
			sstr << entryStrs[1];
			sstr >> tx;
			sstr.clear();
			sstr << entryStrs[2];
			sstr >> ty;
			sstr.clear();
			sstr << entryStrs[3];
			sstr >> tz;
			sstr.clear();
			sstr << entryStrs[4];
			sstr >> qx;
			sstr.clear();
			sstr << entryStrs[5];
			sstr >> qy;
			sstr.clear();
			sstr << entryStrs[6];
			sstr >> qz;
			sstr.clear();
			sstr << entryStrs[7];
			sstr >> qw;

			Eigen::Matrix4d transform = Eigen::Matrix4d::Identity();
			transform.block<3,3>(0,0) = Eigen::Quaterniond( qw, qx, qy, qz ).matrix();
			transform.block<3,1>(0,3) = Eigen::Vector3d( tx, ty, tz );

			groundTruth_[stamp] = transform;

		}

    	// parse associations.txt
    	std::ifstream assocFile( (input_path_ + std::string("/associations.txt")).c_str() );
		std::ofstream fileEstimate( (input_path_ + std::string("/pose_estimate.txt")).c_str() );

    	std::vector< std::vector< std::string > > assocs;

    	int count = -1;

    	unsigned int frameIdx = 0;

    	double nextTime = 0;

    	while( assocFile.good() ) {

    		count++;

    		// read in line
    		char lineCStr[1024];
    		assocFile.getline( lineCStr, 1024, '\n' );

    		std::string lineStr( lineCStr );

    		// split line at blanks
			std::vector< std::string > entryStrs;
			boost::split( entryStrs, lineStr, boost::is_any_of("\t ") );

			// parse entries, load images, generate point cloud, process images...
			if( entryStrs.size() == 4 ) {

	    		while( !viewer_.processFrame && viewer_.is_running ) {
	    			usleep(10);
	    		}

				// load images
				cv::Mat depthImg = cv::imread( input_path_ + "/" + entryStrs[1], CV_LOAD_IMAGE_ANYDEPTH );
				cv::Mat rgbImg = cv::imread( input_path_ + "/" + entryStrs[3], CV_LOAD_IMAGE_ANYCOLOR );

				if( frameIdx >= start_frame_ && frameIdx <= end_frame_ ) {

					std::cout << "processing frame " << frameIdx << "\n";

					double stamp = 0.0;
					std::stringstream sstr;
					sstr << entryStrs[0];
					sstr >> stamp;

					if( frameIdx == start_frame_ ) {
						referenceTransform_.setIdentity();

						GTMap::iterator it = groundTruth_.upper_bound( stamp );
						if( it != groundTruth_.end() ) {
							referenceTransform_ = it->second;
							std::cout << "initialized reference frame from ground truth\n";
							std::cout << referenceTransform_;
						}
					}

					if( skip_past_frames_ && nextTime > stamp ) {
						std::cout << "================= SKIP =================\n";
						frameIdx++;
						continue;
					}

					// extract point cloud from image pair
					pcl::PointCloud< pcl::PointXYZRGB >::Ptr cloud( new pcl::PointCloud< pcl::PointXYZRGB >() );
					imagesToPointCloud( depthImg, rgbImg, entryStrs[0], cloud );

					double deltat = processFrame( cloud );

					nextTime = stamp + 0.001 * deltat;

					Eigen::Vector3d t_est( referenceTransform_(0,3), referenceTransform_(1,3), referenceTransform_(2,3) );
					double dist_est = (t_est - map_mean_).norm();

					// dump estimated and ground truth transform
					Eigen::Quaterniond q( referenceTransform_.block<3,3>(0,0) );
					fileEstimate << fixed << setprecision(10) << entryStrs[0] << " " << referenceTransform_(0,3) << " " << referenceTransform_(1,3) << " "  << referenceTransform_(2,3) << " " << q.x() << " " << q.y() << " " << q.z() << " " << q.w() << " " << dist_est << " " << deltat << "\n";

				}

				if( frameIdx == end_frame_ )
					break;

				if( !viewer_.is_running )
					exit(-1);

				viewer_.spinOnce();
				usleep(1000);

				frameIdx++;

			}
    	}

    }

    double processFrame( pcl::PointCloud< pcl::PointXYZRGB >::Ptr& cloud ) {

		// transform point cloud to reference frame
		pcl::PointCloud< pcl::PointXYZRGB >::Ptr transformedCloud( new pcl::PointCloud< pcl::PointXYZRGB >() );
		pcl::transformPointCloud( *cloud, *transformedCloud, referenceTransform_ );

		// consider image borders
		std::vector< int > imageBorderIndices;
		map_->findVirtualBorderPoints( *transformedCloud, imageBorderIndices );

		Eigen::Vector3d t_est( referenceTransform_(0,3), referenceTransform_(1,3), referenceTransform_(2,3) );
		double dist_est = (t_est - map_mean_).norm();
		double covfactor = std::max( 1.5, 0.5*dist_est );

		// concentrate on window at last object pose estimate
		for( unsigned int i = 0; i < transformedCloud->points.size(); i++ ) {

			const pcl::PointXYZRGB& p = transformedCloud->points[i];
			if( isnan( p.x ) ) {
				continue;
			}

			Eigen::Vector3d point( p.x, p.y, p.z );
			if( (point-map_mean_).dot( map_cov_inv_ * (point-map_mean_) ) > covfactor*8.0 ) {
				transformedCloud->points[i].x = std::numeric_limits< float >::quiet_NaN();
			}

		}

		transformedCloud->sensor_origin_ = referenceTransform_.block<4,1>(0,3).cast<float>();
		transformedCloud->sensor_orientation_ = Eigen::Quaterniond( referenceTransform_.block<3,3>(0,0) ).cast<float>();

		if( viewer_.displayScene ) {

			viewer_.displayPointCloud( "current frame", transformedCloud );

		}
		else
			viewer_.viewer->removePointCloud( "current frame" );

		pcl::StopWatch stopwatch;
		stopwatch.reset();

		// add points to local map
		treeNodeAllocator_->reset();
		MultiResolutionSurfelMap target( map_->min_resolution_, map_->max_range_, treeNodeAllocator_ );
		target.imageAllocator_ = imageAllocator_;
		target.addImage( *transformedCloud, false );
		target.octree_->root_->establishNeighbors();
		target.markNoUpdateAtPoints( *transformedCloud, imageBorderIndices );
		target.evaluateSurfels();
		target.buildShapeTextureFeatures();

		Eigen::Matrix4d incTransform = Eigen::Matrix4d::Identity();
		pcl::PointCloud< pcl::PointXYZRGB >::Ptr corrSrc;
		pcl::PointCloud< pcl::PointXYZRGB >::Ptr corrTgt;
		MultiResolutionColorSurfelRegistration reg;
		reg.estimateTransformation( *map_, target, incTransform, 16.f * map_->min_resolution_, map_->min_resolution_, corrSrc, corrTgt, 20, 0, 5 );

		double deltat = stopwatch.getTimeSeconds() * 1000.0;
		std::cout << "registration took: " << deltat << "\n";

		referenceTransform_ = (incTransform * referenceTransform_).eval();

		if( viewer_.displayMap ) {
			pcl::PointCloud< pcl::PointXYZRGB >::Ptr cloud2 = pcl::PointCloud< pcl::PointXYZRGB >::Ptr( new pcl::PointCloud< pcl::PointXYZRGB >() );
			map_->visualize3DColorDistribution( cloud2, viewer_.selectedDepth, viewer_.selectedViewDir, false );
			viewer_.displayPointCloud( "map cloud", cloud2 );
		}
		else
			viewer_.viewer->removePointCloud( "map cloud" );

		return deltat;

    }

public:

	std::string input_path_;
	std::string object_name_;
    double minHeight_, maxHeight_;

    MultiResolutionSurfelMap* map_;
    Eigen::Matrix< double, 3, 1 > map_mean_;
    Eigen::Matrix< double, 3, 3 > map_cov_inv_;

    boost::shared_ptr< MultiResolutionSurfelMap::ImagePreAllocator > imageAllocator_;
    boost::shared_ptr< spatialaggregate::OcTreeNodeDynamicAllocator< float, MultiResolutionSurfelMap::NodeValue > > treeNodeAllocator_;

    double min_resolution_, max_range_;
    int start_frame_, end_frame_;

    bool skip_past_frames_;

    Eigen::Matrix4d initialTransform_, referenceTransform_;

    Viewer viewer_;

    typedef std::map< double, Eigen::Matrix4d, std::less< double >, Eigen::aligned_allocator< std::pair< const double, Eigen::Matrix4d > > > GTMap;
    GTMap groundTruth_;

};

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

	EvaluatePoseTracking ept( argc, argv );
	ept.load();
	ept.evaluate();

	return 0;
}

<commit_msg>small compile fix<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Computer Science Institute VI, University of Bonn
 *  Author: Joerg Stueckler, 16.09.2011
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of University of Bonn, Computer Science Institute
 *     VI nor the names of its contributors may be used to endorse or
 *     promote products derived from this software without specific
 *     prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <pcl/point_types.h>
#include <pcl/common/transforms.h>

#include <opencv2/opencv.hpp>

#include <Eigen/Core>

#include <pcl/segmentation/extract_polygonal_prism_data.h>
#include <pcl/surface/convex_hull.h>

#include <mrsmap/map/multiresolution_csurfel_map.h>
#include <mrsmap/registration/multiresolution_csurfel_registration.h>

#include <boost/thread/thread.hpp>
#include "pcl/common/common_headers.h"
#include "pcl/visualization/pcl_visualizer.h"

#include "pcl/common/centroid.h"
#include "pcl/common/eigen.h"

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

#include <mrsmap/visualization/visualization_map.h>
#include <mrsmap/utilities/utilities.h>

using namespace std;
using namespace mrsmap;

typedef MultiResolutionColorSurfelMap MultiResolutionSurfelMap;

class PoseInfo {
public:
	PoseInfo( const std::string& time, int id, const Eigen::Matrix4d tf )
	: stamp( time ), referenceID( id ), transform( tf ) {}
	~PoseInfo() {}

	std::string stamp;
	int referenceID;
	Eigen::Matrix4d transform;

	EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
};

class EvaluatePoseTracking
{
public:

	EvaluatePoseTracking( int argc, char** argv ) {

		imageAllocator_ = boost::shared_ptr< MultiResolutionSurfelMap::ImagePreAllocator >( new MultiResolutionSurfelMap::ImagePreAllocator() );
		treeNodeAllocator_ = boost::shared_ptr< spatialaggregate::OcTreeNodeDynamicAllocator< float, MultiResolutionSurfelMap::NodeValue > >( new spatialaggregate::OcTreeNodeDynamicAllocator< float, MultiResolutionSurfelMap::NodeValue >( 10000 ) );

		po::options_description desc("Allowed options");
		desc.add_options()
		    ("help,h", "help")
		    ("object,o", po::value<std::string>(&object_name_)->default_value("object"), "object map file")
		    ("inputpath,i", po::value<std::string>(&input_path_)->default_value("."), "path to input data")
		    ("startframe,s", po::value<int>(&start_frame_)->default_value(0), "start frame")
		    ("endframe,e", po::value<int>(&end_frame_)->default_value(1000), "end frame")
		    ("skippastframes,k", po::value<bool>(&skip_past_frames_)->default_value(false), "skip past frames for real-time evaluation")
		;

    	po::variables_map vm;
    	po::store(po::parse_command_line(argc, argv, desc), vm);
    	po::notify(vm);

    	if( vm.count("help") || vm.count("h") ) {
    		std::cout << desc << "\n";
    		exit(0);
    	}

    }

    void load() {

    	std::cout << "loading " << object_name_.c_str() << "\n";

    	// prepare map
		map_ = new MultiResolutionSurfelMap( 0.05f, 30.f );

		map_->load( object_name_ );
		map_->octree_->root_->establishNeighbors();
		map_->buildShapeTextureFeatures();

		map_->extents( map_mean_, map_cov_inv_ );
		map_cov_inv_ = map_cov_inv_.inverse().eval();

		std::cout << "ready\n";

		return;

    }

    void evaluate() {

    	// prepare output file
    	// memorize parameters

		// parse groundtruth.txt to get initial transform
		std::ifstream gtFile( (input_path_ + std::string("/groundtruth.txt")).c_str() );
		while( gtFile.good() ) {

			// read in line
			char lineCStr[1024];
			gtFile.getline( lineCStr, 1024, '\n' );

			std::string lineStr( lineCStr );

			// split line at blanks
			std::vector< std::string > entryStrs;
			boost::split( entryStrs, lineStr, boost::is_any_of("\t ") );

			if( entryStrs.size() != 8 )
				continue;

			std::stringstream sstr;
			sstr << entryStrs[0];
			double stamp = 0.0;
			sstr >> stamp;

			double tx,ty,tz,qx,qy,qz,qw;
			sstr.clear();
			sstr << entryStrs[1];
			sstr >> tx;
			sstr.clear();
			sstr << entryStrs[2];
			sstr >> ty;
			sstr.clear();
			sstr << entryStrs[3];
			sstr >> tz;
			sstr.clear();
			sstr << entryStrs[4];
			sstr >> qx;
			sstr.clear();
			sstr << entryStrs[5];
			sstr >> qy;
			sstr.clear();
			sstr << entryStrs[6];
			sstr >> qz;
			sstr.clear();
			sstr << entryStrs[7];
			sstr >> qw;

			Eigen::Matrix4d transform = Eigen::Matrix4d::Identity();
			transform.block<3,3>(0,0) = Eigen::Quaterniond( qw, qx, qy, qz ).matrix();
			transform.block<3,1>(0,3) = Eigen::Vector3d( tx, ty, tz );

			groundTruth_[stamp] = transform;

		}

    	// parse associations.txt
    	std::ifstream assocFile( (input_path_ + std::string("/associations.txt")).c_str() );
		std::ofstream fileEstimate( (input_path_ + std::string("/pose_estimate.txt")).c_str() );

    	std::vector< std::vector< std::string > > assocs;

    	int count = -1;

    	unsigned int frameIdx = 0;

    	double nextTime = 0;

    	while( assocFile.good() ) {

    		count++;

    		// read in line
    		char lineCStr[1024];
    		assocFile.getline( lineCStr, 1024, '\n' );

    		std::string lineStr( lineCStr );

    		// split line at blanks
			std::vector< std::string > entryStrs;
			boost::split( entryStrs, lineStr, boost::is_any_of("\t ") );

			// parse entries, load images, generate point cloud, process images...
			if( entryStrs.size() == 4 ) {

	    		while( !viewer_.processFrame && viewer_.is_running ) {
	    			usleep(10);
	    		}

				// load images
				cv::Mat depthImg = cv::imread( input_path_ + "/" + entryStrs[1], CV_LOAD_IMAGE_ANYDEPTH );
				cv::Mat rgbImg = cv::imread( input_path_ + "/" + entryStrs[3], CV_LOAD_IMAGE_ANYCOLOR );

				if( frameIdx >= start_frame_ && frameIdx <= end_frame_ ) {

					std::cout << "processing frame " << frameIdx << "\n";

					double stamp = 0.0;
					std::stringstream sstr;
					sstr << entryStrs[0];
					sstr >> stamp;

					if( frameIdx == start_frame_ ) {
						referenceTransform_.setIdentity();

						GTMap::iterator it = groundTruth_.upper_bound( stamp );
						if( it != groundTruth_.end() ) {
							referenceTransform_ = it->second;
							std::cout << "initialized reference frame from ground truth\n";
							std::cout << referenceTransform_;
						}
					}

					if( skip_past_frames_ && nextTime > stamp ) {
						std::cout << "================= SKIP =================\n";
						frameIdx++;
						continue;
					}

					// extract point cloud from image pair
					pcl::PointCloud< pcl::PointXYZRGB >::Ptr cloud( new pcl::PointCloud< pcl::PointXYZRGB >() );
					imagesToPointCloud( depthImg, rgbImg, entryStrs[0], cloud );

					double deltat = processFrame( cloud );

					nextTime = stamp + 0.001 * deltat;

					Eigen::Vector3d t_est( referenceTransform_(0,3), referenceTransform_(1,3), referenceTransform_(2,3) );
					double dist_est = (t_est - map_mean_).norm();

					// dump estimated and ground truth transform
					Eigen::Quaterniond q( referenceTransform_.block<3,3>(0,0) );
					fileEstimate << fixed << setprecision(10) << entryStrs[0] << " " << referenceTransform_(0,3) << " " << referenceTransform_(1,3) << " "  << referenceTransform_(2,3) << " " << q.x() << " " << q.y() << " " << q.z() << " " << q.w() << " " << dist_est << " " << deltat << "\n";

				}

				if( frameIdx == end_frame_ )
					break;

				if( !viewer_.is_running )
					exit(-1);

				viewer_.spinOnce();
				usleep(1000);

				frameIdx++;

			}
    	}

    }

    double processFrame( pcl::PointCloud< pcl::PointXYZRGB >::Ptr& cloud ) {

		// transform point cloud to reference frame
		pcl::PointCloud< pcl::PointXYZRGB >::Ptr transformedCloud( new pcl::PointCloud< pcl::PointXYZRGB >() );
		pcl::transformPointCloud( *cloud, *transformedCloud, referenceTransform_.cast<float>() );

		// consider image borders
		std::vector< int > imageBorderIndices;
		map_->findVirtualBorderPoints( *transformedCloud, imageBorderIndices );

		Eigen::Vector3d t_est( referenceTransform_(0,3), referenceTransform_(1,3), referenceTransform_(2,3) );
		double dist_est = (t_est - map_mean_).norm();
		double covfactor = std::max( 1.5, 0.5*dist_est );

		// concentrate on window at last object pose estimate
		for( unsigned int i = 0; i < transformedCloud->points.size(); i++ ) {

			const pcl::PointXYZRGB& p = transformedCloud->points[i];
			if( isnan( p.x ) ) {
				continue;
			}

			Eigen::Vector3d point( p.x, p.y, p.z );
			if( (point-map_mean_).dot( map_cov_inv_ * (point-map_mean_) ) > covfactor*8.0 ) {
				transformedCloud->points[i].x = std::numeric_limits< float >::quiet_NaN();
			}

		}

		transformedCloud->sensor_origin_ = referenceTransform_.block<4,1>(0,3).cast<float>();
		transformedCloud->sensor_orientation_ = Eigen::Quaterniond( referenceTransform_.block<3,3>(0,0) ).cast<float>();

		if( viewer_.displayScene ) {

			viewer_.displayPointCloud( "current frame", transformedCloud );

		}
		else
			viewer_.viewer->removePointCloud( "current frame" );

		pcl::StopWatch stopwatch;
		stopwatch.reset();

		// add points to local map
		treeNodeAllocator_->reset();
		MultiResolutionSurfelMap target( map_->min_resolution_, map_->max_range_, treeNodeAllocator_ );
		target.imageAllocator_ = imageAllocator_;
		target.addImage( *transformedCloud, false );
		target.octree_->root_->establishNeighbors();
		target.markNoUpdateAtPoints( *transformedCloud, imageBorderIndices );
		target.evaluateSurfels();
		target.buildShapeTextureFeatures();

		Eigen::Matrix4d incTransform = Eigen::Matrix4d::Identity();
		pcl::PointCloud< pcl::PointXYZRGB >::Ptr corrSrc;
		pcl::PointCloud< pcl::PointXYZRGB >::Ptr corrTgt;
		MultiResolutionColorSurfelRegistration reg;
		reg.estimateTransformation( *map_, target, incTransform, 16.f * map_->min_resolution_, map_->min_resolution_, corrSrc, corrTgt, 20, 0, 5 );

		double deltat = stopwatch.getTimeSeconds() * 1000.0;
		std::cout << "registration took: " << deltat << "\n";

		referenceTransform_ = (incTransform * referenceTransform_).eval();

		if( viewer_.displayMap ) {
			pcl::PointCloud< pcl::PointXYZRGB >::Ptr cloud2 = pcl::PointCloud< pcl::PointXYZRGB >::Ptr( new pcl::PointCloud< pcl::PointXYZRGB >() );
			map_->visualize3DColorDistribution( cloud2, viewer_.selectedDepth, viewer_.selectedViewDir, false );
			viewer_.displayPointCloud( "map cloud", cloud2 );
		}
		else
			viewer_.viewer->removePointCloud( "map cloud" );

		return deltat;

    }

public:

	std::string input_path_;
	std::string object_name_;
    double minHeight_, maxHeight_;

    MultiResolutionSurfelMap* map_;
    Eigen::Matrix< double, 3, 1 > map_mean_;
    Eigen::Matrix< double, 3, 3 > map_cov_inv_;

    boost::shared_ptr< MultiResolutionSurfelMap::ImagePreAllocator > imageAllocator_;
    boost::shared_ptr< spatialaggregate::OcTreeNodeDynamicAllocator< float, MultiResolutionSurfelMap::NodeValue > > treeNodeAllocator_;

    double min_resolution_, max_range_;
    int start_frame_, end_frame_;

    bool skip_past_frames_;

    Eigen::Matrix4d initialTransform_, referenceTransform_;

    Viewer viewer_;

    typedef std::map< double, Eigen::Matrix4d, std::less< double >, Eigen::aligned_allocator< std::pair< const double, Eigen::Matrix4d > > > GTMap;
    GTMap groundTruth_;

};

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

	EvaluatePoseTracking ept( argc, argv );
	ept.load();
	ept.evaluate();

	return 0;
}

<|endoftext|>


<commit_before><commit_msg>startup: refactor subprocess-main call out of ChromeMain<commit_after><|endoftext|>


<commit_before><commit_msg>Create ProfilePersonalization in the ctor of ProfileImpl instead of lazily creating it.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This code glues the RLZ library DLL with Chrome. It allows Chrome to work
// with or without the DLL being present. If the DLL is not present the
// functions do nothing and just return false.

#include "chrome/browser/rlz/rlz.h"

#include <windows.h>
#include <process.h>

#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/task.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/template_url_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_settings.h"
//#include "chrome/common/pref_names.h"
//#include "chrome/common/pref_service.h"

namespace {

// The maximum length of an access points RLZ in wide chars.
const DWORD kMaxRlzLength = 64;

// The RLZ is a DLL that might not be present in the system. We load it
// as needed but never unload it.
volatile HMODULE rlz_dll = NULL;

enum {
  ACCESS_VALUES_STALE,      // Possibly new values available.
  ACCESS_VALUES_FRESH       // The cached values are current.
};

// Tracks if we have tried and succeeded sending the ping. This helps us
// decide if we need to refresh the some cached strings.
volatile int access_values_state = ACCESS_VALUES_STALE;

extern "C" {
typedef bool (*RecordProductEventFn)(RLZTracker::Product product,
                                     RLZTracker::AccessPoint point,
                                     RLZTracker::Event event_id,
                                     void* reserved);

typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point,
                                    wchar_t* rlz,
                                    DWORD rlz_size,
                                    void* reserved);

typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product,
                                        void* reserved);

typedef bool (*SendFinancialPingFn)(RLZTracker::Product product,
                                    RLZTracker::AccessPoint* access_points,
                                    const WCHAR* product_signature,
                                    const WCHAR* product_brand,
                                    const WCHAR* product_id,
                                    const WCHAR* product_lang,
                                    void* reserved);
}  // extern "C"

RecordProductEventFn record_event = NULL;
GetAccessPointRlzFn get_access_point = NULL;
ClearAllProductEventsFn clear_all_events = NULL;
SendFinancialPingFn send_ping = NULL;

template <typename FuncT>
FuncT WireExport(HMODULE module, const char* export_name) {
  void* entry_point = ::GetProcAddress(module, export_name);
  return (module)? reinterpret_cast<FuncT>(entry_point) : NULL;
}

HMODULE LoadRLZLibraryInternal(int directory_key) {
  std::wstring rlz_path;
  if (!PathService::Get(directory_key, &rlz_path))
    return NULL;
  file_util::AppendToPath(&rlz_path, L"rlz.dll");
  return ::LoadLibraryW(rlz_path.c_str());
}

bool LoadRLZLibrary(int directory_key) {
  rlz_dll = LoadRLZLibraryInternal(directory_key);
  if (!rlz_dll) {
    // As a last resort we can try the EXE directory.
    if (directory_key != base::DIR_EXE)
      rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE);
  }
  if (rlz_dll) {
    record_event =
        WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent");
    get_access_point =
        WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz");
    clear_all_events =
        WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents");
    send_ping =
        WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing");
    return (record_event && get_access_point && clear_all_events && send_ping);
  }
  return false;
}

class DailyPingTask : public Task {
 public:
  virtual ~DailyPingTask() {
  }
  virtual void Run() {
    // We use a transient thread because we have no guarantees about
    // how long the RLZ lib can block us.
    _beginthread(PingNow, 0, NULL);
  }

 private:
  // Causes a ping to the server using WinInet. There is logic inside RLZ dll
  // that throttles it to a maximum of one ping per day.
  static void _cdecl PingNow(void*) {
    std::wstring lang;
    GoogleUpdateSettings::GetLanguage(&lang);
    if (lang.empty())
      lang = L"en";
    std::wstring brand;
    GoogleUpdateSettings::GetBrand(&brand);
    if (brand.empty())
      brand = L"GGLD";
    if (RLZTracker::SendFinancialPing(RLZTracker::CHROME, L"chrome",
                                      brand.c_str(), NULL, lang.c_str())) {
      access_values_state = ACCESS_VALUES_STALE;
    }
  }
};

// Performs late RLZ initialization and RLZ event recording for chrome.
// This task needs to run on the UI thread.
class DelayedInitTask : public Task {
 public:
  explicit DelayedInitTask(int directory_key, bool first_run)
      : directory_key_(directory_key), first_run_(first_run) {
  }
  virtual ~DelayedInitTask() {
  }
  virtual void Run() {
    // For non-interactive tests we don't do the rest of the initialization
    // because sometimes the very act of loading the dll causes QEMU to crash.
    if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0))
      return;
    if (!LoadRLZLibrary(directory_key_))
      return;
    // Do the initial event recording if is the first run or if we have an
    // empty rlz which means we haven't got a chance to do it.
    std::wstring omnibox_rlz;
    RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz);

    if (first_run_ || omnibox_rlz.empty()) {
      // Record the installation of chrome.
      RLZTracker::RecordProductEvent(RLZTracker::CHROME,
                                     RLZTracker::CHROME_OMNIBOX,
                                     RLZTracker::INSTALL);
      RLZTracker::RecordProductEvent(RLZTracker::CHROME,
                                     RLZTracker::CHROME_HOME_PAGE,
                                     RLZTracker::INSTALL);
      // Record if google is the initial search provider.
      if (IsGoogleDefaultSearch()) {
        RLZTracker::RecordProductEvent(RLZTracker::CHROME,
                                       RLZTracker::CHROME_OMNIBOX,
                                       RLZTracker::SET_TO_GOOGLE);
      }
    }
    // Schedule the daily RLZ ping.
    base::Thread* thread = g_browser_process->file_thread();
    if (thread)
      thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask());
  }

 private:
  bool IsGoogleDefaultSearch() {
    if (!g_browser_process)
      return false;
    std::wstring user_data_dir;
    if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
      return false;
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
    if (!profile)
      return false;
    const TemplateURL* url_template =
        profile->GetTemplateURLModel()->GetDefaultSearchProvider();
    if (!url_template)
      return false;
    return url_template->url()->HasGoogleBaseURLs();
  }

  int directory_key_;
  bool first_run_;
  DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask);
};

}  // namespace

bool RLZTracker::InitRlz(int directory_key) {
  return LoadRLZLibrary(directory_key);
}

bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) {
  // Schedule the delayed init items.
  const int kTwentySeconds = 20 * 1000;
  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      new DelayedInitTask(directory_key, first_run), kTwentySeconds);
  return true;
}

bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
                                    Event event) {
  return (record_event) ? record_event(product, point, event, NULL) : false;
}

bool RLZTracker::ClearAllProductEvents(Product product) {
  return (clear_all_events) ? clear_all_events(product, NULL) : false;
}

// We implement caching of the answer of get_access_point() if the request
// is for CHROME_OMNIBOX. If we had a successful ping, then we update the
// cached value.

bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
  static std::wstring cached_ommibox_rlz;
  if (!get_access_point)
    return false;
  if ((CHROME_OMNIBOX == point) &&
      (access_values_state == ACCESS_VALUES_FRESH)) {
    *rlz = cached_ommibox_rlz;
    return true;
  }
  wchar_t str_rlz[kMaxRlzLength];
  if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL))
    return false;
  if (CHROME_OMNIBOX == point) {
    access_values_state = ACCESS_VALUES_FRESH;
    cached_ommibox_rlz.assign(str_rlz);
  }
  *rlz = str_rlz;
  return true;
}

bool RLZTracker::SendFinancialPing(Product product,
                                   const wchar_t* product_signature,
                                   const wchar_t* product_brand,
                                   const wchar_t* product_id,
                                   const wchar_t* product_lang) {
  AccessPoint points[] = {CHROME_OMNIBOX, CHROME_HOME_PAGE, NO_ACCESS_POINT};
  return (send_ping) ? send_ping(product, points, product_signature,
      product_brand, product_id, product_lang, NULL) : false;
}

<commit_msg>New default brandcode.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This code glues the RLZ library DLL with Chrome. It allows Chrome to work
// with or without the DLL being present. If the DLL is not present the
// functions do nothing and just return false.

#include "chrome/browser/rlz/rlz.h"

#include <windows.h>
#include <process.h>

#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/task.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/template_url_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_settings.h"
//#include "chrome/common/pref_names.h"
//#include "chrome/common/pref_service.h"

namespace {

// The maximum length of an access points RLZ in wide chars.
const DWORD kMaxRlzLength = 64;

// The RLZ is a DLL that might not be present in the system. We load it
// as needed but never unload it.
volatile HMODULE rlz_dll = NULL;

enum {
  ACCESS_VALUES_STALE,      // Possibly new values available.
  ACCESS_VALUES_FRESH       // The cached values are current.
};

// Tracks if we have tried and succeeded sending the ping. This helps us
// decide if we need to refresh the some cached strings.
volatile int access_values_state = ACCESS_VALUES_STALE;

extern "C" {
typedef bool (*RecordProductEventFn)(RLZTracker::Product product,
                                     RLZTracker::AccessPoint point,
                                     RLZTracker::Event event_id,
                                     void* reserved);

typedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point,
                                    wchar_t* rlz,
                                    DWORD rlz_size,
                                    void* reserved);

typedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product,
                                        void* reserved);

typedef bool (*SendFinancialPingFn)(RLZTracker::Product product,
                                    RLZTracker::AccessPoint* access_points,
                                    const WCHAR* product_signature,
                                    const WCHAR* product_brand,
                                    const WCHAR* product_id,
                                    const WCHAR* product_lang,
                                    void* reserved);
}  // extern "C"

RecordProductEventFn record_event = NULL;
GetAccessPointRlzFn get_access_point = NULL;
ClearAllProductEventsFn clear_all_events = NULL;
SendFinancialPingFn send_ping = NULL;

template <typename FuncT>
FuncT WireExport(HMODULE module, const char* export_name) {
  void* entry_point = ::GetProcAddress(module, export_name);
  return (module)? reinterpret_cast<FuncT>(entry_point) : NULL;
}

HMODULE LoadRLZLibraryInternal(int directory_key) {
  std::wstring rlz_path;
  if (!PathService::Get(directory_key, &rlz_path))
    return NULL;
  file_util::AppendToPath(&rlz_path, L"rlz.dll");
  return ::LoadLibraryW(rlz_path.c_str());
}

bool LoadRLZLibrary(int directory_key) {
  rlz_dll = LoadRLZLibraryInternal(directory_key);
  if (!rlz_dll) {
    // As a last resort we can try the EXE directory.
    if (directory_key != base::DIR_EXE)
      rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE);
  }
  if (rlz_dll) {
    record_event =
        WireExport<RecordProductEventFn>(rlz_dll, "RecordProductEvent");
    get_access_point =
        WireExport<GetAccessPointRlzFn>(rlz_dll, "GetAccessPointRlz");
    clear_all_events =
        WireExport<ClearAllProductEventsFn>(rlz_dll, "ClearAllProductEvents");
    send_ping =
        WireExport<SendFinancialPingFn>(rlz_dll, "SendFinancialPing");
    return (record_event && get_access_point && clear_all_events && send_ping);
  }
  return false;
}

class DailyPingTask : public Task {
 public:
  virtual ~DailyPingTask() {
  }
  virtual void Run() {
    // We use a transient thread because we have no guarantees about
    // how long the RLZ lib can block us.
    _beginthread(PingNow, 0, NULL);
  }

 private:
  // Causes a ping to the server using WinInet. There is logic inside RLZ dll
  // that throttles it to a maximum of one ping per day.
  static void _cdecl PingNow(void*) {
    std::wstring lang;
    GoogleUpdateSettings::GetLanguage(&lang);
    if (lang.empty())
      lang = L"en";
    std::wstring brand;
    GoogleUpdateSettings::GetBrand(&brand);
    if (brand.empty())
      brand = L"GGCM";
    if (RLZTracker::SendFinancialPing(RLZTracker::CHROME, L"chrome",
                                      brand.c_str(), NULL, lang.c_str())) {
      access_values_state = ACCESS_VALUES_STALE;
    }
  }
};

// Performs late RLZ initialization and RLZ event recording for chrome.
// This task needs to run on the UI thread.
class DelayedInitTask : public Task {
 public:
  explicit DelayedInitTask(int directory_key, bool first_run)
      : directory_key_(directory_key), first_run_(first_run) {
  }
  virtual ~DelayedInitTask() {
  }
  virtual void Run() {
    // For non-interactive tests we don't do the rest of the initialization
    // because sometimes the very act of loading the dll causes QEMU to crash.
    if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0))
      return;
    if (!LoadRLZLibrary(directory_key_))
      return;
    // Do the initial event recording if is the first run or if we have an
    // empty rlz which means we haven't got a chance to do it.
    std::wstring omnibox_rlz;
    RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz);

    if (first_run_ || omnibox_rlz.empty()) {
      // Record the installation of chrome.
      RLZTracker::RecordProductEvent(RLZTracker::CHROME,
                                     RLZTracker::CHROME_OMNIBOX,
                                     RLZTracker::INSTALL);
      RLZTracker::RecordProductEvent(RLZTracker::CHROME,
                                     RLZTracker::CHROME_HOME_PAGE,
                                     RLZTracker::INSTALL);
      // Record if google is the initial search provider.
      if (IsGoogleDefaultSearch()) {
        RLZTracker::RecordProductEvent(RLZTracker::CHROME,
                                       RLZTracker::CHROME_OMNIBOX,
                                       RLZTracker::SET_TO_GOOGLE);
      }
    }
    // Schedule the daily RLZ ping.
    base::Thread* thread = g_browser_process->file_thread();
    if (thread)
      thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask());
  }

 private:
  bool IsGoogleDefaultSearch() {
    if (!g_browser_process)
      return false;
    std::wstring user_data_dir;
    if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
      return false;
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
    if (!profile)
      return false;
    const TemplateURL* url_template =
        profile->GetTemplateURLModel()->GetDefaultSearchProvider();
    if (!url_template)
      return false;
    return url_template->url()->HasGoogleBaseURLs();
  }

  int directory_key_;
  bool first_run_;
  DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask);
};

}  // namespace

bool RLZTracker::InitRlz(int directory_key) {
  return LoadRLZLibrary(directory_key);
}

bool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) {
  // Schedule the delayed init items.
  const int kTwentySeconds = 20 * 1000;
  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      new DelayedInitTask(directory_key, first_run), kTwentySeconds);
  return true;
}

bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
                                    Event event) {
  return (record_event) ? record_event(product, point, event, NULL) : false;
}

bool RLZTracker::ClearAllProductEvents(Product product) {
  return (clear_all_events) ? clear_all_events(product, NULL) : false;
}

// We implement caching of the answer of get_access_point() if the request
// is for CHROME_OMNIBOX. If we had a successful ping, then we update the
// cached value.

bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
  static std::wstring cached_ommibox_rlz;
  if (!get_access_point)
    return false;
  if ((CHROME_OMNIBOX == point) &&
      (access_values_state == ACCESS_VALUES_FRESH)) {
    *rlz = cached_ommibox_rlz;
    return true;
  }
  wchar_t str_rlz[kMaxRlzLength];
  if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL))
    return false;
  if (CHROME_OMNIBOX == point) {
    access_values_state = ACCESS_VALUES_FRESH;
    cached_ommibox_rlz.assign(str_rlz);
  }
  *rlz = str_rlz;
  return true;
}

bool RLZTracker::SendFinancialPing(Product product,
                                   const wchar_t* product_signature,
                                   const wchar_t* product_brand,
                                   const wchar_t* product_id,
                                   const wchar_t* product_lang) {
  AccessPoint points[] = {CHROME_OMNIBOX, CHROME_HOME_PAGE, NO_ACCESS_POINT};
  return (send_ping) ? send_ping(product, points, product_signature,
      product_brand, product_id, product_lang, NULL) : false;
}

<|endoftext|>


<commit_before>//
//  yas_ui_types.cpp
//

#include "yas_ui_types.h"

using namespace yas;

#pragma mark - ui::uint_region

uint32_t ui::uint_region::left() const {
    return std::min(origin.x, origin.x + size.width);
}

uint32_t ui::uint_region::right() const {
    return std::max(origin.x, origin.x + size.width);
}

uint32_t ui::uint_region::bottom() const {
    return std::min(origin.y, origin.y + size.height);
}

uint32_t ui::uint_region::top() const {
    return std::max(origin.y, origin.y + size.height);
}

#pragma mark - ui:uint_range

uint32_t ui::uint_range::min() const {
    return std::min(location, location + length);
}

uint32_t ui::uint_range::max() const {
    return std::max(location, location + length);
}

#pragma mark - ui::point

ui::point::point() {
}

ui::point::point(float const x, float const y) : x(x), y(y) {
}

ui::point::point(simd::float2 v) : v(std::move(v)) {
}

bool ui::point::operator==(point const &rhs) const {
    return x == rhs.x && y == rhs.y;
}

bool ui::point::operator!=(point const &rhs) const {
    return x != rhs.x || y != rhs.y;
}

ui::point::operator bool() const {
    return x != 0 || y != 0;
}

#pragma mark - ui::size

ui::size::size() {
}

ui::size::size(float const w, float const h) : width(w), height(h) {
}

ui::size::size(simd::float2 v) : v(std::move(v)) {
}

bool ui::size::operator==(size const &rhs) const {
    return width == rhs.width && height == rhs.height;
}

bool ui::size::operator!=(size const &rhs) const {
    return width != rhs.width || height != rhs.height;
}

ui::size::operator bool() const {
    return width != 0 || height != 0;
}

#pragma mark - ui::range

float ui::range::min() const {
    return std::min(location, location + length);
}

float ui::range::max() const {
    return std::max(location, location + length);
}

#pragma mark - ui::region

ui::range ui::region::horizontal_range() const {
    return ui::range{.location = origin.x, .length = size.width};
}

ui::range ui::region::vertical_range() const {
    return ui::range{.location = origin.y, .length = size.height};
}

float ui::region::left() const {
    return std::min(origin.x, origin.x + size.width);
}

float ui::region::right() const {
    return std::max(origin.x, origin.x + size.width);
}

float ui::region::bottom() const {
    return std::min(origin.y, origin.y + size.height);
}

float ui::region::top() const {
    return std::max(origin.y, origin.y + size.height);
}

#pragma mark - color

ui::color::color() {
}

ui::color::color(float const r, float const g, float const b) : red(r), green(g), blue(b) {
}

ui::color::color(simd::float3 v) : v(std::move(v)) {
}

bool ui::color::operator==(color const &rhs) const {
    return red == rhs.red && green == rhs.green && blue == rhs.blue;
}

bool ui::color::operator!=(color const &rhs) const {
    return red != rhs.red || green != rhs.green || blue != rhs.blue;
}

ui::color::operator bool() const {
    return red != 0 || green != 0 || blue != 0;
}

#pragma mark -

simd::float2 yas::to_float2(CGPoint const &point) {
    return simd::float2{static_cast<float>(point.x), static_cast<float>(point.y)};
}

simd::float2 yas::to_float2(simd::float4 const &vec) {
    return simd::float2{vec.x, vec.y};
}

simd::float4 yas::to_float4(simd::float2 const &vec) {
    return simd::float4{vec.x, vec.y, 0.0f, 1.0f};
}

bool yas::contains(ui::region const &region, ui::point const &pos) {
    float const sum_x = region.origin.x + region.size.width;
    float const min_x = std::min(region.origin.x, sum_x);
    float const max_x = std::max(region.origin.x, sum_x);
    float const sum_y = region.origin.y + region.size.height;
    float const min_y = std::min(region.origin.y, sum_y);
    float const max_y = std::max(region.origin.y, sum_y);

    return min_x <= pos.x && pos.x < max_x && min_y <= pos.y && pos.y < max_y;
}

std::string yas::to_string(ui::pivot const &pivot) {
    switch (pivot) {
        case ui::pivot::left:
            return "left";
        case ui::pivot::center:
            return "center";
        case ui::pivot::right:
            return "right";
    }
}

std::string yas::to_string(ui::uint_origin const &origin) {
    return "{" + std::to_string(origin.x) + ", " + std::to_string(origin.y) + "}";
}

std::string yas::to_string(ui::uint_size const &size) {
    return "{" + std::to_string(size.width) + ", " + std::to_string(size.height) + "}";
}

std::string yas::to_string(ui::uint_region const &region) {
    return "{" + to_string(region.origin) + ", " + to_string(region.size) + "}";
}

std::string yas::to_string(ui::region const &region) {
    return "{" + to_string(region.origin) + ", " + to_string(region.size) + "}";
}

std::string yas::to_string(ui::point const &point) {
    return "{" + std::to_string(point.x) + ", " + std::to_string(point.y) + "}";
}

std::string yas::to_string(ui::size const &size) {
    return "{" + std::to_string(size.width) + ", " + std::to_string(size.height) + "}";
}

std::string yas::to_string(ui::color const &color) {
    return "{" + std::to_string(color.red) + ", " + std::to_string(color.green) + ", " + std::to_string(color.blue) +
           "}";
}

std::string yas::to_string(simd::float2 const &value) {
    return "{" + std::to_string(value.x) + ", " + std::to_string(value.y) + "}";
}

std::string yas::to_string(simd::float3 const &value) {
    return "{" + std::to_string(value.x) + ", " + std::to_string(value.y) + ", " + std::to_string(value.z) + "}";
}

std::string yas::to_string(simd::float4 const &value) {
    return "{" + std::to_string(value.x) + ", " + std::to_string(value.y) + ", " + std::to_string(value.z) + ", " +
           std::to_string(value.w) + "}";
}

std::string yas::to_string(simd::float4x4 const &matrix) {
    return "{" + to_string(matrix.columns[0]) + ", " + to_string(matrix.columns[1]) + ", " +
           to_string(matrix.columns[2]) + ", " + to_string(matrix.columns[3]) + "}";
}

#pragma mark -

bool yas::is_equal(simd::float2 const &lhs, simd::float2 const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}

bool yas::is_equal(simd::float3 const &lhs, simd::float3 const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z;
}

bool yas::is_equal(simd::float4 const &lhs, simd::float4 const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w;
}

bool yas::is_equal(simd::float4x4 const &lhs, simd::float4x4 const &rhs) {
    return (&lhs == &rhs) || memcmp(&lhs, &rhs, sizeof(simd::float4x4)) == 0;
}

bool operator==(yas::ui::uint_origin const &lhs, yas::ui::uint_origin const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}

bool operator!=(yas::ui::uint_origin const &lhs, yas::ui::uint_origin const &rhs) {
    return lhs.x != rhs.x || lhs.y != rhs.y;
}

bool operator==(yas::ui::uint_size const &lhs, yas::ui::uint_size const &rhs) {
    return lhs.width == rhs.width && lhs.height == rhs.height;
}

bool operator!=(yas::ui::uint_size const &lhs, yas::ui::uint_size const &rhs) {
    return lhs.width != rhs.width || lhs.height != rhs.height;
}

bool operator==(yas::ui::uint_region const &lhs, yas::ui::uint_region const &rhs) {
    return lhs.origin == rhs.origin && lhs.size == rhs.size;
}

bool operator!=(yas::ui::uint_region const &lhs, yas::ui::uint_region const &rhs) {
    return lhs.origin != rhs.origin || lhs.size != rhs.size;
}

bool operator==(yas::ui::range const &lhs, yas::ui::range const &rhs) {
    return lhs.location == rhs.location && lhs.length == rhs.length;
}

bool operator!=(yas::ui::range const &lhs, yas::ui::range const &rhs) {
    return lhs.location != rhs.location || lhs.length != rhs.length;
}

bool operator==(yas::ui::region const &lhs, yas::ui::region const &rhs) {
    return lhs.origin == rhs.origin && lhs.size == rhs.size;
}

bool operator!=(yas::ui::region const &lhs, yas::ui::region const &rhs) {
    return lhs.origin != rhs.origin || lhs.size != rhs.size;
}

std::ostream &operator<<(std::ostream &os, yas::ui::uint_origin const &origin) {
    os << to_string(origin);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::uint_size const &size) {
    os << to_string(size);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::uint_region const &region) {
    os << to_string(region);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::region const &region) {
    os << to_string(region);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::point const &point) {
    os << to_string(point);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::size const &size) {
    os << to_string(size);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::color const &color) {
    os << to_string(color);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float2 const &vec) {
    os << to_string(vec);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float3 const &vec) {
    os << to_string(vec);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float4 const &vec) {
    os << to_string(vec);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float4x4 const &mat) {
    os << to_string(mat);
    return os;
}
<commit_msg>fix initial values<commit_after>//
//  yas_ui_types.cpp
//

#include "yas_ui_types.h"

using namespace yas;

#pragma mark - ui::uint_region

uint32_t ui::uint_region::left() const {
    return std::min(origin.x, origin.x + size.width);
}

uint32_t ui::uint_region::right() const {
    return std::max(origin.x, origin.x + size.width);
}

uint32_t ui::uint_region::bottom() const {
    return std::min(origin.y, origin.y + size.height);
}

uint32_t ui::uint_region::top() const {
    return std::max(origin.y, origin.y + size.height);
}

#pragma mark - ui:uint_range

uint32_t ui::uint_range::min() const {
    return std::min(location, location + length);
}

uint32_t ui::uint_range::max() const {
    return std::max(location, location + length);
}

#pragma mark - ui::point

ui::point::point() : v(0.0f) {
}

ui::point::point(float const x, float const y) : x(x), y(y) {
}

ui::point::point(simd::float2 v) : v(std::move(v)) {
}

bool ui::point::operator==(point const &rhs) const {
    return x == rhs.x && y == rhs.y;
}

bool ui::point::operator!=(point const &rhs) const {
    return x != rhs.x || y != rhs.y;
}

ui::point::operator bool() const {
    return x != 0 || y != 0;
}

#pragma mark - ui::size

ui::size::size() : v(0.0f) {
}

ui::size::size(float const w, float const h) : width(w), height(h) {
}

ui::size::size(simd::float2 v) : v(std::move(v)) {
}

bool ui::size::operator==(size const &rhs) const {
    return width == rhs.width && height == rhs.height;
}

bool ui::size::operator!=(size const &rhs) const {
    return width != rhs.width || height != rhs.height;
}

ui::size::operator bool() const {
    return width != 0 || height != 0;
}

#pragma mark - ui::range

float ui::range::min() const {
    return std::min(location, location + length);
}

float ui::range::max() const {
    return std::max(location, location + length);
}

#pragma mark - ui::region

ui::range ui::region::horizontal_range() const {
    return ui::range{.location = origin.x, .length = size.width};
}

ui::range ui::region::vertical_range() const {
    return ui::range{.location = origin.y, .length = size.height};
}

float ui::region::left() const {
    return std::min(origin.x, origin.x + size.width);
}

float ui::region::right() const {
    return std::max(origin.x, origin.x + size.width);
}

float ui::region::bottom() const {
    return std::min(origin.y, origin.y + size.height);
}

float ui::region::top() const {
    return std::max(origin.y, origin.y + size.height);
}

#pragma mark - color

ui::color::color() {
}

ui::color::color(float const r, float const g, float const b) : red(r), green(g), blue(b) {
}

ui::color::color(simd::float3 v) : v(std::move(v)) {
}

bool ui::color::operator==(color const &rhs) const {
    return red == rhs.red && green == rhs.green && blue == rhs.blue;
}

bool ui::color::operator!=(color const &rhs) const {
    return red != rhs.red || green != rhs.green || blue != rhs.blue;
}

ui::color::operator bool() const {
    return red != 0 || green != 0 || blue != 0;
}

#pragma mark -

simd::float2 yas::to_float2(CGPoint const &point) {
    return simd::float2{static_cast<float>(point.x), static_cast<float>(point.y)};
}

simd::float2 yas::to_float2(simd::float4 const &vec) {
    return simd::float2{vec.x, vec.y};
}

simd::float4 yas::to_float4(simd::float2 const &vec) {
    return simd::float4{vec.x, vec.y, 0.0f, 1.0f};
}

bool yas::contains(ui::region const &region, ui::point const &pos) {
    float const sum_x = region.origin.x + region.size.width;
    float const min_x = std::min(region.origin.x, sum_x);
    float const max_x = std::max(region.origin.x, sum_x);
    float const sum_y = region.origin.y + region.size.height;
    float const min_y = std::min(region.origin.y, sum_y);
    float const max_y = std::max(region.origin.y, sum_y);

    return min_x <= pos.x && pos.x < max_x && min_y <= pos.y && pos.y < max_y;
}

std::string yas::to_string(ui::pivot const &pivot) {
    switch (pivot) {
        case ui::pivot::left:
            return "left";
        case ui::pivot::center:
            return "center";
        case ui::pivot::right:
            return "right";
    }
}

std::string yas::to_string(ui::uint_origin const &origin) {
    return "{" + std::to_string(origin.x) + ", " + std::to_string(origin.y) + "}";
}

std::string yas::to_string(ui::uint_size const &size) {
    return "{" + std::to_string(size.width) + ", " + std::to_string(size.height) + "}";
}

std::string yas::to_string(ui::uint_region const &region) {
    return "{" + to_string(region.origin) + ", " + to_string(region.size) + "}";
}

std::string yas::to_string(ui::region const &region) {
    return "{" + to_string(region.origin) + ", " + to_string(region.size) + "}";
}

std::string yas::to_string(ui::point const &point) {
    return "{" + std::to_string(point.x) + ", " + std::to_string(point.y) + "}";
}

std::string yas::to_string(ui::size const &size) {
    return "{" + std::to_string(size.width) + ", " + std::to_string(size.height) + "}";
}

std::string yas::to_string(ui::color const &color) {
    return "{" + std::to_string(color.red) + ", " + std::to_string(color.green) + ", " + std::to_string(color.blue) +
           "}";
}

std::string yas::to_string(simd::float2 const &value) {
    return "{" + std::to_string(value.x) + ", " + std::to_string(value.y) + "}";
}

std::string yas::to_string(simd::float3 const &value) {
    return "{" + std::to_string(value.x) + ", " + std::to_string(value.y) + ", " + std::to_string(value.z) + "}";
}

std::string yas::to_string(simd::float4 const &value) {
    return "{" + std::to_string(value.x) + ", " + std::to_string(value.y) + ", " + std::to_string(value.z) + ", " +
           std::to_string(value.w) + "}";
}

std::string yas::to_string(simd::float4x4 const &matrix) {
    return "{" + to_string(matrix.columns[0]) + ", " + to_string(matrix.columns[1]) + ", " +
           to_string(matrix.columns[2]) + ", " + to_string(matrix.columns[3]) + "}";
}

#pragma mark -

bool yas::is_equal(simd::float2 const &lhs, simd::float2 const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}

bool yas::is_equal(simd::float3 const &lhs, simd::float3 const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z;
}

bool yas::is_equal(simd::float4 const &lhs, simd::float4 const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w;
}

bool yas::is_equal(simd::float4x4 const &lhs, simd::float4x4 const &rhs) {
    return (&lhs == &rhs) || memcmp(&lhs, &rhs, sizeof(simd::float4x4)) == 0;
}

bool operator==(yas::ui::uint_origin const &lhs, yas::ui::uint_origin const &rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}

bool operator!=(yas::ui::uint_origin const &lhs, yas::ui::uint_origin const &rhs) {
    return lhs.x != rhs.x || lhs.y != rhs.y;
}

bool operator==(yas::ui::uint_size const &lhs, yas::ui::uint_size const &rhs) {
    return lhs.width == rhs.width && lhs.height == rhs.height;
}

bool operator!=(yas::ui::uint_size const &lhs, yas::ui::uint_size const &rhs) {
    return lhs.width != rhs.width || lhs.height != rhs.height;
}

bool operator==(yas::ui::uint_region const &lhs, yas::ui::uint_region const &rhs) {
    return lhs.origin == rhs.origin && lhs.size == rhs.size;
}

bool operator!=(yas::ui::uint_region const &lhs, yas::ui::uint_region const &rhs) {
    return lhs.origin != rhs.origin || lhs.size != rhs.size;
}

bool operator==(yas::ui::range const &lhs, yas::ui::range const &rhs) {
    return lhs.location == rhs.location && lhs.length == rhs.length;
}

bool operator!=(yas::ui::range const &lhs, yas::ui::range const &rhs) {
    return lhs.location != rhs.location || lhs.length != rhs.length;
}

bool operator==(yas::ui::region const &lhs, yas::ui::region const &rhs) {
    return lhs.origin == rhs.origin && lhs.size == rhs.size;
}

bool operator!=(yas::ui::region const &lhs, yas::ui::region const &rhs) {
    return lhs.origin != rhs.origin || lhs.size != rhs.size;
}

std::ostream &operator<<(std::ostream &os, yas::ui::uint_origin const &origin) {
    os << to_string(origin);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::uint_size const &size) {
    os << to_string(size);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::uint_region const &region) {
    os << to_string(region);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::region const &region) {
    os << to_string(region);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::point const &point) {
    os << to_string(point);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::size const &size) {
    os << to_string(size);
    return os;
}

std::ostream &operator<<(std::ostream &os, yas::ui::color const &color) {
    os << to_string(color);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float2 const &vec) {
    os << to_string(vec);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float3 const &vec) {
    os << to_string(vec);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float4 const &vec) {
    os << to_string(vec);
    return os;
}

std::ostream &operator<<(std::ostream &os, simd::float4x4 const &mat) {
    os << to_string(mat);
    return os;
}
<|endoftext|>


<commit_before>// Module:  Log4CPLUS
// File:    stringhelper.cxx
// Created: 4/2003
// Author:  Tad E. Smith
//
//
// Copyright (C) Tad E. Smith  All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.1  2003/04/18 22:25:30  tcsmith
// Initial version.
//

#include <log4cplus/helpers/stringhelper.h>

#include <iterator>
#include <algorithm>

#ifdef UNICODE
#  include <ccwtype>
#else
#  include <cctype>
#endif

//////////////////////////////////////////////////////////////////////////////
// Global Methods
//////////////////////////////////////////////////////////////////////////////

log4cplus::tstring
log4cplus::helpers::toupper(const log4cplus::tstring& s)
{
    tstring ret;
    std::transform(s.begin(), s.end(),
                   string_append_iterator<tstring>(ret),
#ifdef UNICODE
                   ::towupper);
#else
                   ::toupper);
#endif

    return ret;
}

log4cplus::tstring
log4cplus::helpers::tolower(const log4cplus::tstring& s)
{
    tstring ret;
    std::transform(s.begin(), s.end(),
                   string_append_iterator<tstring>(ret),
#ifdef UNICODE
                   ::towlower);
#else
                   ::tolower);
#endif

    return ret;
}

<commit_msg>Added tostring and towstring method implementations.<commit_after>// Module:  Log4CPLUS
// File:    stringhelper.cxx
// Created: 4/2003
// Author:  Tad E. Smith
//
//
// Copyright (C) Tad E. Smith  All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.2  2003/04/19 21:33:10  tcsmith
// Replaced use of back_insert_iterator with string_append_iterator.
//
// Revision 1.1  2003/04/18 22:25:30  tcsmith
// Initial version.
//

#include <log4cplus/helpers/stringhelper.h>

#include <iterator>
#include <algorithm>

#ifdef UNICODE
#  include <cwctype>
#else
#  include <cctype>
#endif

//////////////////////////////////////////////////////////////////////////////
// Global Methods
//////////////////////////////////////////////////////////////////////////////

#ifdef UNICODE
std::string
log4cplus::helpers::tostring(const std::wstring& src)
{
    std::string ret;
    ret.resize(src.size());
    for (unsigned int i=0; i<src.size(); i++) {
        ret[i] = static_cast<tchar>(src[i]);
    }

    return ret;
}

std::wstring
log4cplus::helpers::towstring(const std::string& src)
{
    std::wstring ret;
    ret.resize(src.size());
    for (unsigned int i=0; i<src.size(); i++) {
        ret[i] = src[i] < 256 ? src[i] : ' ';
    }

    return ret;
}
#endif

log4cplus::tstring
log4cplus::helpers::toupper(const log4cplus::tstring& s)
{
    tstring ret;
    std::transform(s.begin(), s.end(),
                   string_append_iterator<tstring>(ret),
#ifdef UNICODE
                   ::towupper);
#else
                   ::toupper);
#endif

    return ret;
}

log4cplus::tstring
log4cplus::helpers::tolower(const log4cplus::tstring& s)
{
    tstring ret;
    std::transform(s.begin(), s.end(),
                   string_append_iterator<tstring>(ret),
#ifdef UNICODE
                   ::towlower);
#else
                   ::tolower);
#endif

    return ret;
}

<|endoftext|>


<commit_before>#ifndef ITER_UNIQUE_EVERSEEN_HPP_
#define ITER_UNIQUE_EVERSEEN_HPP_

#include "internal/iterbase.hpp"
#include "filter.hpp"

#include <type_traits>
#include <functional>
#include <utility>
#include <unordered_set>
#include <iterator>

namespace iter {
  template <typename Container>
  auto unique_everseen(Container&& container) {
    using elem_type = impl::iterator_deref<Container>;
    auto func = [elem_seen = std::unordered_set<std::decay_t<elem_type>>()](
        const elem_type& e) mutable {
      return elem_seen.insert(e).second;
    };
    return filter(func, std::forward<Container>(container));
  }

  template <typename T>
  auto unique_everseen(std::initializer_list<T> il) {
    auto func = [elem_seen = std::unordered_set<T>()](const T& e) mutable {
      return elem_seen.insert(e).second;
    };
    return filter(func, il);
  }
}

#endif
<commit_msg>drops init list support from unique_everseen<commit_after>#ifndef ITER_UNIQUE_EVERSEEN_HPP_
#define ITER_UNIQUE_EVERSEEN_HPP_

#include "internal/iterbase.hpp"
#include "filter.hpp"

#include <type_traits>
#include <functional>
#include <utility>
#include <unordered_set>
#include <iterator>

namespace iter {
  template <typename Container>
  auto unique_everseen(Container&& container) {
    using elem_type = impl::iterator_deref<Container>;
    auto func = [elem_seen = std::unordered_set<std::decay_t<elem_type>>()](
        const elem_type& e) mutable {
      return elem_seen.insert(e).second;
    };
    return filter(func, std::forward<Container>(container));
  }
}

#endif
<|endoftext|>


<commit_before>// Ouzel by Elviss Strazdins

#ifndef OUZEL_UTILS_UTILS_HPP
#define OUZEL_UTILS_UTILS_HPP

#include <cstring>
#include <cstdint>
#include <random>
#include <string>
#include <type_traits>
#include <vector>

namespace ouzel
{
    template <class T>
    auto getVectorSize(const T& vec) noexcept
    {
        return sizeof(typename T::value_type) * vec.size();
    }

    template <typename T, typename Iterator>
    std::enable_if_t<std::is_unsigned_v<T>, T> decodeBigEndian(Iterator iterator) noexcept
    {
        T result = T(0);

        for (std::size_t i = 0; i < sizeof(T); ++i, ++iterator)
            result |= static_cast<T>(static_cast<std::uint8_t>(*iterator) << ((sizeof(T) - i - 1) * 8));

        return result;
    }

    template <typename T, typename Iterator>
    std::enable_if_t<std::is_unsigned_v<T>, T> decodeLittleEndian(Iterator iterator) noexcept
    {
        T result = T(0);

        for (std::size_t i = 0; i < sizeof(T); ++i, ++iterator)
            result |= static_cast<T>(static_cast<std::uint8_t>(*iterator) << (i * 8));

        return result;
    }

    template <typename T, std::enable_if_t<std::is_unsigned_v<T>>* = nullptr>
    void encodeBigEndian(std::uint8_t* buffer, const T value) noexcept
    {
        for (std::size_t i = 0; i < sizeof(T); ++i)
            buffer[i] = static_cast<std::uint8_t>(value >> ((sizeof(T) - i - 1) * 8));
    }

    template <typename T, std::enable_if_t<std::is_unsigned_v<T>>* = nullptr>
    void encodeLittleEndian(std::uint8_t* buffer, const T value) noexcept
    {
        for (std::size_t i = 0; i < sizeof(T); ++i)
            buffer[i] = static_cast<std::uint8_t>(value >> (i * 8));
    }

    inline auto explodeString(const std::string& str, char delimiter = ' ')
    {
        std::vector<std::string> result;
        for (std::size_t position = 0, beginPosition = 0; position != std::string::npos; beginPosition = position + 1)
        {
            position = str.find(delimiter, beginPosition);
            const std::size_t endPosition = (position == std::string::npos) ? str.size() : position;
            if (endPosition != beginPosition)
                result.push_back(str.substr(beginPosition, endPosition - beginPosition));
        }
        return result;
    }

    template <typename To, typename From>
    std::enable_if_t<
        (sizeof(To) == sizeof(From)) &&
        std::is_trivially_copyable_v<From> &&
        std::is_trivial_v<To> &&
        (std::is_copy_constructible_v<To> || std::is_move_constructible_v<To>),
        To
    >
    bitCast(const From& src) noexcept
    {
        To dst;
        std::memcpy(&dst, &src, sizeof(To));
        return dst;
    }
}

#endif // OUZEL_UTILS_UTILS_HPP
<commit_msg>Remove the unused include<commit_after>// Ouzel by Elviss Strazdins

#ifndef OUZEL_UTILS_UTILS_HPP
#define OUZEL_UTILS_UTILS_HPP

#include <cstring>
#include <cstdint>
#include <string>
#include <type_traits>
#include <vector>

namespace ouzel
{
    template <class T>
    auto getVectorSize(const T& vec) noexcept
    {
        return sizeof(typename T::value_type) * vec.size();
    }

    template <typename T, typename Iterator>
    std::enable_if_t<std::is_unsigned_v<T>, T> decodeBigEndian(Iterator iterator) noexcept
    {
        T result = T(0);

        for (std::size_t i = 0; i < sizeof(T); ++i, ++iterator)
            result |= static_cast<T>(static_cast<std::uint8_t>(*iterator) << ((sizeof(T) - i - 1) * 8));

        return result;
    }

    template <typename T, typename Iterator>
    std::enable_if_t<std::is_unsigned_v<T>, T> decodeLittleEndian(Iterator iterator) noexcept
    {
        T result = T(0);

        for (std::size_t i = 0; i < sizeof(T); ++i, ++iterator)
            result |= static_cast<T>(static_cast<std::uint8_t>(*iterator) << (i * 8));

        return result;
    }

    template <typename T, std::enable_if_t<std::is_unsigned_v<T>>* = nullptr>
    void encodeBigEndian(std::uint8_t* buffer, const T value) noexcept
    {
        for (std::size_t i = 0; i < sizeof(T); ++i)
            buffer[i] = static_cast<std::uint8_t>(value >> ((sizeof(T) - i - 1) * 8));
    }

    template <typename T, std::enable_if_t<std::is_unsigned_v<T>>* = nullptr>
    void encodeLittleEndian(std::uint8_t* buffer, const T value) noexcept
    {
        for (std::size_t i = 0; i < sizeof(T); ++i)
            buffer[i] = static_cast<std::uint8_t>(value >> (i * 8));
    }

    inline auto explodeString(const std::string& str, char delimiter = ' ')
    {
        std::vector<std::string> result;
        for (std::size_t position = 0, beginPosition = 0; position != std::string::npos; beginPosition = position + 1)
        {
            position = str.find(delimiter, beginPosition);
            const std::size_t endPosition = (position == std::string::npos) ? str.size() : position;
            if (endPosition != beginPosition)
                result.push_back(str.substr(beginPosition, endPosition - beginPosition));
        }
        return result;
    }

    template <typename To, typename From>
    std::enable_if_t<
        (sizeof(To) == sizeof(From)) &&
        std::is_trivially_copyable_v<From> &&
        std::is_trivial_v<To> &&
        (std::is_copy_constructible_v<To> || std::is_move_constructible_v<To>),
        To
    >
    bitCast(const From& src) noexcept
    {
        To dst;
        std::memcpy(&dst, &src, sizeof(To));
        return dst;
    }
}

#endif // OUZEL_UTILS_UTILS_HPP
<|endoftext|>