<commit_before>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"

#include "itkImageFileReader.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkImageFileWriter.h"

#include "itkImage.h"
#include "itkVectorImage.h"
#include "itkVector.h"

//-------------------------------------------------------------------------------------

/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( ComponentTypeIn == #type && Dimension == dim ) \
{ \
  function< type, dim >( inputFileName, outputFileName, index ); \
  supported = true; \
}

//-------------------------------------------------------------------------------------

/** Declare ExtractIndex. */
template< class TPixel, unsigned int NDimension >
void ExtractIndex(
  const std::string & inputFileName,
  const std::string & outputFileName,
  const unsigned int & index );

/** Declare PrintHelp. */
void PrintHelp( void );

//-------------------------------------------------------------------------------------

int main( int argc, char ** argv )
{
  /** Check arguments for help. */
  if ( argc < 5 )
  {
    PrintHelp();
    return 1;
  }

  /** Create a command line argument parser. */
  itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
  parser->SetCommandLineArguments( argc, argv );

  /** Get arguments. */
  std::string inputFileName = "";
  bool retin = parser->GetCommandLineArgument( "-in", inputFileName );

  std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
  outputFileName += "INDEXEXTRACTED.mhd";
  parser->GetCommandLineArgument( "-out", outputFileName );

  unsigned int index = 0;
  bool retind = parser->GetCommandLineArgument( "-ind", index );

  /** Check if the required arguments are given. */
  if ( !retin )
  {
    std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
    return 1;
  }
  /** Check if the required arguments are given. */
  if ( !retind )
  {
    std::cerr << "ERROR: You should specify \"-ind\"." << std::endl;
    return 1;
  }

  /** Determine image properties. */
  std::string ComponentTypeIn = "short";
  std::string PixelType; //we don't use this
  unsigned int Dimension = 3;
  unsigned int NumberOfComponents = 1;
  std::vector<unsigned int> imagesize( Dimension, 0 );
  int retgip = GetImageProperties(
    inputFileName,
    PixelType,
    ComponentTypeIn,
    Dimension,
    NumberOfComponents,
    imagesize );
  if ( retgip != 0 )
  {
    std::cerr << "ERROR: error while getting image properties of the input image!" << std::endl;
    return 1;
  }

  /** Check for vector images. */
  if ( NumberOfComponents == 1 )
  {
    std::cerr << "ERROR: The NumberOfComponents is 1!" << std::endl;
    std::cerr << "Cannot make extract index from a scalar image." << std::endl;
    return 1;
  }

  /** Get rid of the possible "_" in ComponentType. */
  ReplaceUnderscoreWithSpace( ComponentTypeIn );

  /** Sanity check. */
  if ( index > NumberOfComponents - 1 )
  {
    std::cerr << "ERROR: You selected index "
      << index << ", where the input image only has "
      << NumberOfComponents << " components." << std::endl;
    return 1;
  }

  /** Run the program. */
  bool supported = false;
  try
  {
    run( ExtractIndex, char, 2 );
    run( ExtractIndex, unsigned char, 2 );
    run( ExtractIndex, short, 2 );
    run( ExtractIndex, unsigned short, 2 );
    run( ExtractIndex, int, 2 );
    run( ExtractIndex, unsigned int, 2 );
    run( ExtractIndex, long, 2 );
    //run( ExtractIndex, unsigned long, 2 );
    run( ExtractIndex, float, 2 );
    run( ExtractIndex, double, 2 );

    run( ExtractIndex, char, 3 );
    run( ExtractIndex, unsigned char, 3 );
    run( ExtractIndex, short, 3 );
    run( ExtractIndex, unsigned short, 3 );
    run( ExtractIndex, int, 3 );
    run( ExtractIndex, unsigned int, 3 );
    run( ExtractIndex, long, 3 );
    //run( ExtractIndex, unsigned long, 3 );
    run( ExtractIndex, float, 3 );
    run( ExtractIndex, double, 3 );
  }
  catch( itk::ExceptionObject &e )
  {
    std::cerr << "Caught ITK exception: " << e << std::endl;
    return 1;
  }
  if ( !supported )
  {
    std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
    std::cerr
      << "pixel (component) type = " << ComponentTypeIn
      << " ; dimension = " << Dimension
      << std::endl;
    return 1;
  }

  /** End program. */
  return 0;

} // end main

/**
 * ******************* ExtractIndex *******************
 */

template< class TPixel, unsigned int NDimension >
void ExtractIndex(
  const std::string & inputFileName,
  const std::string & outputFileName,
  const unsigned int & index )
{
  /** Typedef's. */
  typedef TPixel                 PixelType;
  const unsigned int Dimension = NDimension;

  //typedef itk::Vector< PixelType, Dimension >         VectorPixelType;
  //typedef itk::Image< VectorPixelType, Dimension >    VectorImageType;
  /** Use vector image type that dynamically determines vector length: */
  typedef itk::VectorImage< PixelType, Dimension >    VectorImageType;
  typedef itk::Image< PixelType, Dimension >          ImageType;
  typedef itk::ImageFileReader< VectorImageType >     ImageReaderType;
  typedef itk::VectorIndexSelectionCastImageFilter<
    VectorImageType, ImageType >                      IndexExtractorType;
  typedef itk::ImageFileWriter< ImageType >           ImageWriterType;

  /** Read input image. */
  typename ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( inputFileName );

  /** Extract index. */
  typename IndexExtractorType::Pointer extractor = IndexExtractorType::New();
  extractor->SetInput( reader->GetOutput() );
  extractor->SetIndex( index );

  /** Write output image. */
  typename ImageWriterType::Pointer writer = ImageWriterType::New();
  writer->SetFileName( outputFileName );
  writer->SetInput( extractor->GetOutput() );
  writer->Update();

} // end ExtractIndex()

/**
 * ******************* PrintHelp *******************
 */

void PrintHelp()
{
  std::cout << "This program extracts a user specified component from a vector image.\n";
  std::cout << "Usage:\n"
            << "pxextractindexfromvectorimage\n";
  std::cout << "  -in      inputFilename\n";
  std::cout << "  [-out]   outputFilename, default in + INDEXEXTRACTED.mhd\n";
  std::cout << "  -ind     a valid index\n";
  std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int,\n"
            << "long, float, double." << std::endl;

} // end PrintHelp()

<commit_msg>New style arguments for extractindexfromvectorimage<commit_after>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"

#include "itkImageFileReader.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkImageFileWriter.h"

#include "itkImage.h"
#include "itkVectorImage.h"
#include "itkVector.h"

//-------------------------------------------------------------------------------------

/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( ComponentTypeIn == #type && Dimension == dim ) \
{ \
  function< type, dim >( inputFileName, outputFileName, index ); \
  supported = true; \
}

//-------------------------------------------------------------------------------------

/** Declare ExtractIndex. */
template< class TPixel, unsigned int NDimension >
void ExtractIndex(
  const std::string & inputFileName,
  const std::string & outputFileName,
  const unsigned int & index );

/** Declare PrintHelp. */
std::string PrintHelp( void );

//-------------------------------------------------------------------------------------

int main( int argc, char ** argv )
{
  /** Create a command line argument parser. */
  itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
  parser->SetCommandLineArguments( argc, argv );
  parser->SetProgramHelpText(PrintHelp());

  parser->MarkArgumentAsRequired( "-in", "The input filename." );
  parser->MarkArgumentAsRequired( "-ind", "The index to extract." );

  bool validateArguments = parser->CheckForRequiredArguments();

  if(!validateArguments)
  {
    return EXIT_FAILURE;
  }

  /** Get arguments. */
  std::string inputFileName = "";
  parser->GetCommandLineArgument( "-in", inputFileName );

  std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
  outputFileName += "INDEXEXTRACTED.mhd";
  parser->GetCommandLineArgument( "-out", outputFileName );

  unsigned int index = 0;
  parser->GetCommandLineArgument( "-ind", index );

  /** Determine image properties. */
  std::string ComponentTypeIn = "short";
  std::string PixelType; //we don't use this
  unsigned int Dimension = 3;
  unsigned int NumberOfComponents = 1;
  std::vector<unsigned int> imagesize( Dimension, 0 );
  int retgip = GetImageProperties(
    inputFileName,
    PixelType,
    ComponentTypeIn,
    Dimension,
    NumberOfComponents,
    imagesize );
  if ( retgip != 0 )
  {
    std::cerr << "ERROR: error while getting image properties of the input image!" << std::endl;
    return 1;
  }

  /** Check for vector images. */
  if ( NumberOfComponents == 1 )
  {
    std::cerr << "ERROR: The NumberOfComponents is 1!" << std::endl;
    std::cerr << "Cannot make extract index from a scalar image." << std::endl;
    return 1;
  }

  /** Get rid of the possible "_" in ComponentType. */
  ReplaceUnderscoreWithSpace( ComponentTypeIn );

  /** Sanity check. */
  if ( index > NumberOfComponents - 1 )
  {
    std::cerr << "ERROR: You selected index "
      << index << ", where the input image only has "
      << NumberOfComponents << " components." << std::endl;
    return 1;
  }

  /** Run the program. */
  bool supported = false;
  try
  {
    run( ExtractIndex, char, 2 );
    run( ExtractIndex, unsigned char, 2 );
    run( ExtractIndex, short, 2 );
    run( ExtractIndex, unsigned short, 2 );
    run( ExtractIndex, int, 2 );
    run( ExtractIndex, unsigned int, 2 );
    run( ExtractIndex, long, 2 );
    //run( ExtractIndex, unsigned long, 2 );
    run( ExtractIndex, float, 2 );
    run( ExtractIndex, double, 2 );

    run( ExtractIndex, char, 3 );
    run( ExtractIndex, unsigned char, 3 );
    run( ExtractIndex, short, 3 );
    run( ExtractIndex, unsigned short, 3 );
    run( ExtractIndex, int, 3 );
    run( ExtractIndex, unsigned int, 3 );
    run( ExtractIndex, long, 3 );
    //run( ExtractIndex, unsigned long, 3 );
    run( ExtractIndex, float, 3 );
    run( ExtractIndex, double, 3 );
  }
  catch( itk::ExceptionObject &e )
  {
    std::cerr << "Caught ITK exception: " << e << std::endl;
    return 1;
  }
  if ( !supported )
  {
    std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
    std::cerr
      << "pixel (component) type = " << ComponentTypeIn
      << " ; dimension = " << Dimension
      << std::endl;
    return 1;
  }

  /** End program. */
  return 0;

} // end main

/**
 * ******************* ExtractIndex *******************
 */

template< class TPixel, unsigned int NDimension >
void ExtractIndex(
  const std::string & inputFileName,
  const std::string & outputFileName,
  const unsigned int & index )
{
  /** Typedef's. */
  typedef TPixel                 PixelType;
  const unsigned int Dimension = NDimension;

  //typedef itk::Vector< PixelType, Dimension >         VectorPixelType;
  //typedef itk::Image< VectorPixelType, Dimension >    VectorImageType;
  /** Use vector image type that dynamically determines vector length: */
  typedef itk::VectorImage< PixelType, Dimension >    VectorImageType;
  typedef itk::Image< PixelType, Dimension >          ImageType;
  typedef itk::ImageFileReader< VectorImageType >     ImageReaderType;
  typedef itk::VectorIndexSelectionCastImageFilter<
    VectorImageType, ImageType >                      IndexExtractorType;
  typedef itk::ImageFileWriter< ImageType >           ImageWriterType;

  /** Read input image. */
  typename ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( inputFileName );

  /** Extract index. */
  typename IndexExtractorType::Pointer extractor = IndexExtractorType::New();
  extractor->SetInput( reader->GetOutput() );
  extractor->SetIndex( index );

  /** Write output image. */
  typename ImageWriterType::Pointer writer = ImageWriterType::New();
  writer->SetFileName( outputFileName );
  writer->SetInput( extractor->GetOutput() );
  writer->Update();

} // end ExtractIndex()

/**
 * ******************* PrintHelp *******************
 */

std::string PrintHelp()
{
  std::string helpText = "This program extracts a user specified component from a vector image.\n \
  Usage:\n \
  pxextractindexfromvectorimage\n \
    -in      inputFilename\n \
    [-out]   outputFilename, default in + INDEXEXTRACTED.mhd\n \
    -ind     a valid index\n \
  Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int,\n \
  long, float, double.";
  return helpText;
} // end PrintHelp()

<|endoftext|>


<commit_before>//
//  Macros.hpp
//  SwingGame
//
//  Created by Tim Brier on 25/09/2014.
//  Copyright (c) 2014 tbrier. All rights reserved.
//

#ifndef SwingGame_Macros_hpp
#define SwingGame_Macros_hpp

// =============================================================================
// Allocation
// -----------------------------------------------------------------------------
#define SAFE_DELETE(ptr)    \
    if (ptr != NULL)        \
    {                       \
        delete ptr;         \
        ptr = NULL;         \
    }

// =============================================================================
// Logging
// -----------------------------------------------------------------------------
#if SG_DEBUG
#define DEBUG_LOG(...)                      \
    printf("%s:%d ", __FILE__, __LINE__);   \
    printf(__VA_ARGS__);                    \
    printf("\n");
#else
#define DEBUG_LOG(fmt, ...)
#endif

#endif
<commit_msg>Add a macro to iterate over a list<commit_after>//
//  Macros.hpp
//  SwingGame
//
//  Created by Tim Brier on 25/09/2014.
//  Copyright (c) 2014 tbrier. All rights reserved.
//

#ifndef SwingGame_Macros_hpp
#define SwingGame_Macros_hpp

// =============================================================================
// Allocation
// -----------------------------------------------------------------------------
#define SAFE_DELETE(ptr)    \
    if (ptr != NULL)        \
    {                       \
        delete ptr;         \
        ptr = NULL;         \
    }

// =============================================================================
// Logging
// -----------------------------------------------------------------------------
#if SG_DEBUG
#define DEBUG_LOG(...)                      \
    printf("%s:%d ", __FILE__, __LINE__);   \
    printf(__VA_ARGS__);                    \
    printf("\n");
#else
#define DEBUG_LOG(fmt, ...)
#endif

// =============================================================================
// Iterate over lists
// -----------------------------------------------------------------------------
#define FOR_EACH_IN_LIST(type, listName)                            \
    for (std::list<type>::iterator it = listName.begin();           \
         it != listName.end();                                      \
         ++it)

#endif
<|endoftext|>


<commit_before><commit_msg>Tests for change_strength() and change_weight()<commit_after><|endoftext|>


<commit_before>#include "Window.h"

#define DELAY_BEETWEEN_2_BUTTON 20

Window::Window():
    m_clock(),

    m_window(new sf::RenderWindow(sf::VideoMode(800, 800), "IN in Game!!!")),
    m_currentWorld(new World()),

	m_currentStatus(GAME_MAIN_MENU),
    m_mouseButtonPressed(false),
    m_leftButtonPushed(false),
    m_timeLeftButtonPressed(),
    m_rightButtonPushed(false),
    m_timeRightButtonPressed(),
    m_bothButtonsEnabled(false)
{
    m_buttonDeadZoneDelay = sf::milliseconds(50);

    sf::View view(sf::FloatRect(0, 0, m_window->getSize().x , m_window->getSize().y));
    m_window->setView(view);
}

Window::~Window()
{
    if(m_window->isOpen())
        m_window->close();

    delete m_currentWorld;
    delete m_window;
}

int Window::run()
{
	//update state of the system
	sf::Clock clk;
    while(m_currentStatus != GAME_STOPPED)
    {
        //events
        sf::Event event;
        while(m_window->pollEvent(event))
            this->react(event);

		if (clk.getElapsedTime().asMilliseconds() > DELAY_BEETWEEN_2_BUTTON)
		{
			this->update(clk );

        //drawing
        m_window->clear();
        this->draw();
        m_window->display();
		clk.restart();
		}
    }

    m_window->close();

    return EXIT_SUCCESS;
}

void Window::draw() const
{
	m_currentWorld->draw(m_window);
}

void Window::react(sf::Event const& event)
{
    if(event.type == sf::Event::Closed)
    {
        m_currentStatus = GAME_STOPPED;
    }

    else if(event.type == sf::Event::Resized)
    {
        m_window->setView(sf::View(sf::FloatRect(0,0, event.size.width, event.size.height)));
    }

    else if(event.type == sf::Event::MouseWheelScrolled)
    {
        sf::View view = m_window->getView();
        if(event.mouseWheelScroll.delta < 0)
            view.zoom(1.2);
        else
            view.zoom(0.8);
        m_window->setView(view);
    }

    else if(event.type == sf::Event::MouseButtonPressed)
    {
        if(event.mouseButton.button == sf::Mouse::Left)
            m_mouseButtonPressed = true;
    }

    else if(event.type == sf::Event::MouseButtonReleased)
    {
        if(event.mouseButton.button == sf::Mouse::Left)
            m_mouseButtonPressed = false;
    }

    else if(event.type == sf::Event::MouseMoved)
    {
        if(m_mouseButtonPressed)
        {
            int deltaX = m_mouseOldX - event.mouseMove.x;
            int deltaY = m_mouseOldY - event.mouseMove.y;

            sf::View view = m_window->getView();
            view.move(deltaX, deltaY);
            m_window->setView(view);
        }

        m_mouseOldX = event.mouseMove.x;
        m_mouseOldY = event.mouseMove.y;
    }

    else if(event.type == sf::Event::KeyPressed)
    {
        if(event.key.code == sf::Keyboard::Left)
        {
            if(m_rightButtonPushed)
            {
                if((m_clock.getElapsedTime() - m_timeRightButtonPressed) < m_buttonDeadZoneDelay)
                {
                    m_bothButtonsEnabled = true;
                    //one-time action for both buttons
                    bothButtons();
                }

                else
                {
                    m_leftButtonPushed = false;
                    m_rightButtonPushed = false;
                }
            }

            else
            {
                m_leftButtonPushed = true;
                m_timeLeftButtonPressed = m_clock.getElapsedTime();
            }
        }

        else if(event.key.code == sf::Keyboard::Right)
        {
            if(m_leftButtonPushed)
            {
                if((m_clock.getElapsedTime() - m_timeLeftButtonPressed) < m_buttonDeadZoneDelay)
                {
                    m_bothButtonsEnabled = true;
                    //one-time action for both buttons
                    bothButtons();
                }

                else
                {
                    m_rightButtonPushed = false;
                    m_leftButtonPushed = false;
                }
            }

            else
            {
                m_rightButtonPushed = true;
                m_timeRightButtonPressed = m_clock.getElapsedTime();
            }
        }
    }

    else if(event.type == sf::Event::KeyReleased)
    {
        if(event.key.code == sf::Keyboard::Left)
        {
            if(m_bothButtonsEnabled)
            {
                m_rightButtonPushed = false;
                m_bothButtonsEnabled = false;
            }
            m_leftButtonPushed = false;
        }
        else if(event.key.code == sf::Keyboard::Right)
        {
            if(m_bothButtonsEnabled)
            {
                m_leftButtonPushed = false;
                m_bothButtonsEnabled = false;
            }
            m_rightButtonPushed = false;
        }
    }
}

void Window::update(sf::Clock const & clk)
{
    if(m_bothButtonsEnabled)
    {
        //repeated action for both buttons
    }

    else if(m_leftButtonPushed)
    {
        if((m_clock.getElapsedTime() - m_timeLeftButtonPressed) >= m_buttonDeadZoneDelay)
        {
            //repeated action for left button
            leftButton();
        }
    }

    else if(m_rightButtonPushed)
    {
        if((m_clock.getElapsedTime() - m_timeRightButtonPressed) >= m_buttonDeadZoneDelay)
        {
            //repeated action for right button
            rightButton();
        }
    }

    m_currentWorld->update(clk );
}

void Window::leftButton() const
{
	//std::cout << "SetAngle:" << m_currentWorld->getCharacter()-> << std::endl;

	Ray intersectionRay(m_currentWorld->getCharacter()->getPosition(), m_currentWorld->getCharacter()->getDirection());
	m_currentWorld->getBuilding()->checkCollisions(&intersectionRay);
	std::cout << "distance to intersection: " << intersectionRay.distanceToIntersection() << std::endl;

	if(!m_currentWorld->getCharacter()->isJumping())
		m_currentWorld->getCharacter()->setAngle(10);
	//std::cout << "Angle: " << m_currentWorld->getCharacter()-> << std::endl;

	m_currentWorld->getCharacter()->getArrowSprite()->setRotation(m_currentWorld->getCharacter()->getAngle()-45);

}

void Window::rightButton() const
{
	//std::cout << "Jump" << std::endl;

	Ray intersectionRay(m_currentWorld->getCharacter()->getPosition(), m_currentWorld->getCharacter()->getDirection());
	m_currentWorld->getBuilding()->checkCollisions(&intersectionRay);
	std::cout << "distance to intersection: " << intersectionRay.distanceToIntersection() << std::endl;

	if(!m_currentWorld->getCharacter()->isJumping())
		m_currentWorld->getCharacter()->setAngle(-10);

	m_currentWorld->getCharacter()->getArrowSprite()->setRotation(m_currentWorld->getCharacter()->getAngle()-45);
}

void Window::bothButtons() const
{
	std::cout << "Jump" << std::endl;
	Ray * intersectionRay = m_currentWorld->getCharacter()->jump();

	m_currentWorld->getBuilding()->checkCollisions(intersectionRay);

	//Rcupre distance
	//	//world->getBuilding()->checkCollisions(m_intersectionRay);
	//{
	//	std::cout << "/!\\ Pas de Collisions /!\\" << std::endl;
	//	setPosition(nextFramePosition());
	//	setStatusCollision(false);
	//}

}

<commit_msg>J'ai dis yo<commit_after>#include "Window.h"

#define DELAY_BEETWEEN_2_BUTTON 20

Window::Window():
    m_clock(),

    m_window(new sf::RenderWindow(sf::VideoMode(800, 800), "IN in Game!!!")),
    m_currentWorld(new World()),

	m_currentStatus(GAME_MAIN_MENU),
    m_mouseButtonPressed(false),
    m_leftButtonPushed(false),
    m_timeLeftButtonPressed(),
    m_rightButtonPushed(false),
    m_timeRightButtonPressed(),
    m_bothButtonsEnabled(false)
{
    m_buttonDeadZoneDelay = sf::milliseconds(50);

    sf::View view(sf::FloatRect(0, 0, m_window->getSize().x , m_window->getSize().y));
    m_window->setView(view);
}

Window::~Window()
{
    if(m_window->isOpen())
        m_window->close();

    delete m_currentWorld;
    delete m_window;
}

int Window::run()
{
	//update state of the system
	sf::Clock clk;
    while(m_currentStatus != GAME_STOPPED)
    {
        //events
        sf::Event event;
        while(m_window->pollEvent(event))
            this->react(event);

		if (clk.getElapsedTime().asMilliseconds() > DELAY_BEETWEEN_2_BUTTON)
		{
			this->update(clk );

        //drawing
        m_window->clear();
        this->draw();
        m_window->display();
		clk.restart();
		}
    }

    m_window->close();

    return EXIT_SUCCESS;
}

void Window::draw() const
{
	m_currentWorld->draw(m_window);
}

void Window::react(sf::Event const& event)
{
    if(event.type == sf::Event::Closed)
    {
        m_currentStatus = GAME_STOPPED;
    }

    else if(event.type == sf::Event::Resized)
    {
        m_window->setView(sf::View(sf::FloatRect(0,0, event.size.width, event.size.height)));
    }

    else if(event.type == sf::Event::MouseWheelScrolled)
    {
        sf::View view = m_window->getView();
        if(event.mouseWheelScroll.delta < 0)
            view.zoom(1.2);
        else
            view.zoom(0.8);
        m_window->setView(view);
    }

    else if(event.type == sf::Event::MouseButtonPressed)
    {
        if(event.mouseButton.button == sf::Mouse::Left)
            m_mouseButtonPressed = true;
    }

    else if(event.type == sf::Event::MouseButtonReleased)
    {
        if(event.mouseButton.button == sf::Mouse::Left)
            m_mouseButtonPressed = false;
    }

    else if(event.type == sf::Event::MouseMoved)
    {
        if(m_mouseButtonPressed)
        {
            int deltaX = m_mouseOldX - event.mouseMove.x;
            int deltaY = m_mouseOldY - event.mouseMove.y;

            sf::View view = m_window->getView();
            view.move(deltaX, deltaY);
            m_window->setView(view);
        }

        m_mouseOldX = event.mouseMove.x;
        m_mouseOldY = event.mouseMove.y;
    }

    else if(event.type == sf::Event::KeyPressed)
    {
        if(event.key.code == sf::Keyboard::Left)
        {
            if(m_rightButtonPushed)
            {
                if((m_clock.getElapsedTime() - m_timeRightButtonPressed) < m_buttonDeadZoneDelay)
                {
                    m_bothButtonsEnabled = true;
                    //one-time action for both buttons
                    bothButtons();
                }

                else
                {
                    m_leftButtonPushed = false;
                    m_rightButtonPushed = false;
                }
            }

            else
            {
                m_leftButtonPushed = true;
                m_timeLeftButtonPressed = m_clock.getElapsedTime();
            }
        }

        else if(event.key.code == sf::Keyboard::Right)
        {
            if(m_leftButtonPushed)
            {
                if((m_clock.getElapsedTime() - m_timeLeftButtonPressed) < m_buttonDeadZoneDelay)
                {
                    m_bothButtonsEnabled = true;
                    //one-time action for both buttons
                    bothButtons();
                }

                else
                {
                    m_rightButtonPushed = false;
                    m_leftButtonPushed = false;
                }
            }

            else
            {
                m_rightButtonPushed = true;
                m_timeRightButtonPressed = m_clock.getElapsedTime();
            }
        }
    }

    else if(event.type == sf::Event::KeyReleased)
    {
        if(event.key.code == sf::Keyboard::Left)
        {
            if(m_bothButtonsEnabled)
            {
                m_rightButtonPushed = false;
                m_bothButtonsEnabled = false;
            }
            m_leftButtonPushed = false;
        }
        else if(event.key.code == sf::Keyboard::Right)
        {
            if(m_bothButtonsEnabled)
            {
                m_leftButtonPushed = false;
                m_bothButtonsEnabled = false;
            }
            m_rightButtonPushed = false;
        }
    }
}

void Window::update(sf::Clock const & clk)
{
    if(m_bothButtonsEnabled)
    {
        //repeated action for both buttons
    }

    else if(m_leftButtonPushed)
    {
        if((m_clock.getElapsedTime() - m_timeLeftButtonPressed) >= m_buttonDeadZoneDelay)
        {
            //repeated action for left button
            leftButton();
        }
    }

    else if(m_rightButtonPushed)
    {
        if((m_clock.getElapsedTime() - m_timeRightButtonPressed) >= m_buttonDeadZoneDelay)
        {
            //repeated action for right button
            rightButton();
        }
    }

    m_currentWorld->update(clk );
}

void Window::leftButton() const
{
	//std::cout << "SetAngle:" << m_currentWorld->getCharacter()-> << std::endl;

	Ray intersectionRay(m_currentWorld->getCharacter()->getPosition(), m_currentWorld->getCharacter()->getDirection());
	m_currentWorld->getBuilding()->checkCollisions(&intersectionRay);
	std::cout << "distance to intersection: " << intersectionRay.distanceToIntersection() << std::endl;

	if(!m_currentWorld->getCharacter()->isJumping())
		m_currentWorld->getCharacter()->setAngle(10);
	//std::cout << "Angle: " << m_currentWorld->getCharacter()-> << std::endl;

	m_currentWorld->getCharacter()->getArrowSprite()->setRotation(m_currentWorld->getCharacter()->getAngle()-45);

}

void Window::rightButton() const
{
	//std::cout << "Jump" << std::endl;

	Ray intersectionRay(m_currentWorld->getCharacter()->getPosition(), m_currentWorld->getCharacter()->getDirection());
	m_currentWorld->getBuilding()->checkCollisions(&intersectionRay);
	std::cout << "distance to intersection: " << intersectionRay.distanceToIntersection() << std::endl;

	if(!m_currentWorld->getCharacter()->isJumping())
		m_currentWorld->getCharacter()->setAngle(-10);

	m_currentWorld->getCharacter()->getArrowSprite()->setRotation(m_currentWorld->getCharacter()->getAngle()-45);
}

void Window::bothButtons() const
{
	std::cout << "Jump" << std::endl;
	Ray * intersectionRay = m_currentWorld->getCharacter()->jump();

	m_currentWorld->getBuilding()->checkCollisions(intersectionRay);

	// Yoooo la frite ?

	//Rcupre distance
	//	//world->getBuilding()->checkCollisions(m_intersectionRay);
	//{
	//	std::cout << "/!\\ Pas de Collisions /!\\" << std::endl;
	//	setPosition(nextFramePosition());
	//	setStatusCollision(false);
	//}

}

<|endoftext|>


<commit_before><commit_msg>#87057#: create tiles instead of bands<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: download.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 20:10:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DOWNLOAD_HXX
#define _DOWNLOAD_HXX

// Forward declarations
class String;
class Link;

#define DOWNLOAD_SUCCESS    0
#define DOWNLOAD_CONNECT    1
#define DOWNLOAD_LOCATION   2
#define DOWNLOAD_ABORT      3
#define DOWNLOAD_FILEACCESS 4
#define DOWNLOAD_INSTALL    5
#define DOWNLOAD_ERROR      6

class Downloader
/* ***************************************************************************
Purpose: Abstract base class for a file downloader
*************************************************************************** */
{
public:
    Downloader() {};

    virtual void Download(const String &rDestLocation,
                          const String &rSourceLocation,
                          const Link &rFinishedLink) = 0;
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.120); FILE MERGED 2008/03/28 15:41:07 rt 1.2.120.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: download.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DOWNLOAD_HXX
#define _DOWNLOAD_HXX

// Forward declarations
class String;
class Link;

#define DOWNLOAD_SUCCESS    0
#define DOWNLOAD_CONNECT    1
#define DOWNLOAD_LOCATION   2
#define DOWNLOAD_ABORT      3
#define DOWNLOAD_FILEACCESS 4
#define DOWNLOAD_INSTALL    5
#define DOWNLOAD_ERROR      6

class Downloader
/* ***************************************************************************
Purpose: Abstract base class for a file downloader
*************************************************************************** */
{
public:
    Downloader() {};

    virtual void Download(const String &rDestLocation,
                          const String &rSourceLocation,
                          const Link &rFinishedLink) = 0;
};

#endif
<|endoftext|>


<commit_before>//===- llvm-xray.cc - XRay Tool Main Program ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the main entry point for the suite of XRay tools. All
// additional functionality are implemented as subcommands.
//
//===----------------------------------------------------------------------===//
//
// Basic usage:
//
//   llvm-xray [options] <subcommand> [subcommand-specific options]
//
#include "xray-registry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <unistd.h>

using namespace llvm;
using namespace llvm::xray;

int main(int argc, char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv,
                              "XRay Tools\n\n"
                              "  This program consolidates multiple XRay trace "
                              "processing tools for convenient access.\n");
  for (auto *SC : cl::getRegisteredSubcommands()) {
    if (*SC)
      if (auto C = dispatch(SC)) {
        ExitOnError("llvm-xray: ")(C());
        return 0;
      }
  }

  cl::PrintHelpMessage(false, true);
}
<commit_msg>[XRay] Remove unnecessary include of <unistd.h><commit_after>//===- llvm-xray.cc - XRay Tool Main Program ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the main entry point for the suite of XRay tools. All
// additional functionality are implemented as subcommands.
//
//===----------------------------------------------------------------------===//
//
// Basic usage:
//
//   llvm-xray [options] <subcommand> [subcommand-specific options]
//
#include "xray-registry.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace llvm::xray;

int main(int argc, char *argv[]) {
  cl::ParseCommandLineOptions(argc, argv,
                              "XRay Tools\n\n"
                              "  This program consolidates multiple XRay trace "
                              "processing tools for convenient access.\n");
  for (auto *SC : cl::getRegisteredSubcommands()) {
    if (*SC)
      if (auto C = dispatch(SC)) {
        ExitOnError("llvm-xray: ")(C());
        return 0;
      }
  }

  cl::PrintHelpMessage(false, true);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cartographer/mapping/3d/submap_3d.h"

#include <cmath>
#include <limits>

#include "cartographer/common/math.h"
#include "cartographer/sensor/range_data.h"
#include "glog/logging.h"

namespace cartographer {
namespace mapping {
namespace {

struct PixelData {
  int min_z = INT_MAX;
  int max_z = INT_MIN;
  int count = 0;
  float probability_sum = 0.f;
  float max_probability = 0.5f;
};

// Filters 'range_data', retaining only the returns that have no more than
// 'max_range' distance from the origin. Removes misses and reflectivity
// information.
sensor::RangeData FilterRangeDataByMaxRange(const sensor::RangeData& range_data,
                                            const float max_range) {
  sensor::RangeData result{range_data.origin, {}, {}};
  for (const Eigen::Vector3f& hit : range_data.returns) {
    if ((hit - range_data.origin).norm() <= max_range) {
      result.returns.push_back(hit);
    }
  }
  return result;
}

std::vector<PixelData> AccumulatePixelData(
    const int width, const int height, const Eigen::Array2i& min_index,
    const Eigen::Array2i& max_index,
    const std::vector<Eigen::Array4i>& voxel_indices_and_probabilities) {
  std::vector<PixelData> accumulated_pixel_data(width * height);
  for (const Eigen::Array4i& voxel_index_and_probability :
       voxel_indices_and_probabilities) {
    const Eigen::Array2i pixel_index = voxel_index_and_probability.head<2>();
    if ((pixel_index < min_index).any() || (pixel_index > max_index).any()) {
      // Out of bounds. This could happen because of floating point inaccuracy.
      continue;
    }
    const int x = max_index.x() - pixel_index[0];
    const int y = max_index.y() - pixel_index[1];
    PixelData& pixel = accumulated_pixel_data[x * width + y];
    ++pixel.count;
    pixel.min_z = std::min(pixel.min_z, voxel_index_and_probability[2]);
    pixel.max_z = std::max(pixel.max_z, voxel_index_and_probability[2]);
    const float probability =
        ValueToProbability(voxel_index_and_probability[3]);
    pixel.probability_sum += probability;
    pixel.max_probability = std::max(pixel.max_probability, probability);
  }
  return accumulated_pixel_data;
}

// The first three entries of each returned value are a cell_index and the
// last is the corresponding probability value. We batch them together like
// this to only have one vector and have better cache locality.
std::vector<Eigen::Array4i> ExtractVoxelData(
    const HybridGrid& hybrid_grid, const transform::Rigid3f& transform,
    Eigen::Array2i* min_index, Eigen::Array2i* max_index) {
  std::vector<Eigen::Array4i> voxel_indices_and_probabilities;
  const float resolution_inverse = 1.f / hybrid_grid.resolution();

  constexpr float kXrayObstructedCellProbabilityLimit = 0.501f;
  for (auto it = HybridGrid::Iterator(hybrid_grid); !it.Done(); it.Next()) {
    const uint16 probability_value = it.GetValue();
    const float probability = ValueToProbability(probability_value);
    if (probability < kXrayObstructedCellProbabilityLimit) {
      // We ignore non-obstructed cells.
      continue;
    }

    const Eigen::Vector3f cell_center_submap =
        hybrid_grid.GetCenterOfCell(it.GetCellIndex());
    const Eigen::Vector3f cell_center_global = transform * cell_center_submap;
    const Eigen::Array4i voxel_index_and_probability(
        common::RoundToInt(cell_center_global.x() * resolution_inverse),
        common::RoundToInt(cell_center_global.y() * resolution_inverse),
        common::RoundToInt(cell_center_global.z() * resolution_inverse),
        probability_value);

    voxel_indices_and_probabilities.push_back(voxel_index_and_probability);
    const Eigen::Array2i pixel_index = voxel_index_and_probability.head<2>();
    *min_index = min_index->cwiseMin(pixel_index);
    *max_index = max_index->cwiseMax(pixel_index);
  }
  return voxel_indices_and_probabilities;
}

// Builds texture data containing interleaved value and alpha for the
// visualization from 'accumulated_pixel_data'.
std::string ComputePixelValues(
    const std::vector<PixelData>& accumulated_pixel_data) {
  std::string cell_data;
  cell_data.reserve(2 * accumulated_pixel_data.size());
  constexpr float kMinZDifference = 3.f;
  constexpr float kFreeSpaceWeight = 0.15f;
  for (const PixelData& pixel : accumulated_pixel_data) {
    // TODO(whess): Take into account submap rotation.
    // TODO(whess): Document the approach and make it more independent from the
    // chosen resolution.
    const float z_difference = pixel.count > 0 ? pixel.max_z - pixel.min_z : 0;
    if (z_difference < kMinZDifference) {
      cell_data.push_back(0);  // value
      cell_data.push_back(0);  // alpha
      continue;
    }
    const float free_space = std::max(z_difference - pixel.count, 0.f);
    const float free_space_weight = kFreeSpaceWeight * free_space;
    const float total_weight = pixel.count + free_space_weight;
    const float free_space_probability = 1.f - pixel.max_probability;
    const float average_probability = ClampProbability(
        (pixel.probability_sum + free_space_probability * free_space_weight) /
        total_weight);
    const int delta = 128 - ProbabilityToLogOddsInteger(average_probability);
    const uint8 alpha = delta > 0 ? 0 : -delta;
    const uint8 value = delta > 0 ? delta : 0;
    cell_data.push_back(value);                         // value
    cell_data.push_back((value || alpha) ? alpha : 1);  // alpha
  }
  return cell_data;
}

void AddToTextureProto(
    const HybridGrid& hybrid_grid, const transform::Rigid3d& global_submap_pose,
    proto::SubmapQuery::Response::SubmapTexture* const texture) {
  // Generate an X-ray view through the 'hybrid_grid', aligned to the
  // xy-plane in the global map frame.
  const float resolution = hybrid_grid.resolution();
  texture->set_resolution(resolution);

  // Compute a bounding box for the texture.
  Eigen::Array2i min_index(INT_MAX, INT_MAX);
  Eigen::Array2i max_index(INT_MIN, INT_MIN);
  const std::vector<Eigen::Array4i> voxel_indices_and_probabilities =
      ExtractVoxelData(hybrid_grid, global_submap_pose.cast<float>(),
                       &min_index, &max_index);

  const int width = max_index.y() - min_index.y() + 1;
  const int height = max_index.x() - min_index.x() + 1;
  texture->set_width(width);
  texture->set_height(height);

  const std::vector<PixelData> accumulated_pixel_data = AccumulatePixelData(
      width, height, min_index, max_index, voxel_indices_and_probabilities);
  const std::string cell_data = ComputePixelValues(accumulated_pixel_data);

  common::FastGzipString(cell_data, texture->mutable_cells());
  *texture->mutable_slice_pose() = transform::ToProto(
      global_submap_pose.inverse() *
      transform::Rigid3d::Translation(Eigen::Vector3d(
          max_index.x() * resolution, max_index.y() * resolution,
          global_submap_pose.translation().z())));
}

}  // namespace

proto::SubmapsOptions3D CreateSubmapsOptions3D(
    common::LuaParameterDictionary* parameter_dictionary) {
  proto::SubmapsOptions3D options;
  options.set_high_resolution(
      parameter_dictionary->GetDouble("high_resolution"));
  options.set_high_resolution_max_range(
      parameter_dictionary->GetDouble("high_resolution_max_range"));
  options.set_low_resolution(parameter_dictionary->GetDouble("low_resolution"));
  options.set_num_range_data(
      parameter_dictionary->GetNonNegativeInt("num_range_data"));
  *options.mutable_range_data_inserter_options() =
      CreateRangeDataInserterOptions3D(
          parameter_dictionary->GetDictionary("range_data_inserter").get());
  CHECK_GT(options.num_range_data(), 0);
  return options;
}

Submap3D::Submap3D(const float high_resolution, const float low_resolution,
                   const transform::Rigid3d& local_submap_pose)
    : Submap(local_submap_pose),
      high_resolution_hybrid_grid_(
          common::make_unique<HybridGrid>(high_resolution)),
      low_resolution_hybrid_grid_(
          common::make_unique<HybridGrid>(low_resolution)) {}

Submap3D::Submap3D(const proto::Submap3D& proto)
    : Submap(transform::ToRigid3(proto.local_pose())) {
  UpdateFromProto(proto);
}

proto::Submap Submap3D::ToProto(
    const bool include_probability_grid_data) const {
  proto::Submap proto;
  auto* const submap_3d = proto.mutable_submap_3d();
  *submap_3d->mutable_local_pose() = transform::ToProto(local_pose());
  submap_3d->set_num_range_data(num_range_data());
  submap_3d->set_finished(finished());
  if (include_probability_grid_data) {
    *submap_3d->mutable_high_resolution_hybrid_grid() =
        high_resolution_hybrid_grid().ToProto();
    *submap_3d->mutable_low_resolution_hybrid_grid() =
        low_resolution_hybrid_grid().ToProto();
  }
  return proto;
}

void Submap3D::UpdateFromProto(const proto::Submap& proto) {
  CHECK(proto.has_submap_3d());
  UpdateFromProto(proto.submap_3d());
}

void Submap3D::UpdateFromProto(const proto::Submap3D& submap_3d) {
  set_num_range_data(submap_3d.num_range_data());
  set_finished(submap_3d.finished());
  if (submap_3d.has_high_resolution_hybrid_grid()) {
    high_resolution_hybrid_grid_ =
        submap_3d.has_high_resolution_hybrid_grid()
            ? common::make_unique<HybridGrid>(
                  submap_3d.high_resolution_hybrid_grid())
            : nullptr;
  }
  if (submap_3d.has_low_resolution_hybrid_grid()) {
    low_resolution_hybrid_grid_ =
        submap_3d.has_low_resolution_hybrid_grid()
            ? common::make_unique<HybridGrid>(
                  submap_3d.low_resolution_hybrid_grid())
            : nullptr;
  }
}

void Submap3D::ToResponseProto(
    const transform::Rigid3d& global_submap_pose,
    proto::SubmapQuery::Response* const response) const {
  response->set_submap_version(num_range_data());

  AddToTextureProto(*high_resolution_hybrid_grid_, global_submap_pose,
                    response->add_textures());
  AddToTextureProto(*low_resolution_hybrid_grid_, global_submap_pose,
                    response->add_textures());
}

void Submap3D::InsertRangeData(const sensor::RangeData& range_data,
                               const RangeDataInserter3D& range_data_inserter,
                               const float high_resolution_max_range) {
  CHECK(!finished());
  const sensor::RangeData transformed_range_data = sensor::TransformRangeData(
      range_data, local_pose().inverse().cast<float>());
  range_data_inserter.Insert(
      FilterRangeDataByMaxRange(transformed_range_data,
                                high_resolution_max_range),
      high_resolution_hybrid_grid_.get());
  range_data_inserter.Insert(transformed_range_data,
                             low_resolution_hybrid_grid_.get());
  set_num_range_data(num_range_data() + 1);
}

void Submap3D::Finish() {
  CHECK(!finished());
  set_finished(true);
}

ActiveSubmaps3D::ActiveSubmaps3D(const proto::SubmapsOptions3D& options)
    : options_(options),
      range_data_inserter_(options.range_data_inserter_options()) {}

std::vector<std::shared_ptr<const Submap3D>> ActiveSubmaps3D::submaps() const {
  return std::vector<std::shared_ptr<const Submap3D>>(submaps_.begin(),
                                                      submaps_.end());
}

std::vector<std::shared_ptr<const Submap3D>> ActiveSubmaps3D::InsertRangeData(
    const sensor::RangeData& range_data,
    const Eigen::Quaterniond& gravity_alignment) {
  if (submaps_.empty() ||
      submaps_.back()->num_range_data() == options_.num_range_data()) {
    AddSubmap(transform::Rigid3d(range_data.origin.cast<double>(),
                                 gravity_alignment));
  }
  for (auto& submap : submaps_) {
    submap->InsertRangeData(range_data, range_data_inserter_,
                            options_.high_resolution_max_range());
  }
  if (submaps_.front()->num_range_data() == 2 * options_.num_range_data()) {
    submaps_.front()->Finish();
  }
  return submaps();
}

void ActiveSubmaps3D::AddSubmap(const transform::Rigid3d& local_submap_pose) {
  if (submaps_.size() >= 2) {
    // This will crop the finished Submap before inserting a new Submap to
    // reduce peak memory usage a bit.
    CHECK(submaps_.front()->finished());
    submaps_.erase(submaps_.begin());
  }
  submaps_.emplace_back(new Submap3D(options_.high_resolution(),
                                     options_.low_resolution(),
                                     local_submap_pose));
}

}  // namespace mapping
}  // namespace cartographer
<commit_msg>removed redundant condition (#1344)<commit_after>/*
 * Copyright 2016 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cartographer/mapping/3d/submap_3d.h"

#include <cmath>
#include <limits>

#include "cartographer/common/math.h"
#include "cartographer/sensor/range_data.h"
#include "glog/logging.h"

namespace cartographer {
namespace mapping {
namespace {

struct PixelData {
  int min_z = INT_MAX;
  int max_z = INT_MIN;
  int count = 0;
  float probability_sum = 0.f;
  float max_probability = 0.5f;
};

// Filters 'range_data', retaining only the returns that have no more than
// 'max_range' distance from the origin. Removes misses and reflectivity
// information.
sensor::RangeData FilterRangeDataByMaxRange(const sensor::RangeData& range_data,
                                            const float max_range) {
  sensor::RangeData result{range_data.origin, {}, {}};
  for (const Eigen::Vector3f& hit : range_data.returns) {
    if ((hit - range_data.origin).norm() <= max_range) {
      result.returns.push_back(hit);
    }
  }
  return result;
}

std::vector<PixelData> AccumulatePixelData(
    const int width, const int height, const Eigen::Array2i& min_index,
    const Eigen::Array2i& max_index,
    const std::vector<Eigen::Array4i>& voxel_indices_and_probabilities) {
  std::vector<PixelData> accumulated_pixel_data(width * height);
  for (const Eigen::Array4i& voxel_index_and_probability :
       voxel_indices_and_probabilities) {
    const Eigen::Array2i pixel_index = voxel_index_and_probability.head<2>();
    if ((pixel_index < min_index).any() || (pixel_index > max_index).any()) {
      // Out of bounds. This could happen because of floating point inaccuracy.
      continue;
    }
    const int x = max_index.x() - pixel_index[0];
    const int y = max_index.y() - pixel_index[1];
    PixelData& pixel = accumulated_pixel_data[x * width + y];
    ++pixel.count;
    pixel.min_z = std::min(pixel.min_z, voxel_index_and_probability[2]);
    pixel.max_z = std::max(pixel.max_z, voxel_index_and_probability[2]);
    const float probability =
        ValueToProbability(voxel_index_and_probability[3]);
    pixel.probability_sum += probability;
    pixel.max_probability = std::max(pixel.max_probability, probability);
  }
  return accumulated_pixel_data;
}

// The first three entries of each returned value are a cell_index and the
// last is the corresponding probability value. We batch them together like
// this to only have one vector and have better cache locality.
std::vector<Eigen::Array4i> ExtractVoxelData(
    const HybridGrid& hybrid_grid, const transform::Rigid3f& transform,
    Eigen::Array2i* min_index, Eigen::Array2i* max_index) {
  std::vector<Eigen::Array4i> voxel_indices_and_probabilities;
  const float resolution_inverse = 1.f / hybrid_grid.resolution();

  constexpr float kXrayObstructedCellProbabilityLimit = 0.501f;
  for (auto it = HybridGrid::Iterator(hybrid_grid); !it.Done(); it.Next()) {
    const uint16 probability_value = it.GetValue();
    const float probability = ValueToProbability(probability_value);
    if (probability < kXrayObstructedCellProbabilityLimit) {
      // We ignore non-obstructed cells.
      continue;
    }

    const Eigen::Vector3f cell_center_submap =
        hybrid_grid.GetCenterOfCell(it.GetCellIndex());
    const Eigen::Vector3f cell_center_global = transform * cell_center_submap;
    const Eigen::Array4i voxel_index_and_probability(
        common::RoundToInt(cell_center_global.x() * resolution_inverse),
        common::RoundToInt(cell_center_global.y() * resolution_inverse),
        common::RoundToInt(cell_center_global.z() * resolution_inverse),
        probability_value);

    voxel_indices_and_probabilities.push_back(voxel_index_and_probability);
    const Eigen::Array2i pixel_index = voxel_index_and_probability.head<2>();
    *min_index = min_index->cwiseMin(pixel_index);
    *max_index = max_index->cwiseMax(pixel_index);
  }
  return voxel_indices_and_probabilities;
}

// Builds texture data containing interleaved value and alpha for the
// visualization from 'accumulated_pixel_data'.
std::string ComputePixelValues(
    const std::vector<PixelData>& accumulated_pixel_data) {
  std::string cell_data;
  cell_data.reserve(2 * accumulated_pixel_data.size());
  constexpr float kMinZDifference = 3.f;
  constexpr float kFreeSpaceWeight = 0.15f;
  for (const PixelData& pixel : accumulated_pixel_data) {
    // TODO(whess): Take into account submap rotation.
    // TODO(whess): Document the approach and make it more independent from the
    // chosen resolution.
    const float z_difference = pixel.count > 0 ? pixel.max_z - pixel.min_z : 0;
    if (z_difference < kMinZDifference) {
      cell_data.push_back(0);  // value
      cell_data.push_back(0);  // alpha
      continue;
    }
    const float free_space = std::max(z_difference - pixel.count, 0.f);
    const float free_space_weight = kFreeSpaceWeight * free_space;
    const float total_weight = pixel.count + free_space_weight;
    const float free_space_probability = 1.f - pixel.max_probability;
    const float average_probability = ClampProbability(
        (pixel.probability_sum + free_space_probability * free_space_weight) /
        total_weight);
    const int delta = 128 - ProbabilityToLogOddsInteger(average_probability);
    const uint8 alpha = delta > 0 ? 0 : -delta;
    const uint8 value = delta > 0 ? delta : 0;
    cell_data.push_back(value);                         // value
    cell_data.push_back((value || alpha) ? alpha : 1);  // alpha
  }
  return cell_data;
}

void AddToTextureProto(
    const HybridGrid& hybrid_grid, const transform::Rigid3d& global_submap_pose,
    proto::SubmapQuery::Response::SubmapTexture* const texture) {
  // Generate an X-ray view through the 'hybrid_grid', aligned to the
  // xy-plane in the global map frame.
  const float resolution = hybrid_grid.resolution();
  texture->set_resolution(resolution);

  // Compute a bounding box for the texture.
  Eigen::Array2i min_index(INT_MAX, INT_MAX);
  Eigen::Array2i max_index(INT_MIN, INT_MIN);
  const std::vector<Eigen::Array4i> voxel_indices_and_probabilities =
      ExtractVoxelData(hybrid_grid, global_submap_pose.cast<float>(),
                       &min_index, &max_index);

  const int width = max_index.y() - min_index.y() + 1;
  const int height = max_index.x() - min_index.x() + 1;
  texture->set_width(width);
  texture->set_height(height);

  const std::vector<PixelData> accumulated_pixel_data = AccumulatePixelData(
      width, height, min_index, max_index, voxel_indices_and_probabilities);
  const std::string cell_data = ComputePixelValues(accumulated_pixel_data);

  common::FastGzipString(cell_data, texture->mutable_cells());
  *texture->mutable_slice_pose() = transform::ToProto(
      global_submap_pose.inverse() *
      transform::Rigid3d::Translation(Eigen::Vector3d(
          max_index.x() * resolution, max_index.y() * resolution,
          global_submap_pose.translation().z())));
}

}  // namespace

proto::SubmapsOptions3D CreateSubmapsOptions3D(
    common::LuaParameterDictionary* parameter_dictionary) {
  proto::SubmapsOptions3D options;
  options.set_high_resolution(
      parameter_dictionary->GetDouble("high_resolution"));
  options.set_high_resolution_max_range(
      parameter_dictionary->GetDouble("high_resolution_max_range"));
  options.set_low_resolution(parameter_dictionary->GetDouble("low_resolution"));
  options.set_num_range_data(
      parameter_dictionary->GetNonNegativeInt("num_range_data"));
  *options.mutable_range_data_inserter_options() =
      CreateRangeDataInserterOptions3D(
          parameter_dictionary->GetDictionary("range_data_inserter").get());
  CHECK_GT(options.num_range_data(), 0);
  return options;
}

Submap3D::Submap3D(const float high_resolution, const float low_resolution,
                   const transform::Rigid3d& local_submap_pose)
    : Submap(local_submap_pose),
      high_resolution_hybrid_grid_(
          common::make_unique<HybridGrid>(high_resolution)),
      low_resolution_hybrid_grid_(
          common::make_unique<HybridGrid>(low_resolution)) {}

Submap3D::Submap3D(const proto::Submap3D& proto)
    : Submap(transform::ToRigid3(proto.local_pose())) {
  UpdateFromProto(proto);
}

proto::Submap Submap3D::ToProto(
    const bool include_probability_grid_data) const {
  proto::Submap proto;
  auto* const submap_3d = proto.mutable_submap_3d();
  *submap_3d->mutable_local_pose() = transform::ToProto(local_pose());
  submap_3d->set_num_range_data(num_range_data());
  submap_3d->set_finished(finished());
  if (include_probability_grid_data) {
    *submap_3d->mutable_high_resolution_hybrid_grid() =
        high_resolution_hybrid_grid().ToProto();
    *submap_3d->mutable_low_resolution_hybrid_grid() =
        low_resolution_hybrid_grid().ToProto();
  }
  return proto;
}

void Submap3D::UpdateFromProto(const proto::Submap& proto) {
  CHECK(proto.has_submap_3d());
  UpdateFromProto(proto.submap_3d());
}

void Submap3D::UpdateFromProto(const proto::Submap3D& submap_3d) {
  set_num_range_data(submap_3d.num_range_data());
  set_finished(submap_3d.finished());
  if (submap_3d.has_high_resolution_hybrid_grid()) {
    high_resolution_hybrid_grid_ = common::make_unique<HybridGrid>(
        submap_3d.high_resolution_hybrid_grid());
  }
  if (submap_3d.has_low_resolution_hybrid_grid()) {
    low_resolution_hybrid_grid_ =
        common::make_unique<HybridGrid>(submap_3d.low_resolution_hybrid_grid());
  }
}

void Submap3D::ToResponseProto(
    const transform::Rigid3d& global_submap_pose,
    proto::SubmapQuery::Response* const response) const {
  response->set_submap_version(num_range_data());

  AddToTextureProto(*high_resolution_hybrid_grid_, global_submap_pose,
                    response->add_textures());
  AddToTextureProto(*low_resolution_hybrid_grid_, global_submap_pose,
                    response->add_textures());
}

void Submap3D::InsertRangeData(const sensor::RangeData& range_data,
                               const RangeDataInserter3D& range_data_inserter,
                               const float high_resolution_max_range) {
  CHECK(!finished());
  const sensor::RangeData transformed_range_data = sensor::TransformRangeData(
      range_data, local_pose().inverse().cast<float>());
  range_data_inserter.Insert(
      FilterRangeDataByMaxRange(transformed_range_data,
                                high_resolution_max_range),
      high_resolution_hybrid_grid_.get());
  range_data_inserter.Insert(transformed_range_data,
                             low_resolution_hybrid_grid_.get());
  set_num_range_data(num_range_data() + 1);
}

void Submap3D::Finish() {
  CHECK(!finished());
  set_finished(true);
}

ActiveSubmaps3D::ActiveSubmaps3D(const proto::SubmapsOptions3D& options)
    : options_(options),
      range_data_inserter_(options.range_data_inserter_options()) {}

std::vector<std::shared_ptr<const Submap3D>> ActiveSubmaps3D::submaps() const {
  return std::vector<std::shared_ptr<const Submap3D>>(submaps_.begin(),
                                                      submaps_.end());
}

std::vector<std::shared_ptr<const Submap3D>> ActiveSubmaps3D::InsertRangeData(
    const sensor::RangeData& range_data,
    const Eigen::Quaterniond& gravity_alignment) {
  if (submaps_.empty() ||
      submaps_.back()->num_range_data() == options_.num_range_data()) {
    AddSubmap(transform::Rigid3d(range_data.origin.cast<double>(),
                                 gravity_alignment));
  }
  for (auto& submap : submaps_) {
    submap->InsertRangeData(range_data, range_data_inserter_,
                            options_.high_resolution_max_range());
  }
  if (submaps_.front()->num_range_data() == 2 * options_.num_range_data()) {
    submaps_.front()->Finish();
  }
  return submaps();
}

void ActiveSubmaps3D::AddSubmap(const transform::Rigid3d& local_submap_pose) {
  if (submaps_.size() >= 2) {
    // This will crop the finished Submap before inserting a new Submap to
    // reduce peak memory usage a bit.
    CHECK(submaps_.front()->finished());
    submaps_.erase(submaps_.begin());
  }
  submaps_.emplace_back(new Submap3D(options_.high_resolution(),
                                     options_.low_resolution(),
                                     local_submap_pose));
}

}  // namespace mapping
}  // namespace cartographer
<|endoftext|>


<commit_before>#pragma once

#include <memory>

namespace wonder_rabbit_project
{
  namespace message
  {
    class sender_t
    {
      std::weak_ptr<sender_t> _this_weak_ptr;
    public:
      using type     = sender_t;
      using shared_t = std::shared_ptr<type>;

      auto send_message
      ( const reciever_t::shared_t&    target_reciever
      , const message_t::functor_t&    functor         = message_t::nothing_functor()
      , const message_t::predicator_t& predicator      = message_t::true_predicator()
      , const message_t::launch_e      launch          = message_t::launch_e::async
      )
        -> void
      {
        auto message = std::make_shared<message_t>
          ( functor
          , predicator
          , launch
          );

        target_reciever -> recieve_message(std::move(message));
      }
    };
  }
}<commit_msg>fix #4 change send_message as sync, add post_message as async messaging<commit_after>#pragma once

#include <memory>

namespace wonder_rabbit_project
{
  namespace message
  {
    class sender_t
    {
      std::weak_ptr<sender_t> _this_weak_ptr;

      auto _send_or_post_message
      ( const reciever_t::shared_t&    target_reciever
      , const message_t::functor_t&    functor         = message_t::nothing_functor()
      , const message_t::predicator_t& predicator      = message_t::true_predicator()
      , const message_t::launch_e      launch          = message_t::launch_e::sync
      )
        -> void
      {
        auto message = std::make_shared<message_t>
          ( functor
          , predicator
          , launch
          );

        target_reciever -> recieve_message(std::move(message));
      }

    public:
      using type     = sender_t;
      using shared_t = std::shared_ptr<type>;

      auto send_message
      ( const reciever_t::shared_t&    target_reciever
      , const message_t::functor_t&    functor         = message_t::nothing_functor()
      , const message_t::predicator_t& predicator      = message_t::true_predicator()
      )
        -> void
      { _send_or_post_message(target_reciever, functor, predicator, message_t::launch_e::sync); }

      auto post_message
      ( const reciever_t::shared_t&    target_reciever
      , const message_t::functor_t&    functor         = message_t::nothing_functor()
      , const message_t::predicator_t& predicator      = message_t::true_predicator()
      , const message_t::launch_e      launch          = message_t::launch_e::async
      )
        -> void
     { _send_or_post_message(target_reciever, functor, predicator, message_t::launch_e::async); }

    };
  }
}<|endoftext|>


<commit_before>//
// Created by riku on 2016/07/19.
//
#include "HElib/Ctxt.h"
#include "HElib/EncryptedArray.h"
#include "HElib/timing.h"
#include "core/ctxt_util.hpp"
#include "core/coda.hpp"
#include "core/contingency_table.hpp"
#include "core/greaterthan.h"
#include <vector>
#include <thread>

#include <NTL/ZZ.h>
namespace core {
std::pair<size_t, size_t> coprime(size_t i, size_t j) {
    while (NTL::GCD(i, j) != 1) {
        if (i > j) j += 1;
        else i += 1;
    }
    return std::make_pair(i, j);
};

static Ctxt process(const Ctxt &one_record,
                    const Attribute &I,
                    const Attribute &J,
                    const EncryptedArray &ea) {
    auto modified_sizes = coprime(I.size, J.size);
    assert(modified_sizes.first * modified_sizes.second <= ea.size() && "Too large domain!");

    Ctxt attr_i(one_record), attr_j(one_record);
    ea.rotate(attr_i, -static_cast<long>(I.offset));
    ea.rotate(attr_j, -static_cast<long>(J.offset));

    mask_first(attr_i, modified_sizes.first, ea);
    mask_first(attr_j, modified_sizes.second, ea);
    attr_i = core::repeat0(attr_i, modified_sizes.first, modified_sizes.second, ea);
    attr_j = core::repeat0(attr_j, modified_sizes.second, modified_sizes.first, ea);

    attr_i *= attr_j;
    return attr_i;
}

static long InvMod(long a, long p) {
    long p0(p), t, q;
    long x0(0), x1(1);
    if (p == 1) return 1;
    while (a > 1) {
        q = a / p;
        t = p; p = a % p; a = t;
        t = x0; x0 = x1 - q * x0; x1 = t;
    }
    if (x1 < 0) x1 += p0;
    return x1;
}
// return x that x = u mod k1, x = v mod k2
long CRT(long u, long v, long k1, long k2) {
    assert(NTL::GCD(k1, k2) == 1);
    auto P = k1 * k2;
    return (u * InvMod(k2, k1) * k2 + v * InvMod(k1, k2) * k1) % P;
}

static NTL::ZZX make_I_x(long u, long v, long k1, long k2,
                         const EncryptedArray *ea) {
    std::vector<long> X(ea->size(), 0);
    X.at(CRT(u, v, k1, k2)) = 1;
    NTL::ZZX poly;
    ea->encode(poly, X);
    return poly;
}

PrivateContingencyTable
::PrivateContingencyTable(context_ptr context,
                          PrivateContingencyTableHelper *helper)
        : context(context), helper(helper) { }

std::shared_ptr<Ctxt>
PrivateContingencyTable::compute_table(const std::vector <Ctxt> &attributes,
                                       Attribute p, Attribute q,
                                       const EncryptedArray *ea) const {
    std::atomic<size_t> counter(0);
    std::mutex lock;
    size_t nr_ctxts = attributes.size();
    const auto &pk = attributes.front().getPubKey();
    std::shared_ptr<Ctxt> ct = std::make_shared<Ctxt>(pk);
    auto program = [&]() {
        size_t next;
        while (true) {
            next = counter.fetch_add(1UL);
            if (next >= nr_ctxts) break;
            auto tmp = process(attributes.at(next), p, q, *ea);
            lock.lock();
            ct->operator+=(tmp);
            lock.unlock();
        }
    };

    std::vector<std::thread> workers;
    for (auto wr = 0; wr < 1; wr++)
        workers.push_back(std::thread(program));
    for (auto &&wr : workers) wr.join();
    ct->reLinearize();
    return ct;
}

static std::vector<NTL::ZZX>
random_permutation_for_GT(size_t block_size, size_t copies,
                          long threshold, long domain_size,
                          const EncryptedArray *ea) {
    size_t usable_size = ea->size() / block_size * block_size;
    std::vector<long> I(domain_size);
    for (long i = 0; i < I.size(); i++) I.at(i) = -threshold - i;
    auto pr = ea->getAlMod().getPPowR();
    long dummy_random;
    do { dummy_random = NTL::RandomBnd(pr); } while(dummy_random == 0);

    std::vector<std::vector<long>> parts(copies, std::vector<long>(ea->size(), dummy_random));

    for (size_t b = 0; b < block_size; b++) {
        std::random_shuffle(I.begin(), I.end());
        for (size_t i = 0; i < domain_size; i++) {
            auto ii = i * block_size + b;
            auto idx_of_part = ii / usable_size;
            auto idx_in_part = ii % usable_size;
            parts.at(idx_of_part).at(idx_in_part) = I.at(i);
        }
    }

    std::vector<NTL::ZZX> rets(copies);
    for (size_t c = 0; c < copies; c++)
        ea->encode(rets.at(c), parts.at(c));
    return rets;
}

static std::vector<long>
random_hash_key(size_t block_size, size_t repeats, const EncryptedArray *ea) {
    size_t usable_size = ea->size() / block_size * block_size;
    std::vector<long> keys(ea->size());
    long pr = ea->getAlMod().getPPowR();
    for (size_t b = 0; b < block_size; b++) {
        keys.at(b) = NTL::RandomBnd(pr);
        for (size_t r = 1; r < repeats; r++)
            keys.at(b + r * block_size) = keys.at(b);
    }
    return keys;
}

static std::vector<NTL::ZZX>
randomness_for_GT(size_t copies, const EncryptedArray *ea) {
    auto random_sample = [](std::vector<long> &r, long pr) {
        for (size_t i = 0; i < r.size(); i++) {
            do {
                r.at(i) = NTL::RandomBnd(pr);
            } while (r.at(i) == 0);
        }
    };

    auto pr = ea->getAlMod().getPPowR();
    std::vector<long> randomness(ea->size());
    std::vector<NTL::ZZX> rets(copies);
    for (size_t c = 0; c < copies; c++) {
        random_sample(randomness, pr);
        random_sample(randomness, pr);
        ea->encode(rets.at(c), randomness);
    }

    return rets;
}

PrivateContingencyTable::ResultType::Type_gamma
PrivateContingencyTable::special_greater_than(ctxt_ptr CT, long domain_size,
                                              const EncryptedArray *ea) const {
    helper->setCT(CT.get());
    ctxt_ptr repeated = helper->repeat(domain_size);
    auto repeats = helper->repeats_per_cipher();
    auto copies = helper->how_many_copies(domain_size);
    auto parts = random_permutation_for_GT(helper->block_size(), copies,
                                           helper->getThreshold(), domain_size, ea);
    auto randomness = randomness_for_GT(copies, ea);

    ResultType::Type_gamma gamma;
    for (size_t i = 0; i < parts.size(); i++) {
        auto tmp = std::make_shared<Ctxt>(*repeated);
        tmp->addConstant(parts.at(i));
        tmp->multByConstant(randomness.at(i));
        gamma.push_back(tmp);
    }
    return gamma;
}

PrivateContingencyTable::ResultType::Type_gamma
PrivateContingencyTable::add_key_to_gamma(const ResultType::Type_gamma &gamma,
                                          const std::vector<long> &keys,
                                          long domain_size,
                                          const EncryptedArray *ea) const {
    ResultType::Type_gamma  tilde_gamma(gamma.size());
    NTL::ZZX poly;
    ea->encode(poly, keys);
    for (size_t i = 0; i < gamma.size(); i++) {
        tilde_gamma.at(i) = std::make_shared<Ctxt>(*gamma.at(i));
        tilde_gamma.at(i)->addConstant(poly);
    }
    return tilde_gamma;
}

PrivateContingencyTable::ResultType
PrivateContingencyTable::evaluate(const std::vector <Ctxt> &attributes) const {
    assert(!attributes.empty());
    const auto &pk = attributes.front().getPubKey();
    auto ea = context->ea;

    Attribute P = helper->getP();
    Attribute Q = helper->getQ();
    long domain_size = attributes.size();
    printf("repeat block size %zd for %zd times with %zd copies\n",
           helper->block_size(),
           helper->repeats_per_cipher(),
           helper->how_many_copies(domain_size));
    FHE_NTIMER_START(Conduction);
    auto contingency_table = compute_table(attributes, P, Q, ea);
    FHE_NTIMER_STOP(Conduction);

    FHE_NTIMER_START(GreaterThan);
    auto gamma = special_greater_than(contingency_table, domain_size, ea);
    FHE_NTIMER_STOP(GreaterThan);

    FHE_NTIMER_START(Blinding);
    auto keys = random_hash_key(helper->block_size(),
                                helper->repeats_per_cipher(), ea);
    auto tilde_gamma = add_key_to_gamma(gamma, keys, domain_size, ea);
    FHE_NTIMER_STOP(Blinding);

    return { .n_uv = std::vector<ctxt_ptr>(1, contingency_table), .gamma = gamma, .tilde_gamma = tilde_gamma };
}

size_t PrivateContingencyTableHelper::repeats_per_cipher() const {
    auto cont_table_size = block_size();
    assert(cont_table_size <= ea->size() && "One cipher can't contain the whole contingency table");
    return ea->size() / cont_table_size;
}

size_t PrivateContingencyTableHelper::how_many_copies(long domain_size) const {
    size_t repeats = repeats_per_cipher();
    return (domain_size + repeats - 1UL) / repeats;
}

size_t PrivateContingencyTableHelper::block_size() const {
    auto modified_size = coprime(P.size, Q.size);
    return modified_size.first * modified_size.second;
}

std::shared_ptr<Ctxt> PrivateContingencyTableHelper::repeat(size_t R) const {
    assert(CT != nullptr && "the CT haven't been set");
    size_t repeats = std::min(R, repeats_per_cipher());
    if (repeats != R)
        printf("Warning! hope to repeat %zd times but only get %zd\n", R, repeats);
    return std::make_shared<Ctxt>(core::repeat0(*CT, block_size(), repeats, *ea));
}

void PrivateContingencyTableHelper::open_gamma(std::vector<Publishable> &unsuppression,
                                               const Type_gamma &gamma,
                                               const Type_gamma &tilde_gamma,
                                               const EncryptedArray *ea,
                                               sk_ptr sk) {
    size_t bs = block_size();
    auto modified_sizes = coprime(P.size, Q.size);
    size_t usable_size = ea->size() / bs * bs;
    std::vector<long> decrypted(ea->size());
    std::vector<long> keys(ea->size());

    for (size_t i = 0; i < gamma.size(); i++) {
        if (!gamma.at(i)->isCorrect())
            printf("Warnning! might be an invalid cipher\n");
        ea->decrypt(*gamma.at(i), *sk, decrypted);
        ea->decrypt(*tilde_gamma.at(i), *sk, keys);
        for (size_t j = 0; j < usable_size; j++) {
            if (decrypted.at(j) != 0) continue;

            size_t u = j % modified_sizes.first;
            size_t v = j % modified_sizes.second;
            long hash_key = keys.at(j);
            Publishable info = {.u = u, .v = v, .hash_key = hash_key};
            unsuppression.push_back(info);
        }
    }
}
}

<commit_msg>better concurrency<commit_after>//
// Created by riku on 2016/07/19.
//
#include "HElib/Ctxt.h"
#include "HElib/EncryptedArray.h"
#include "HElib/timing.h"
#include "core/ctxt_util.hpp"
#include "core/coda.hpp"
#include "core/contingency_table.hpp"
#include "core/greaterthan.h"
#include <vector>
#include <thread>

#include <NTL/ZZ.h>

#ifdef FHE_THREADS
#define NR_THREADS 8
#else
#define NR_THREADS 1
#endif

namespace core {
std::pair<size_t, size_t> coprime(size_t i, size_t j) {
    while (NTL::GCD(i, j) != 1) {
        if (i > j) j += 1;
        else i += 1;
    }
    return std::make_pair(i, j);
};

static Ctxt process(const Ctxt &one_record,
                    const Attribute &I,
                    const Attribute &J,
                    const EncryptedArray &ea) {
    auto modified_sizes = coprime(I.size, J.size);
    assert(modified_sizes.first * modified_sizes.second <= ea.size() && "Too large domain!");

    Ctxt attr_i(one_record), attr_j(one_record);
    ea.rotate(attr_i, -static_cast<long>(I.offset));
    ea.rotate(attr_j, -static_cast<long>(J.offset));

    mask_first(attr_i, modified_sizes.first, ea);
    mask_first(attr_j, modified_sizes.second, ea);
    attr_i = core::repeat0(attr_i, modified_sizes.first, modified_sizes.second, ea);
    attr_j = core::repeat0(attr_j, modified_sizes.second, modified_sizes.first, ea);

    attr_i *= attr_j;
    return attr_i;
}

static long InvMod(long a, long p) {
    long p0(p), t, q;
    long x0(0), x1(1);
    if (p == 1) return 1;
    while (a > 1) {
        q = a / p;
        t = p; p = a % p; a = t;
        t = x0; x0 = x1 - q * x0; x1 = t;
    }
    if (x1 < 0) x1 += p0;
    return x1;
}
// return x that x = u mod k1, x = v mod k2
long CRT(long u, long v, long k1, long k2) {
    assert(NTL::GCD(k1, k2) == 1);
    auto P = k1 * k2;
    return (u * InvMod(k2, k1) * k2 + v * InvMod(k1, k2) * k1) % P;
}

static NTL::ZZX make_I_x(long u, long v, long k1, long k2,
                         const EncryptedArray *ea) {
    std::vector<long> X(ea->size(), 0);
    X.at(CRT(u, v, k1, k2)) = 1;
    NTL::ZZX poly;
    ea->encode(poly, X);
    return poly;
}

PrivateContingencyTable
::PrivateContingencyTable(context_ptr context,
                          PrivateContingencyTableHelper *helper)
        : context(context), helper(helper) { }

std::shared_ptr<Ctxt>
PrivateContingencyTable::compute_table(const std::vector <Ctxt> &attributes,
                                       Attribute p, Attribute q,
                                       const EncryptedArray *ea) const {
    std::atomic<size_t> counter(0);
    size_t nr_ctxts = attributes.size();
    const auto &pk = attributes.front().getPubKey();
    std::shared_ptr<Ctxt> ct = std::make_shared<Ctxt>(pk);
    std::vector<Ctxt> workers_space(NR_THREADS, pk);
    auto program = [&](const long worker_id) {
        size_t next;
        while (true) {
            next = counter.fetch_add(1UL);
            if (next >= nr_ctxts) break;
            auto tmp = process(attributes.at(next), p, q, *ea);
            workers_space.at(worker_id) += tmp;
        }
    };

    std::vector<std::thread> workers;
    for (auto wr = 0; wr < NR_THREADS; wr++)
        workers.push_back(std::thread(program, wr));
    for (auto &&wr : workers) wr.join();

    for (auto &tmp : workers_space)
        ct->operator+=(tmp);
    ct->reLinearize();
    return ct;
}

static std::vector<NTL::ZZX>
random_permutation_for_GT(size_t block_size, size_t copies,
                          long threshold, long domain_size,
                          const EncryptedArray *ea) {
    size_t usable_size = ea->size() / block_size * block_size;
    std::vector<long> I(domain_size);
    for (long i = 0; i < I.size(); i++) I.at(i) = -threshold - i;
    auto pr = ea->getAlMod().getPPowR();
    long dummy_random;
    do { dummy_random = NTL::RandomBnd(pr); } while(dummy_random == 0);

    std::vector<std::vector<long>> parts(copies, std::vector<long>(ea->size(), dummy_random));

    for (size_t b = 0; b < block_size; b++) {
        std::random_shuffle(I.begin(), I.end());
        for (size_t i = 0; i < domain_size; i++) {
            auto ii = i * block_size + b;
            auto idx_of_part = ii / usable_size;
            auto idx_in_part = ii % usable_size;
            parts.at(idx_of_part).at(idx_in_part) = I.at(i);
        }
    }

    std::vector<NTL::ZZX> rets(copies);
    for (size_t c = 0; c < copies; c++)
        ea->encode(rets.at(c), parts.at(c));
    return rets;
}

static std::vector<long>
random_hash_key(size_t block_size, size_t repeats, const EncryptedArray *ea) {
    size_t usable_size = ea->size() / block_size * block_size;
    std::vector<long> keys(ea->size());
    long pr = ea->getAlMod().getPPowR();
    for (size_t b = 0; b < block_size; b++) {
        keys.at(b) = NTL::RandomBnd(pr);
        for (size_t r = 1; r < repeats; r++)
            keys.at(b + r * block_size) = keys.at(b);
    }
    return keys;
}

static std::vector<NTL::ZZX>
randomness_for_GT(size_t copies, const EncryptedArray *ea) {
    auto random_sample = [](std::vector<long> &r, long pr) {
        for (size_t i = 0; i < r.size(); i++) {
            do {
                r.at(i) = NTL::RandomBnd(pr);
            } while (r.at(i) == 0);
        }
    };

    auto pr = ea->getAlMod().getPPowR();
    std::vector<long> randomness(ea->size());
    std::vector<NTL::ZZX> rets(copies);
    for (size_t c = 0; c < copies; c++) {
        random_sample(randomness, pr);
        random_sample(randomness, pr);
        ea->encode(rets.at(c), randomness);
    }

    return rets;
}

PrivateContingencyTable::ResultType::Type_gamma
PrivateContingencyTable::special_greater_than(ctxt_ptr CT, long domain_size,
                                              const EncryptedArray *ea) const {
    helper->setCT(CT.get());
    ctxt_ptr repeated = helper->repeat(domain_size);
    auto repeats = helper->repeats_per_cipher();
    auto copies = helper->how_many_copies(domain_size);
    auto parts = random_permutation_for_GT(helper->block_size(), copies,
                                           helper->getThreshold(), domain_size, ea);
    auto randomness = randomness_for_GT(copies, ea);

    ResultType::Type_gamma gamma;
    for (size_t i = 0; i < parts.size(); i++) {
        auto tmp = std::make_shared<Ctxt>(*repeated);
        tmp->addConstant(parts.at(i));
        tmp->multByConstant(randomness.at(i));
        gamma.push_back(tmp);
    }
    return gamma;
}

PrivateContingencyTable::ResultType::Type_gamma
PrivateContingencyTable::add_key_to_gamma(const ResultType::Type_gamma &gamma,
                                          const std::vector<long> &keys,
                                          long domain_size,
                                          const EncryptedArray *ea) const {
    ResultType::Type_gamma  tilde_gamma(gamma.size());
    NTL::ZZX poly;
    ea->encode(poly, keys);
    for (size_t i = 0; i < gamma.size(); i++) {
        tilde_gamma.at(i) = std::make_shared<Ctxt>(*gamma.at(i));
        tilde_gamma.at(i)->addConstant(poly);
    }
    return tilde_gamma;
}

PrivateContingencyTable::ResultType
PrivateContingencyTable::evaluate(const std::vector <Ctxt> &attributes) const {
    assert(!attributes.empty());
    const auto &pk = attributes.front().getPubKey();
    auto ea = context->ea;

    Attribute P = helper->getP();
    Attribute Q = helper->getQ();
    long domain_size = attributes.size();
    printf("repeat block size %zd for %zd times with %zd copies\n",
           helper->block_size(),
           helper->repeats_per_cipher(),
           helper->how_many_copies(domain_size));
    FHE_NTIMER_START(Conduction);
    auto contingency_table = compute_table(attributes, P, Q, ea);
    FHE_NTIMER_STOP(Conduction);

    FHE_NTIMER_START(GreaterThan);
    auto gamma = special_greater_than(contingency_table, domain_size, ea);
    FHE_NTIMER_STOP(GreaterThan);

    FHE_NTIMER_START(Blinding);
    auto keys = random_hash_key(helper->block_size(),
                                helper->repeats_per_cipher(), ea);
    auto tilde_gamma = add_key_to_gamma(gamma, keys, domain_size, ea);
    FHE_NTIMER_STOP(Blinding);

    return { .n_uv = std::vector<ctxt_ptr>(1, contingency_table), .gamma = gamma, .tilde_gamma = tilde_gamma };
}

size_t PrivateContingencyTableHelper::repeats_per_cipher() const {
    auto cont_table_size = block_size();
    assert(cont_table_size <= ea->size() && "One cipher can't contain the whole contingency table");
    return ea->size() / cont_table_size;
}

size_t PrivateContingencyTableHelper::how_many_copies(long domain_size) const {
    size_t repeats = repeats_per_cipher();
    return (domain_size + repeats - 1UL) / repeats;
}

size_t PrivateContingencyTableHelper::block_size() const {
    auto modified_size = coprime(P.size, Q.size);
    return modified_size.first * modified_size.second;
}

std::shared_ptr<Ctxt> PrivateContingencyTableHelper::repeat(size_t R) const {
    assert(CT != nullptr && "the CT haven't been set");
    size_t repeats = std::min(R, repeats_per_cipher());
    if (repeats != R)
        printf("Warning! hope to repeat %zd times but only get %zd\n", R, repeats);
    return std::make_shared<Ctxt>(core::repeat0(*CT, block_size(), repeats, *ea));
}

void PrivateContingencyTableHelper::open_gamma(std::vector<Publishable> &unsuppression,
                                               const Type_gamma &gamma,
                                               const Type_gamma &tilde_gamma,
                                               const EncryptedArray *ea,
                                               sk_ptr sk) {
    size_t bs = block_size();
    auto modified_sizes = coprime(P.size, Q.size);
    size_t usable_size = ea->size() / bs * bs;
    std::vector<long> decrypted(ea->size());
    std::vector<long> keys(ea->size());

    for (size_t i = 0; i < gamma.size(); i++) {
        if (!gamma.at(i)->isCorrect())
            printf("Warnning! might be an invalid cipher\n");
        ea->decrypt(*gamma.at(i), *sk, decrypted);
        ea->decrypt(*tilde_gamma.at(i), *sk, keys);
        for (size_t j = 0; j < usable_size; j++) {
            if (decrypted.at(j) != 0) continue;

            size_t u = j % modified_sizes.first;
            size_t v = j % modified_sizes.second;
            long hash_key = keys.at(j);
            Publishable info = {.u = u, .v = v, .hash_key = hash_key};
            unsuppression.push_back(info);
        }
    }
}
}

<|endoftext|>


<commit_before>/***************************************************************************
*   Copyright (C) 2005-2007 by the FIFE Team                              *
*   fife-public@lists.sourceforge.net                                     *
*   This file is part of FIFE.                                            *
*                                                                         *
*   FIFE is free software; you can redistribute it and/or modify          *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA              *
***************************************************************************/

// Standard C++ library includes
#include <stdio.h>
#include <iostream>
#include <cassert>

// 3rd party library includes
#include <boost/test/unit_test.hpp>
#include <lua.hpp>

// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "map/layer.h"
#include "map/objectinfo.h"
#include "map/factory.h"
#include "vfs/vfssourcefactory.h"
#include "vfs/vfs.h"
#include "settingsmanager.h"
#include "script/lua/lunar.h"
#include "exception.cpp"
#include "script/lua/lua_ref.h"

using boost::unit_test::test_suite;
using namespace FIFE::map;
using namespace FIFE;

class DemoObj {
	public:
#define method(name) {#name, DemoObj::name}

	DemoObj(lua_State *L) {
		std::cout << "instance created" << std::endl;
	}

	~DemoObj() {
		std::cout << "instance destroyed" << std::endl;
	}

	static const char className[];
	static Lunar<DemoObj>::RegType methods[];
};

const char DemoObj::className[] = "DemoObj";
Lunar<DemoObj>::RegType DemoObj::methods[] = {
	{NULL, NULL}
};

void lua_run(lua_State *L, const char* cmd_buf) {
	if (luaL_loadbuffer(L, cmd_buf, strlen(cmd_buf), "cmd") || lua_pcall(L, 0, 0, 0)) {
		std::cerr << "Error: " << lua_tostring(L, 1) << std::endl;
		lua_pop(L, 1);
		exit(1);
	}
}

struct environment {
	lua_State * state;
	environment() {
		state = lua_open();
		luaL_openlibs(state);
		Lunar<DemoObj>::Register(state);
	}
	~environment() {
		lua_close(state);
	}
};

void simple_test()
{
	environment env;
	lua_State *L = env.state;

	const char * cmd_buf = "foo = DemoObj()";

	lua_run(L, cmd_buf);

	lua_getglobal(L, "foo");
	BOOST_CHECK( lua_isuserdata(L, 1) );

	BOOST_CHECK( lua_gettop(L) == 1 );

	LuaRef luaref;
	luaref.ref(L, 1);
	lua_pop(L, 1);

	BOOST_CHECK( lua_gettop(L) == 0);

	lua_run(L, "_G[\"foo\"] = nil");
// 	std::cout << lua_gc(L, LUA_GCCOUNT, 0) << lua_gc(L, LUA_GCCOUNTB, 0) << "B\n";
	lua_gc(L, LUA_GCCOLLECT, 0);
// 	std::cout << lua_gc(L, LUA_GCCOUNT, 0) << lua_gc(L, LUA_GCCOUNTB, 0) << "B\n";
	luaref.unref();
	lua_gc(L, LUA_GCCOLLECT, 0);
// 	std::cout << lua_gc(L, LUA_GCCOUNT, 0) << lua_gc(L, LUA_GCCOUNTB, 0) << "B\n";
	lua_run(L, cmd_buf);
	luaref.ref(L, 1);
	lua_pop(L, 1);
	LuaRef::unrefAll(L);
	BOOST_CHECK( !luaref.isValid() );
}

void anonymous_function_test() {
	environment env;
	lua_State *L = env.state;

	LuaRef luaref;
	lua_run(L, "foo = function() print(\"Lambda called.\") end");
	lua_getglobal(L,"foo");
	luaref.ref(L,1);
	lua_pop(L,1);
	lua_run(L, "_G[\"foo\"] = nil");
	BOOST_CHECK( lua_gettop(L) == 0);
	lua_gc(L, LUA_GCCOLLECT, 0);

	lua_getglobal(L,"foo");
	BOOST_CHECK( lua_isnil(L, 1) );
	lua_pop(L,1);

	luaref.push();
	BOOST_CHECK( lua_isfunction(L, 1) );
	lua_call(L,0,0); // Should print the message

	LuaRef::unrefAll(L);
}

test_suite* init_unit_test_suite(int argc, char** argv) {
	test_suite* test = BOOST_TEST_SUITE("Lua Ref tests");
	test->add(BOOST_TEST_CASE(&simple_test), 0);
	test->add(BOOST_TEST_CASE(&anonymous_function_test), 0);
	return test;
}
<commit_msg>Added another LuaRef test case two proove that holding two references works as expected.<commit_after>/***************************************************************************
*   Copyright (C) 2005-2007 by the FIFE Team                              *
*   fife-public@lists.sourceforge.net                                     *
*   This file is part of FIFE.                                            *
*                                                                         *
*   FIFE is free software; you can redistribute it and/or modify          *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA              *
***************************************************************************/

// Standard C++ library includes
#include <stdio.h>
#include <iostream>
#include <cassert>

// 3rd party library includes
#include <boost/test/unit_test.hpp>
#include <lua.hpp>

// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "map/layer.h"
#include "map/objectinfo.h"
#include "map/factory.h"
#include "vfs/vfssourcefactory.h"
#include "vfs/vfs.h"
#include "settingsmanager.h"
#include "script/lua/lunar.h"
#include "exception.cpp"
#include "script/lua/lua_ref.h"

using boost::unit_test::test_suite;
using namespace FIFE::map;
using namespace FIFE;

class DemoObj {
	public:
#define method(name) {#name, DemoObj::name}

	DemoObj(lua_State *L) {
		std::cout << "instance created" << std::endl;
	}

	~DemoObj() {
		std::cout << "instance destroyed" << std::endl;
	}

	static const char className[];
	static Lunar<DemoObj>::RegType methods[];
};

const char DemoObj::className[] = "DemoObj";
Lunar<DemoObj>::RegType DemoObj::methods[] = {
	{NULL, NULL}
};

void lua_run(lua_State *L, const char* cmd_buf) {
	if (luaL_loadbuffer(L, cmd_buf, strlen(cmd_buf), "cmd") || lua_pcall(L, 0, 0, 0)) {
		std::cerr << "Error: " << lua_tostring(L, 1) << std::endl;
		lua_pop(L, 1);
		exit(1);
	}
}

struct environment {
	lua_State * state;
	environment() {
		state = lua_open();
		luaL_openlibs(state);
		Lunar<DemoObj>::Register(state);
	}
	~environment() {
		lua_close(state);
	}
};

void simple_test()
{
	// Check whether LuaRef gracefully handles
	// lua_close() though it's still held.

	environment env;
	lua_State *L = env.state;

	const char * cmd_buf = "foo = DemoObj()";

	lua_run(L, cmd_buf);

	lua_getglobal(L, "foo");
	BOOST_CHECK( lua_isuserdata(L, 1) );

	BOOST_CHECK( lua_gettop(L) == 1 );

	LuaRef luaref;
	luaref.ref(L, 1);
	lua_pop(L, 1);

	BOOST_CHECK( lua_gettop(L) == 0);

	lua_run(L, "_G[\"foo\"] = nil");
// 	std::cout << lua_gc(L, LUA_GCCOUNT, 0) << lua_gc(L, LUA_GCCOUNTB, 0) << "B\n";
	lua_gc(L, LUA_GCCOLLECT, 0);
// 	std::cout << lua_gc(L, LUA_GCCOUNT, 0) << lua_gc(L, LUA_GCCOUNTB, 0) << "B\n";
	luaref.unref();
	lua_gc(L, LUA_GCCOLLECT, 0);
// 	std::cout << lua_gc(L, LUA_GCCOUNT, 0) << lua_gc(L, LUA_GCCOUNTB, 0) << "B\n";
	lua_run(L, cmd_buf);
	luaref.ref(L, 1);
	lua_pop(L, 1);
	LuaRef::unrefAll(L);
	BOOST_CHECK( !luaref.isValid() );
}

void anonymous_function_test() {
	// Check whether LuaRef is suitable for callbacks.

	environment env;
	lua_State *L = env.state;

	LuaRef luaref;
	lua_run(L, "foo = function() print(\"Lambda call works.\") end");
	lua_getglobal(L,"foo");
	luaref.ref(L,1);
	lua_pop(L,1);
	lua_run(L, "_G[\"foo\"] = nil");
	BOOST_CHECK( lua_gettop(L) == 0);
	lua_gc(L, LUA_GCCOLLECT, 0);

	lua_getglobal(L,"foo");
	BOOST_CHECK( lua_isnil(L, 1) );
	lua_pop(L,1);

	luaref.push();
	BOOST_CHECK( lua_isfunction(L, 1) );
	lua_call(L,0,0); // Should print the message

	LuaRef::unrefAll(L);
}

void double_ref_test() {
	environment env;

	lua_State *L = env.state;

	LuaRef luaref[2];
	lua_run(L, "foo = function() print(\"Double references work.\") end");
	lua_getglobal(L,"foo");
	luaref[0].ref(L,1);
	luaref[1].ref(L,1);
	lua_pop(L,1);
	lua_run(L, "_G[\"foo\"] = nil");
	BOOST_CHECK( lua_gettop(L) == 0);
	lua_gc(L, LUA_GCCOLLECT, 0);

	luaref[0].unref();
	lua_gc(L, LUA_GCCOLLECT, 0);

	// Now one reference was released,
	// but 'foo' should still not be gc'ed.

	luaref[1].push();
	BOOST_CHECK( lua_isfunction(L, 1) );
	lua_call(L,0,0); // Should print the message

	LuaRef::unrefAll(L);
}

test_suite* init_unit_test_suite(int argc, char** argv) {
	test_suite* test = BOOST_TEST_SUITE("Lua Ref tests");
	test->add(BOOST_TEST_CASE(&simple_test), 0);
	test->add(BOOST_TEST_CASE(&anonymous_function_test), 0);
	test->add(BOOST_TEST_CASE(&double_ref_test), 0);
	return test;
}
<|endoftext|>