<commit_before>#include "util/bitmap.h"
#include "gui/widget.h"
#include <math.h>
#include "globals.h"
#include "util/token.h"
#include "gui/coordinate.h"

using namespace Gui;

static const double S_PI = 3.14159265358979323846;
static const double DEG_TO_RAD = 180.0/S_PI;
static const double RAD_TO_DEG = S_PI/180.0;

static void round_double (double dbl_to_round , int &rounded_num) {
		rounded_num = static_cast<int>(dbl_to_round);
		if ((dbl_to_round - static_cast<double>(rounded_num)) >= 0.5) {rounded_num++;}
	}

//! min (borrowed from allegro)
static inline int Min(int x, int y){ return (((x) < (y)) ? (x) : (y)); }

//! max (borrowed from allegro)
static inline int Max(int x, int y){ return (((x) > (y)) ? (x) : (y)); }

//! mid (borrowed from allegro)
static inline int Mid(int x,int y,int z){ return (Max((x), Min((y), (z)))); }

Widget::Widget() : workArea(0)
{
	// Nothing yet
}

Widget::Widget( const Widget & w ){
	this->location = w.location;
	this->workArea = w.workArea;
}

Widget::~Widget(){
	if ( workArea ){
		delete workArea;
	}
}

// copy
Widget &Widget::operator=( const Widget &copy){
	location = copy.location;
	workArea = copy.workArea;

	return *this;
}

void Widget::setCoordinates(Token * token){
    if ( *token == "position" ){
        int x, y, width, height;
        *token >> x >> y >> width >> height;
        AbsolutePoint pos(x, y);
        AbsolutePoint dimensions(x + width, y + height);
        location.setPosition(pos);
        location.setDimensions(dimensions);
    } else if ( *token == "relative-position" ){
        double x1, y1, x2, y2;
        *token >> x1 >> y1 >> x2 >> y2;
        RelativePoint pos(x1,y1);
        RelativePoint dimensions(x2,y2);
        location = Coordinate(pos, dimensions);
    } else if ( *token == "coordinate" ){
        while (token->hasTokens()){
            Token * coordToken;
            *token >> coordToken;
            if (*coordToken == "absolute"){
                int x, y, width, height;
                *coordToken >> x >> y >> width >> height;
                AbsolutePoint pos(x, y);
                AbsolutePoint dimensions(x + width, y + height);
                location = Coordinate(pos, dimensions);
            } else if (*coordToken == "relative"){
                double x1, y1, x2, y2;
                *coordToken >> x1 >> y1 >> x2 >> y2;
                RelativePoint pos(x1,y1);
                RelativePoint dimensions(x2,y2);
                location = Coordinate(pos, dimensions);
            } else if (*coordToken == "radius"){
                double radius;
                *coordToken >> radius;
                location.setRadius(radius);
            } else if (*coordToken == "z"){
                double z;
                *coordToken >> z;
                location.setZ(z);
            }
        }
    }
}

void Widget::setColors(Token * token){
    if ( *token == "position-body" ) {
        // This handles the body color of the widget
        int r,g,b;
        *token >> r >> g >> b >> colors.bodyAlpha;
        colors.body = Bitmap::makeColor(r,g,b);
    } else if ( *token == "position-border" ) {
        // This handles the border color of the widget
        int r,g,b;
        *token >> r >> g >> b >> colors.borderAlpha;
        colors.border = Bitmap::makeColor(r,g,b);
    }
}

void Widget::arc( const Bitmap & work, int x, int y, double startAngle, int radius, int color )
{
	int q = 0;// for counters
	double d_q = 0.0;// for percentage of loop completed
	double d_q_plus_one = 0.0;

	const double d_angular_length_deg = 0.030;
	const double d_start_angle_rad = startAngle*DEG_TO_RAD;
	const double d_angular_length_rad = d_angular_length_deg*DEG_TO_RAD;
	const double d_arc_distance_between_points = 0.25*pow(2.0 , static_cast<double>(10) / 10.0);
	double d_angular_length_rad_per_segment = 0.0;

	double arc_length = radius*d_angular_length_rad;
	if (arc_length < 0.0) {arc_length *= -1.0;}
	const double d_num_segments = arc_length / d_arc_distance_between_points;

	int num_segments = 0;
	round_double(d_num_segments , num_segments);

	if (num_segments == 0) {num_segments += 1;} // need at least one segment (two points)
	const int num_points = num_segments + 1;
	const double d_num_points_minus_one = static_cast<double>(num_points - 1);

	int arc_point_x;//[num_points];
	int arc_point_y;//[num_points];
	int arc_point2_x;//[num_points];
	int arc_point2_y;//[num_points];
	double d_arc_point_x = 0.0;
	double d_arc_point_y = 0.0;
	double d_arc_point2_x = 0.0;
	double d_arc_point2_y = 0.0;

	double current_angle_rad = 0.0;
	double current_angle2_rad = 0.0;

	if (d_arc_distance_between_points <= 1.0) {
		for (q = 0 ; q < num_points ; q++) {
			d_q = static_cast<double>(q);
			current_angle_rad = d_start_angle_rad + (d_q / d_num_points_minus_one)*d_angular_length_rad;
			d_arc_point_x = x + radius*cos(current_angle_rad);
			d_arc_point_y = y + radius*sin(current_angle_rad);

			round_double(d_arc_point_x , arc_point_x);
			round_double(d_arc_point_y , arc_point_y);

			work.putPixel(arc_point_x,arc_point_y,color);
		}
	}
	if (d_arc_distance_between_points > 1.0) {

		d_angular_length_rad_per_segment = d_angular_length_rad / d_num_points_minus_one;
		for (q = 0 ; q < num_segments ; q++) {
			d_q = static_cast<double>(q);
			d_q_plus_one = static_cast<double>(q + 1);

			current_angle_rad = d_start_angle_rad + d_q*d_angular_length_rad_per_segment;
			current_angle2_rad = d_start_angle_rad + d_q_plus_one*d_angular_length_rad_per_segment;

			d_arc_point_x = x + radius*cos(current_angle_rad);
			d_arc_point_y = y + radius*sin(current_angle_rad);

			round_double(d_arc_point_x , arc_point_x);
			round_double(d_arc_point_y , arc_point_y);

			d_arc_point2_x = x + radius*cos(current_angle2_rad);
			d_arc_point2_y = y + radius*sin(current_angle2_rad);

			round_double(d_arc_point2_x , arc_point2_x);
			round_double(d_arc_point2_y , arc_point2_y);

			work.line(arc_point_x,arc_point_y, arc_point2_x, arc_point2_y,color);
		}
	}
}

void Widget::roundRect( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color ){
    const int width = x2 - x1;
    const int height = y2 - y1;
    radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
    work.line(x1+radius, y1, x1+width-radius, y1, color);
    work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
    work.line(x1, y1+radius,x1, y1+height-radius, color);
    work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);
    arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
    arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
    arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
    arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);

}

void Widget::roundRectFill( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color ){
    const int width = x2 - x1;
    const int height = y2 - y1;
    radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
    work.circleFill(x1+radius, y1+radius, radius, color);
    work.circleFill((x1+width)-radius, y1+radius, radius, color);
    work.circleFill(x1+radius, (y1+height)-radius, radius, color);
    work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
    work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
    work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
    work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);
}

void Widget::checkWorkArea(){
    if ( ! workArea ){
        workArea = new Bitmap(location.getWidth(),location.getHeight());
    } else if(location.getWidth() < workArea->getWidth() || location.getHeight() < workArea->getHeight()) {
        delete workArea;
        workArea = new Bitmap(location.getWidth(), location.getHeight());
    } else if(location.getWidth() > workArea->getWidth() || location.getHeight() > workArea->getHeight()) {
        delete workArea;
        workArea = new Bitmap(location.getWidth(),location.getHeight());
    }
    if ( workArea ){
        workArea->fill(Bitmap::makeColor(255,0,255));
    }
}
<commit_msg>make line() use the proper colors<commit_after>#include "util/bitmap.h"
#include "gui/widget.h"
#include <math.h>
#include "globals.h"
#include "util/token.h"
#include "gui/coordinate.h"

using namespace Gui;

static const double S_PI = 3.14159265358979323846;
static const double DEG_TO_RAD = 180.0/S_PI;
static const double RAD_TO_DEG = S_PI/180.0;

static void round_double (double dbl_to_round , int &rounded_num) {
		rounded_num = static_cast<int>(dbl_to_round);
		if ((dbl_to_round - static_cast<double>(rounded_num)) >= 0.5) {rounded_num++;}
	}

//! min (borrowed from allegro)
static inline int Min(int x, int y){ return (((x) < (y)) ? (x) : (y)); }

//! max (borrowed from allegro)
static inline int Max(int x, int y){ return (((x) > (y)) ? (x) : (y)); }

//! mid (borrowed from allegro)
static inline int Mid(int x,int y,int z){ return (Max((x), Min((y), (z)))); }

Widget::Widget() : workArea(0)
{
	// Nothing yet
}

Widget::Widget( const Widget & w ){
	this->location = w.location;
	this->workArea = w.workArea;
}

Widget::~Widget(){
	if ( workArea ){
		delete workArea;
	}
}

// copy
Widget &Widget::operator=( const Widget &copy){
	location = copy.location;
	workArea = copy.workArea;

	return *this;
}

void Widget::setCoordinates(Token * token){
    if ( *token == "position" ){
        int x, y, width, height;
        *token >> x >> y >> width >> height;
        AbsolutePoint pos(x, y);
        AbsolutePoint dimensions(x + width, y + height);
        location.setPosition(pos);
        location.setDimensions(dimensions);
    } else if ( *token == "relative-position" ){
        double x1, y1, x2, y2;
        *token >> x1 >> y1 >> x2 >> y2;
        RelativePoint pos(x1,y1);
        RelativePoint dimensions(x2,y2);
        location = Coordinate(pos, dimensions);
    } else if ( *token == "coordinate" ){
        while (token->hasTokens()){
            Token * coordToken;
            *token >> coordToken;
            if (*coordToken == "absolute"){
                int x, y, width, height;
                *coordToken >> x >> y >> width >> height;
                AbsolutePoint pos(x, y);
                AbsolutePoint dimensions(x + width, y + height);
                location = Coordinate(pos, dimensions);
            } else if (*coordToken == "relative"){
                double x1, y1, x2, y2;
                *coordToken >> x1 >> y1 >> x2 >> y2;
                RelativePoint pos(x1,y1);
                RelativePoint dimensions(x2,y2);
                location = Coordinate(pos, dimensions);
            } else if (*coordToken == "radius"){
                double radius;
                *coordToken >> radius;
                location.setRadius(radius);
            } else if (*coordToken == "z"){
                double z;
                *coordToken >> z;
                location.setZ(z);
            }
        }
    }
}

void Widget::setColors(Token * token){
    if ( *token == "position-body" ) {
        // This handles the body color of the widget
        int r,g,b;
        *token >> r >> g >> b >> colors.bodyAlpha;
        colors.body = Bitmap::makeColor(r,g,b);
    } else if ( *token == "position-border" ) {
        // This handles the border color of the widget
        int r,g,b;
        *token >> r >> g >> b >> colors.borderAlpha;
        colors.border = Bitmap::makeColor(r,g,b);
    }
}

void Widget::arc( const Bitmap & work, int x, int y, double startAngle, int radius, int color )
{
	int q = 0;// for counters
	double d_q = 0.0;// for percentage of loop completed
	double d_q_plus_one = 0.0;

	const double d_angular_length_deg = 0.030;
	const double d_start_angle_rad = startAngle*DEG_TO_RAD;
	const double d_angular_length_rad = d_angular_length_deg*DEG_TO_RAD;
	const double d_arc_distance_between_points = 0.25*pow(2.0 , static_cast<double>(10) / 10.0);
	double d_angular_length_rad_per_segment = 0.0;

	double arc_length = radius*d_angular_length_rad;
	if (arc_length < 0.0) {arc_length *= -1.0;}
	const double d_num_segments = arc_length / d_arc_distance_between_points;

	int num_segments = 0;
	round_double(d_num_segments , num_segments);

	if (num_segments == 0) {num_segments += 1;} // need at least one segment (two points)
	const int num_points = num_segments + 1;
	const double d_num_points_minus_one = static_cast<double>(num_points - 1);

	int arc_point_x;//[num_points];
	int arc_point_y;//[num_points];
	int arc_point2_x;//[num_points];
	int arc_point2_y;//[num_points];
	double d_arc_point_x = 0.0;
	double d_arc_point_y = 0.0;
	double d_arc_point2_x = 0.0;
	double d_arc_point2_y = 0.0;

	double current_angle_rad = 0.0;
	double current_angle2_rad = 0.0;

	if (d_arc_distance_between_points <= 1.0) {
		for (q = 0 ; q < num_points ; q++) {
			d_q = static_cast<double>(q);
			current_angle_rad = d_start_angle_rad + (d_q / d_num_points_minus_one)*d_angular_length_rad;
			d_arc_point_x = x + radius*cos(current_angle_rad);
			d_arc_point_y = y + radius*sin(current_angle_rad);

			round_double(d_arc_point_x , arc_point_x);
			round_double(d_arc_point_y , arc_point_y);

			work.putPixel(arc_point_x,arc_point_y,color);
		}
	}
	if (d_arc_distance_between_points > 1.0) {

		d_angular_length_rad_per_segment = d_angular_length_rad / d_num_points_minus_one;
		for (q = 0 ; q < num_segments ; q++) {
			d_q = static_cast<double>(q);
			d_q_plus_one = static_cast<double>(q + 1);

			current_angle_rad = d_start_angle_rad + d_q*d_angular_length_rad_per_segment;
			current_angle2_rad = d_start_angle_rad + d_q_plus_one*d_angular_length_rad_per_segment;

			d_arc_point_x = x + radius*cos(current_angle_rad);
			d_arc_point_y = y + radius*sin(current_angle_rad);

			round_double(d_arc_point_x , arc_point_x);
			round_double(d_arc_point_y , arc_point_y);

			d_arc_point2_x = x + radius*cos(current_angle2_rad);
			d_arc_point2_y = y + radius*sin(current_angle2_rad);

			round_double(d_arc_point2_x , arc_point2_x);
			round_double(d_arc_point2_y , arc_point2_y);

			work.line(arc_point_x,arc_point_y, arc_point2_x, arc_point2_y,color);
		}
	}
}

void Widget::roundRect( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color ){
    const int width = x2 - x1;
    const int height = y2 - y1;
    radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
    work.line(x1+radius, y1, x1+width-radius, y1, color);
    work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
    work.line(x1, y1+radius,x1, y1+height-radius, color);
    work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);

    arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
    arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
    arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
    arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}

void Widget::roundRectFill( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color ){
    const int width = x2 - x1;
    const int height = y2 - y1;
    radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
    work.circleFill(x1+radius, y1+radius, radius, color);
    work.circleFill((x1+width)-radius, y1+radius, radius, color);
    work.circleFill(x1+radius, (y1+height)-radius, radius, color);
    work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
    work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
    work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
    work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);
}

void Widget::checkWorkArea(){
    if ( ! workArea ){
        workArea = new Bitmap(location.getWidth(),location.getHeight());
    } else if(location.getWidth() < workArea->getWidth() || location.getHeight() < workArea->getHeight()) {
        delete workArea;
        workArea = new Bitmap(location.getWidth(), location.getHeight());
    } else if(location.getWidth() > workArea->getWidth() || location.getHeight() > workArea->getHeight()) {
        delete workArea;
        workArea = new Bitmap(location.getWidth(),location.getHeight());
    }
    if ( workArea ){
        workArea->fill(Bitmap::makeColor(255,0,255));
    }
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <sstream>

#include <QPainter>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QCheckBox>

#include <geometry_msgs/Twist.h>

#include "drive_widget.h"
#include "gui_teleop.h"

namespace sesto_rviz_plugins
{

  GuiTeleop::GuiTeleop( QWidget* parent )
    : rviz::Panel( parent )
    , linear_velocity_( 0 )
    , angular_velocity_( 0 )
  {

    // max_linear_vel = DEFAULT_MAX_LINEAR_VEL;
    // max_angular_vel = DEFAULT_MAX_ANGULAR_VEL;

    QHBoxLayout* topic_layout = new QHBoxLayout;

    topic_layout->addWidget( new QLabel( "Output Topic:" ));
    output_topic_editor_ = new QLineEdit;
    topic_layout->addWidget( output_topic_editor_ );

    QHBoxLayout* max_vel_layout = new QHBoxLayout;

    max_vel_layout->addWidget(new QLabel("Max Lin"));
    max_linear_vel_editor_ = new QLineEdit;
    max_vel_layout->addWidget(max_linear_vel_editor_);

    max_vel_layout->addWidget(new QLabel("Max Ang"));
    max_angular_vel_editor_ = new QLineEdit;
    max_vel_layout->addWidget(max_angular_vel_editor_);

    QHBoxLayout* pub_checkbox_layout = new QHBoxLayout;

    pub_check_box_ = new QCheckBox("Publish", this);
    pub_checkbox_layout->addWidget(pub_check_box_);

    drive_widget_ = new DriveWidget;

    QVBoxLayout* layout = new QVBoxLayout;
    layout->addLayout( topic_layout );
    layout->addLayout( max_vel_layout);
    layout->addLayout( pub_checkbox_layout);
    layout->addWidget( drive_widget_ );
    setLayout( layout );

    QTimer* output_timer = new QTimer( this );

    connect( drive_widget_, SIGNAL( outputVelocity( float, float )), this, SLOT( setVel( float, float )));
    connect( output_topic_editor_, SIGNAL( editingFinished() ), this, SLOT( updateTopic() ));
    connect( output_timer, SIGNAL( timeout() ), this, SLOT( sendVel() ));
    connect( max_linear_vel_editor_, SIGNAL(editingFinished()), this, SLOT( setMaxLinearVel() ));
    connect( max_angular_vel_editor_, SIGNAL(editingFinished()), this, SLOT( setMaxAngularVel() ));

    output_timer->start( 100 );

    drive_widget_->setEnabled( false );
  }

  void GuiTeleop::setVel( float lin, float ang )
  {
    linear_velocity_ = lin;
    angular_velocity_ = ang;
  }

  void GuiTeleop::updateTopic()
  {
    setTopic( output_topic_editor_->text() );
  }

  void GuiTeleop::setMaxLinearVel()
  {
    max_linear_vel = max_linear_vel_editor_->text().toFloat();
  }

  void GuiTeleop::setMaxAngularVel()
  {
    max_angular_vel = max_angular_vel_editor_->text().toFloat();
  }

  void GuiTeleop::setTopic( const QString& new_topic )
  {
    if( new_topic != output_topic_ )
    {
      output_topic_ = new_topic;

      if( output_topic_ == "" )
      {
        velocity_publisher_.shutdown();
      }
      else
      {
        velocity_publisher_ = nh_.advertise<geometry_msgs::Twist>( output_topic_.toStdString(), 1 );
      }

      Q_EMIT configChanged();
    }

    drive_widget_->setEnabled( output_topic_ != "" );
  }

  void GuiTeleop::sendVel()
  {
    if( ros::ok() && velocity_publisher_ && pub_check_box_->isChecked())
    {
      suppressSpeed();

      geometry_msgs::Twist msg;
      msg.linear.x = linear_velocity_;
      msg.linear.y = 0;
      msg.linear.z = 0;
      msg.angular.x = 0;
      msg.angular.y = 0;
      msg.angular.z = angular_velocity_;
      velocity_publisher_.publish( msg );
    }
  }

  void GuiTeleop::suppressSpeed()
  {
    if (linear_velocity_ > max_linear_vel) {
      linear_velocity_ = max_linear_vel;
    }

    if (angular_velocity_ > max_angular_vel) {
      angular_velocity_ = max_angular_vel;
    }

  }

// TODO: save other states
  void GuiTeleop::save( rviz::Config config ) const
  {
    rviz::Panel::save( config );
    config.mapSetValue( "Topic", output_topic_ );
    config.mapSetValue("MaxLinVel", max_linear_vel);
    config.mapSetValue("MaxAngVel", max_angular_vel);
  }

  void GuiTeleop::load( const rviz::Config& config )
  {
    rviz::Panel::load( config );
    QString topic;
    if( config.mapGetString( "Topic", &topic ))
    {
      output_topic_editor_->setText( topic );
      updateTopic();
    }

    QString initMaxLinVel, initMaxAngVel;

    if (config.mapGetString("MaxLinVel", &initMaxLinVel)) {
      max_linear_vel = initMaxLinVel.toFloat();
    } else {
      max_linear_vel = DEFAULT_MAX_LINEAR_VEL;
    }

    std::ostringstream temp;
    temp << max_linear_vel;

    max_linear_vel_editor_->setText(QString::fromStdString(temp.str().c_str()));

    if (config.mapGetString("MaxAng", &initMaxAngVel)) {
      max_angular_vel = initMaxAngVel.toFloat();
    } else {
      max_angular_vel = DEFAULT_MAX_ANGULAR_VEL;
    }

    temp << max_linear_vel;

    max_angular_vel_editor_->setText(QString::fromStdString(temp.str().c_str()));

  }

}

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(sesto_rviz_plugins::GuiTeleop,rviz::Panel )
<commit_msg>Pushing to github<commit_after>#include <stdio.h>
#include <sstream>

#include <QPainter>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QTimer>
#include <QCheckBox>

#include <geometry_msgs/Twist.h>

#include "drive_widget.h"
#include "gui_teleop.h"

namespace sesto_rviz_plugins
{

  GuiTeleop::GuiTeleop( QWidget* parent )
    : rviz::Panel( parent )
    , linear_velocity_( 0 )
    , angular_velocity_( 0 )
  {

    QHBoxLayout* topic_layout = new QHBoxLayout;

    topic_layout->addWidget( new QLabel( "Output Topic:" ));
    output_topic_editor_ = new QLineEdit;
    topic_layout->addWidget( output_topic_editor_ );

    QHBoxLayout* max_vel_layout = new QHBoxLayout;

    max_vel_layout->addWidget(new QLabel("Max Lin"));
    max_linear_vel_editor_ = new QLineEdit;
    max_vel_layout->addWidget(max_linear_vel_editor_);

    max_vel_layout->addWidget(new QLabel("Max Ang"));
    max_angular_vel_editor_ = new QLineEdit;
    max_vel_layout->addWidget(max_angular_vel_editor_);

    QHBoxLayout* pub_checkbox_layout = new QHBoxLayout;

    pub_check_box_ = new QCheckBox("Publish", this);
    pub_checkbox_layout->addWidget(pub_check_box_);

    drive_widget_ = new DriveWidget;

    QVBoxLayout* layout = new QVBoxLayout;
    layout->addLayout( topic_layout );
    layout->addLayout( max_vel_layout);
    layout->addLayout( pub_checkbox_layout);
    layout->addWidget( drive_widget_ );
    setLayout( layout );

    QTimer* output_timer = new QTimer( this );

    connect( drive_widget_, SIGNAL( outputVelocity( float, float )), this, SLOT( setVel( float, float )));
    connect( output_topic_editor_, SIGNAL( editingFinished() ), this, SLOT( updateTopic() ));
    connect( output_timer, SIGNAL( timeout() ), this, SLOT( sendVel() ));
    connect( max_linear_vel_editor_, SIGNAL(editingFinished()), this, SLOT( setMaxLinearVel() ));
    connect( max_angular_vel_editor_, SIGNAL(editingFinished()), this, SLOT( setMaxAngularVel() ));

    output_timer->start( 100 );

    drive_widget_->setEnabled( false );
  }

  void GuiTeleop::setVel( float lin, float ang )
  {
    linear_velocity_ = lin;
    angular_velocity_ = ang;
  }

  void GuiTeleop::updateTopic()
  {
    setTopic( output_topic_editor_->text() );
  }

  void GuiTeleop::setMaxLinearVel()
  {
    max_linear_vel = max_linear_vel_editor_->text().toFloat();
  }

  void GuiTeleop::setMaxAngularVel()
  {
    max_angular_vel = max_angular_vel_editor_->text().toFloat();
  }

  void GuiTeleop::setTopic( const QString& new_topic )
  {
    if( new_topic != output_topic_ )
    {
      output_topic_ = new_topic;

      if( output_topic_ == "" )
      {
        velocity_publisher_.shutdown();
      }
      else
      {
        velocity_publisher_ = nh_.advertise<geometry_msgs::Twist>( output_topic_.toStdString(), 1 );
      }

      Q_EMIT configChanged();
    }

    drive_widget_->setEnabled( output_topic_ != "" );
  }

  void GuiTeleop::sendVel()
  {
    if( ros::ok() && velocity_publisher_ && pub_check_box_->isChecked())
    {
      suppressSpeed();

      geometry_msgs::Twist msg;
      msg.linear.x = linear_velocity_;
      msg.linear.y = 0;
      msg.linear.z = 0;
      msg.angular.x = 0;
      msg.angular.y = 0;
      msg.angular.z = angular_velocity_;
      velocity_publisher_.publish( msg );
    }
  }

  void GuiTeleop::suppressSpeed()
  {
    if (linear_velocity_ > max_linear_vel) {
      linear_velocity_ = max_linear_vel;
    }

    if (angular_velocity_ > max_angular_vel) {
      angular_velocity_ = max_angular_vel;
    }

  }

// TODO: save other states
  void GuiTeleop::save( rviz::Config config ) const
  {
    rviz::Panel::save( config );
    config.mapSetValue("Topic", output_topic_ );
    config.mapSetValue("MaxLinVel", max_linear_vel);
    config.mapSetValue("MaxAngVel", max_angular_vel);
  }

  void GuiTeleop::load( const rviz::Config& config )
  {
    rviz::Panel::load( config );
    QString topic;
    if( config.mapGetString( "Topic", &topic ))
    {
      output_topic_editor_->setText( topic );
      updateTopic();
    }

    QString initMaxLinVel, initMaxAngVel;

    if (config.mapGetString("MaxLinVel", &initMaxLinVel)) {
      max_linear_vel = initMaxLinVel.toFloat();
    } else {
      max_linear_vel = DEFAULT_MAX_LINEAR_VEL;
    }

    std::ostringstream temp;
    temp << max_linear_vel;

    max_linear_vel_editor_->setText(QString::fromStdString(temp.str().c_str()));

    if (config.mapGetString("MaxAng", &initMaxAngVel)) {
      max_angular_vel = initMaxAngVel.toFloat();
    } else {
      max_angular_vel = DEFAULT_MAX_ANGULAR_VEL;
    }

    temp << max_linear_vel;

    max_angular_vel_editor_->setText(QString::fromStdString(temp.str().c_str()));

  }

}

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(sesto_rviz_plugins::GuiTeleop,rviz::Panel )
<|endoftext|>


<commit_before>#include <cstdio>

int main(){
    int d[] = {100, 50, 20, 10, 5, 2, 1};
    int n, t = 0;

    scanf("%d", &n);
    printf("%d\n", n);
    do {
        printf("%d nota(s) de R$ %d,00\n", n / d[t], d[t]);
        if (n >= d[t])
        n -= d[t] * (n / d[t]);
    } while(d[t++] != 1);
    return 0;
}
<commit_msg>Identando.<commit_after>#include <cstdio>

int main(){
    int d[] = {100, 50, 20, 10, 5, 2, 1};
    int n, t = 0;

    scanf("%d", &n);
    printf("%d\n", n);
    do {
        printf("%d nota(s) de R$ %d,00\n", n / d[t], d[t]);
        if (n >= d[t])
            n -= d[t] * (n / d[t]);
    } while(d[t++] != 1);
    return 0;
}
<|endoftext|>


<commit_before>// RUN: cat %s | %cling -Xclang -verify -I%p
// XFAIL: vg
// We expect for now this to fail, because the access to the invalid memory comes
// from the fact that we invalidate the included file cache and when we are in
// verify mode the verifier notifies about errors at the end of the source file.
//
// Tests the ChainedConsumer's ability to recover from errors. .x produces
// #include \"CannotDotX.h\" \n void wrapper() {CannotDotX();}, which causes
// a TagDecl to be passed trough the consumers. This TagDecl is caught twice by
// the ChainedConsumer and cached is the queue of incoming declaration twice.
// If we encounter error the ChainedConsumer shouldn't try to remove the
// declaration twice and this test makes sure of that.

.x CannotDotX.h() // expected-error {{use of undeclared identifier 'CannotDotX'}}
.x CannotDotX.h() // expected-error {{use of undeclared identifier 'CannotDotX'}}

 // Uses a bug in the implementation of .L, which must be fixed soon.
 // Exposes another issue with the VerifyDiagnosticConsumer in the context of
 // cling. The first .L shouldn't cause errors . However when using the
 // preprocessor most probably we lose track of the errors source locations
 // and files.
.L CannotDotX.h "// expected-error {{redefinition of 'MyClass'}} expected-error {{expected member name or ';' after declaration specifiers}} expected-node {{previous definition is here}}

.L CannotDotX.h

.q
<commit_msg>Do not issue error in case: .x MyFile() - where no string is between the parenthesis.<commit_after>// RUN: cat %s | %cling -Xclang -verify -I%p
// XFAIL: vg
.x CannotDotX.h() // expected-error {{use of undeclared identifier 'CannotDotX'}}
.x CannotDotX.h() // expected-error {{use of undeclared identifier 'CannotDotX'}}

 // Uses a bug in the implementation of .L, which must be fixed soon.
 // Exposes another issue with the VerifyDiagnosticConsumer in the context of
 // cling. The first .L shouldn't cause errors . However when using the
 // preprocessor most probably we lose track of the errors source locations
 // and files.
.L CannotDotX.h "// expected-error {{redefinition of 'MyClass'}} expected-error {{expected member name or ';' after declaration specifiers}} expected-node {{previous definition is here}}

.L CannotDotX.h

.q
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"

#include "condor_io.h"

#include "qmgr.h"
#include "condor_qmgr.h"
#include "condor_debug.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "daemon.h"
#include "my_hostname.h"
#include "my_username.h"

ReliSock *qmgmt_sock = NULL;
static Qmgr_connection connection;

Qmgr_connection *
ConnectQ(const char *qmgr_location, int timeout, bool read_only, CondorError* errstack, const char *effective_owner, const char* schedd_version_str )
{
	int		rval, ok;
	int cmd = read_only ? QMGMT_READ_CMD : QMGMT_WRITE_CMD;

		// do we already have a connection active?
	if( qmgmt_sock ) {
			// yes; reject new connection (we can only handle one at a time)
		return( NULL );
	}

	// set up the error handling so it will clean up automatically on
	// return.  also allow them to specify their own stack.
	CondorError  our_errstack;
	CondorError* errstack_select = &our_errstack;
	if (errstack) {
		errstack_select = errstack;
	}

    // no connection active as of now; create a new one
	Daemon d( DT_SCHEDD, qmgr_location );
	if( ! d.locate() ) {
		ok = FALSE;
		if( qmgr_location ) {
			dprintf( D_ALWAYS, "Can't find address of queue manager %s\n",
					 qmgr_location );
		} else {
			dprintf( D_ALWAYS, "Can't find address of local queue manager\n" );
		}
	} else {
			// QMGMT_WRITE_CMD didn't exist before 7.5.0, so use QMGMT_READ_CMD
			// when talking to older schedds
		if( cmd == QMGMT_WRITE_CMD ) {
			if( !schedd_version_str ) schedd_version_str = d.version();
			if( !schedd_version_str ) {
					// Some day when we don't care about compatibility with
					// things from before 7.5.0, we could stop defaulting
					// to QMGMT_READ_CMD here.
				cmd = QMGMT_READ_CMD;
			}
			else {
				CondorVersionInfo ver_info(schedd_version_str);
				if( !ver_info.built_since_version(7,5,0) ) {
					cmd = QMGMT_READ_CMD;
				}
			}
		}

		qmgmt_sock = (ReliSock*) d.startCommand( cmd,
												 Stream::reli_sock,
												 timeout,
												 errstack_select);
		ok = qmgmt_sock != NULL;
		if( !ok && !errstack) {
			dprintf(D_ALWAYS, "Can't connect to queue manager: %s\n",
					errstack_select->getFullText().c_str() );
		}
	}

	if( !ok ) {
		if( qmgmt_sock ) delete qmgmt_sock;
		qmgmt_sock = NULL;
		return 0;
	}

		// If security negotiation is turned off and we are using WRITE_CMD,
		// then we must force authentication now, before trying to initialize
		// the connection, because this command is registered with
		// force_authentication=true on the server side.
	if( cmd == QMGMT_WRITE_CMD && !qmgmt_sock->triedAuthentication()) {
		if( !SecMan::authenticate_sock(qmgmt_sock, CLIENT_PERM, errstack_select ) )
		{
			delete qmgmt_sock;
			qmgmt_sock = NULL;
			if (!errstack) {
				dprintf( D_ALWAYS, "Authentication Error: %s\n",
						 errstack_select->getFullText().c_str() );
			}
			return 0;
		}
	}

    // This could be a problem
	char *username = my_username();
	char *domain = my_domainname();

	if ( !username ) {
		dprintf(D_FULLDEBUG,"Failure getting my_username()\n");
		delete qmgmt_sock;
		qmgmt_sock = NULL;
		if (domain) free(domain);
		return( 0 );
	}

	/* Get the schedd to handle Q ops. */

    /* Get rid of all the code below */

    if (read_only || !qmgmt_sock->triedAuthentication()) {
        if ( read_only ) {
            rval = InitializeReadOnlyConnection( username );
        } else {
            rval = InitializeConnection( username, domain );
        }

		if (username) {
			free(username);
			username = NULL;
		}
		if (domain) {
			free(domain);
			domain = NULL;
		}

        if (rval < 0) {
            delete qmgmt_sock;
            qmgmt_sock = NULL;
            return 0;
        }

        if ( !read_only ) {
            if (!SecMan::authenticate_sock(qmgmt_sock, CLIENT_PERM, errstack_select)) {
                delete qmgmt_sock;
                qmgmt_sock = NULL;
				if (!errstack) {
					dprintf( D_ALWAYS, "Authentication Error: %s\n",
							 errstack_select->getFullText().c_str() );
				}
                return 0;
            }
        }
    }

	if (username) free(username);
	if (domain) free(domain);

	if( effective_owner && *effective_owner ) {
		if( QmgmtSetEffectiveOwner( effective_owner ) != 0 ) {
			if( errstack ) {
				errstack->pushf(
					"Qmgmt",SCHEDD_ERR_SET_EFFECTIVE_OWNER_FAILED,
					"SetEffectiveOwner(%s) failed with errno=%d: %s.",
					effective_owner, errno, strerror(errno) );
			}
			else {
				dprintf( D_ALWAYS,
						 "SetEffectiveOwner(%s) failed with errno=%d: %s.\n",
						 effective_owner, errno, strerror(errno) );
			}
			delete qmgmt_sock;
			qmgmt_sock = NULL;
			return 0;
		}
	}

	return &connection;
}

// we can ignore the parameter because there is only one connection
bool
DisconnectQ(Qmgr_connection *,bool commit_transactions, CondorError *errstack)
{
	int rval = -1;

	if( !qmgmt_sock ) return( false );
	if ( commit_transactions ) {
		rval = RemoteCommitTransaction(0, errstack);
	}
	CloseSocket();
	delete qmgmt_sock;
	qmgmt_sock = NULL;
	return( rval >= 0 );
}

void
FreeJobAd(ClassAd *&ad)
{
	delete ad;
	ad = NULL;
}

int
SendSpoolFileBytes(char const *filename)
{
	filesize_t	size;
	qmgmt_sock->encode();
	if (qmgmt_sock->put_file(&size, filename) < 0) {
		return -1;
	}

	return 0;

}

void
WalkJobQueue2(scan_func func, void* pv)
{
	ClassAd *ad;
	int rval = 0;

	ad = GetNextJob(1);
	while (ad != NULL && rval >= 0) {
		rval = func(ad, pv);
		if (rval >= 0) {
			FreeJobAd(ad);
			ad = GetNextJob(0);
		}
	}
	if (ad != NULL)
		FreeJobAd(ad);
}

int
rusage_to_float(const struct rusage &ru, double *utime, double *stime )
{
	if ( utime )
		*utime = (double) ru.ru_utime.tv_sec;

	if ( stime )
		*stime = (double) ru.ru_stime.tv_sec;

	return 0;
}

int
float_to_rusage(double utime, double stime, struct rusage *ru)
{
	ru->ru_utime.tv_sec = (time_t)utime;
	ru->ru_stime.tv_sec = (time_t)stime;
	ru->ru_utime.tv_usec = 0;
	ru->ru_stime.tv_usec = 0;
	return 0;
}

<commit_msg>Assume all schedds support QMGMT_WRITE_CMD in ConnectQ(). #6844<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"

#include "condor_io.h"

#include "qmgr.h"
#include "condor_qmgr.h"
#include "condor_debug.h"
#include "condor_attributes.h"
#include "condor_classad.h"
#include "daemon.h"
#include "my_hostname.h"
#include "my_username.h"

ReliSock *qmgmt_sock = NULL;
static Qmgr_connection connection;

Qmgr_connection *
ConnectQ(const char *qmgr_location, int timeout, bool read_only, CondorError* errstack, const char *effective_owner, const char* schedd_version_str )
{
	int		rval, ok;
	int cmd = read_only ? QMGMT_READ_CMD : QMGMT_WRITE_CMD;

		// do we already have a connection active?
	if( qmgmt_sock ) {
			// yes; reject new connection (we can only handle one at a time)
		return( NULL );
	}

	// set up the error handling so it will clean up automatically on
	// return.  also allow them to specify their own stack.
	CondorError  our_errstack;
	CondorError* errstack_select = &our_errstack;
	if (errstack) {
		errstack_select = errstack;
	}

    // no connection active as of now; create a new one
	Daemon d( DT_SCHEDD, qmgr_location );
	if( ! d.locate() ) {
		ok = FALSE;
		if( qmgr_location ) {
			dprintf( D_ALWAYS, "Can't find address of queue manager %s\n",
					 qmgr_location );
		} else {
			dprintf( D_ALWAYS, "Can't find address of local queue manager\n" );
		}
	} else {
		qmgmt_sock = (ReliSock*) d.startCommand( cmd,
												 Stream::reli_sock,
												 timeout,
												 errstack_select);
		ok = qmgmt_sock != NULL;
		if( !ok && !errstack) {
			dprintf(D_ALWAYS, "Can't connect to queue manager: %s\n",
					errstack_select->getFullText().c_str() );
		}
	}

	if( !ok ) {
		if( qmgmt_sock ) delete qmgmt_sock;
		qmgmt_sock = NULL;
		return 0;
	}

		// If security negotiation is turned off and we are using WRITE_CMD,
		// then we must force authentication now, before trying to initialize
		// the connection, because this command is registered with
		// force_authentication=true on the server side.
	if( cmd == QMGMT_WRITE_CMD && !qmgmt_sock->triedAuthentication()) {
		if( !SecMan::authenticate_sock(qmgmt_sock, CLIENT_PERM, errstack_select ) )
		{
			delete qmgmt_sock;
			qmgmt_sock = NULL;
			if (!errstack) {
				dprintf( D_ALWAYS, "Authentication Error: %s\n",
						 errstack_select->getFullText().c_str() );
			}
			return 0;
		}
	}

    // This could be a problem
	char *username = my_username();
	char *domain = my_domainname();

	if ( !username ) {
		dprintf(D_FULLDEBUG,"Failure getting my_username()\n");
		delete qmgmt_sock;
		qmgmt_sock = NULL;
		if (domain) free(domain);
		return( 0 );
	}

	/* Get the schedd to handle Q ops. */

    /* Get rid of all the code below */

    if (read_only || !qmgmt_sock->triedAuthentication()) {
        if ( read_only ) {
            rval = InitializeReadOnlyConnection( username );
        } else {
            rval = InitializeConnection( username, domain );
        }

		if (username) {
			free(username);
			username = NULL;
		}
		if (domain) {
			free(domain);
			domain = NULL;
		}

        if (rval < 0) {
            delete qmgmt_sock;
            qmgmt_sock = NULL;
            return 0;
        }

        if ( !read_only ) {
            if (!SecMan::authenticate_sock(qmgmt_sock, CLIENT_PERM, errstack_select)) {
                delete qmgmt_sock;
                qmgmt_sock = NULL;
				if (!errstack) {
					dprintf( D_ALWAYS, "Authentication Error: %s\n",
							 errstack_select->getFullText().c_str() );
				}
                return 0;
            }
        }
    }

	if (username) free(username);
	if (domain) free(domain);

	if( effective_owner && *effective_owner ) {
		if( QmgmtSetEffectiveOwner( effective_owner ) != 0 ) {
			if( errstack ) {
				errstack->pushf(
					"Qmgmt",SCHEDD_ERR_SET_EFFECTIVE_OWNER_FAILED,
					"SetEffectiveOwner(%s) failed with errno=%d: %s.",
					effective_owner, errno, strerror(errno) );
			}
			else {
				dprintf( D_ALWAYS,
						 "SetEffectiveOwner(%s) failed with errno=%d: %s.\n",
						 effective_owner, errno, strerror(errno) );
			}
			delete qmgmt_sock;
			qmgmt_sock = NULL;
			return 0;
		}
	}

	return &connection;
}

// we can ignore the parameter because there is only one connection
bool
DisconnectQ(Qmgr_connection *,bool commit_transactions, CondorError *errstack)
{
	int rval = -1;

	if( !qmgmt_sock ) return( false );
	if ( commit_transactions ) {
		rval = RemoteCommitTransaction(0, errstack);
	}
	CloseSocket();
	delete qmgmt_sock;
	qmgmt_sock = NULL;
	return( rval >= 0 );
}

void
FreeJobAd(ClassAd *&ad)
{
	delete ad;
	ad = NULL;
}

int
SendSpoolFileBytes(char const *filename)
{
	filesize_t	size;
	qmgmt_sock->encode();
	if (qmgmt_sock->put_file(&size, filename) < 0) {
		return -1;
	}

	return 0;

}

void
WalkJobQueue2(scan_func func, void* pv)
{
	ClassAd *ad;
	int rval = 0;

	ad = GetNextJob(1);
	while (ad != NULL && rval >= 0) {
		rval = func(ad, pv);
		if (rval >= 0) {
			FreeJobAd(ad);
			ad = GetNextJob(0);
		}
	}
	if (ad != NULL)
		FreeJobAd(ad);
}

int
rusage_to_float(const struct rusage &ru, double *utime, double *stime )
{
	if ( utime )
		*utime = (double) ru.ru_utime.tv_sec;

	if ( stime )
		*stime = (double) ru.ru_stime.tv_sec;

	return 0;
}

int
float_to_rusage(double utime, double stime, struct rusage *ru)
{
	ru->ru_utime.tv_sec = (time_t)utime;
	ru->ru_stime.tv_sec = (time_t)stime;
	ru->ru_utime.tv_usec = 0;
	ru->ru_stime.tv_usec = 0;
	return 0;
}

<|endoftext|>


<commit_before>#include "homography.hpp"

#include <linalg.hpp>
#include <math.hpp>

cv::matrixr homography_8_point(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points) {

	cv::matrixr H;

	auto n = image_points.size();
	ASSERT(model_points.size() == n);
	cv::matrixr L = cv::matrixr::zeros(2*n, 9);

	for(unsigned k = 0; k < n; k++) {

		real_t X=model_points[k][0];  /* X coord of model point k */
		real_t Y=model_points[k][1];  /* Y coord of model point k */
		real_t W=model_points[k][2];  /* W coord of model point k */
		real_t u=image_points[k][0];  /* u coord of image point k */
		real_t v=image_points[k][1];  /* v coord of image point k */

		int i = 2*k;                 /* line number in matrix L  */

		L(i,0) =    X;
		L(i, 1) =    Y;
		L(i, 2) =    W;
		L(i, 3) =    0;
		L(i, 4) =    0;
		L(i, 5) =    0;
		L(i, 6) = -u*X;
		L(i, 7) = -u*Y;
		L(i, 8) = -u*W;

		i++;

		L(i, 0) =    0;
		L(i, 1) =    0;
		L(i, 2) =    0;
		L(i, 3) =    X;
		L(i, 4) =    Y;
		L(i, 5) =    W;
		L(i, 6) = -v*X;
		L(i, 7) = -v*Y;
		L(i, 8) = -v*W;
	}

	cv::null_solve(L, H);
	H.reshape(3, 3);

	H *= 1. / H(2, 2);

	return H;
}

// Similarity estimation for normalization process.
template<size_t _size>
cv::matrixr homography_dlt_sim_estimation(const std::vector<cv::vectorx<real_t, _size> > &features) {
	cv::matrixr transform = cv::matrixr::eye(3);

	cv::vec2r centroid(0, 0);
	cv::matrixr S;

	for (auto feat : features) {
		centroid += feat;
	}
	centroid /= features.size();

	real_t sum_dist = 0;

	for (auto feat : features) {
		sum_dist+= centroid.distance(feat);
	}
	centroid *= -1;

	real_t scale_v = std::sqrt(2.) / (sum_dist / features.size());

	transform(0, 0) = scale_v;
	transform(1, 1) = scale_v;
	transform(0, 2) = centroid[0];
	transform(1, 2) = centroid[1];

	return transform;
}

template<size_t _size>
void homography_dlt_normalize(std::vector<cv::vectorx<real_t, _size> > &features, const cv::matrixr &S) {
	ASSERT(S && S.rows() == 3 && S.cols() == 3);
	cv::matrixr x(3, 1), xp(3, 1);
	for (unsigned i = 0; i < features.size(); ++i) {
		x(0, 0) = features[i][0];
		x(1, 0) = features[i][1];
		x(2, 0) = (_size == 3) ? features[i][2] : 1.;
		cross(S, x, xp);
		features[i][0] = xp(0, 0) / xp(2, 0);
		features[i][1] = xp(1, 0) / xp(2, 0);
		if(_size == 3)
			features[i][2] = 1.;
	}
}

cv::matrixr homography_dlt(const std::vector<cv::vec2r> &src_pts, const std::vector<cv::vec3r> &tgt_pts) {
	ASSERT(src_pts.size() >= 4 && src_pts.size() == tgt_pts.size());

	cv::matrixr H;

	// 0. Prepare data;
	cv::matrixr srcS, tgtS, invTgtS;
	cv::matrixr A = cv::matrixr::zeros(2 * src_pts.size(), 9);

	// 1. Perform normalization;
	srcS = homography_dlt_sim_estimation<2>(src_pts);
	tgtS = homography_dlt_sim_estimation<3>(tgt_pts);

	auto src_n = src_pts; // source normalized points
	auto tgt_n = tgt_pts; // target normalized points

	invTgtS = tgtS.clone();
	invert(invTgtS);

	homography_dlt_normalize<2>(src_n, srcS);
	homography_dlt_normalize<3>(tgt_n, tgtS);

	// 2. Pack matrix A;
	for (unsigned i = 0; i < src_pts.size(); ++i) {
		A(i * 2 + 0, 0) = -1 * src_n[i][0];
		A(i * 2 + 0, 1) = -1 * src_n[i][1];
		A(i * 2 + 0, 2) = -1;
		A(i * 2 + 0, 6) = tgt_n[i][0] * src_n[i][0];
		A(i * 2 + 0, 7) = tgt_n[i][0] * src_n[i][1];
		A(i * 2 + 0, 8) = tgt_n[i][0];

		A(i * 2 + 1, 3) = -1 * src_n[i][0];
		A(i * 2 + 1, 4) = -1 * src_n[i][1];
		A(i * 2 + 1, 5) = -1;
		A(i * 2 + 1, 6) = tgt_n[i][1] * src_n[i][0];
		A(i * 2 + 1, 7) = tgt_n[i][1] * src_n[i][1];
		A(i * 2 + 1, 8) = tgt_n[i][1];
	}

	// 3. solve nullspace of A for H;
	cv::null_solve(A, H);

	H.reshape(3, 3);

	// 4. denormalize the homography.
	H = invTgtS * H * srcS;

	return H;
}

/*
 * Pack homography matrices A and B by the form used for least squares solving.
 */
void pack_ab(const std::vector<cv::vec2r> &src_pts, const std::vector<cv::vec3r> &tgt_pts, cv::matrixr &A, cv::matrixr &B) {

	ASSERT(src_pts.size() && src_pts.size() == tgt_pts.size());

	// construct matrices
	A = cv::matrixr::zeros(src_pts.size() * 2, 8);
	B.create(src_pts.size() * 2, 1);

	// populate matrices with data.
	for (unsigned i = 0; i < src_pts.size(); i++) {

		auto &src = src_pts[i];
		auto &tgt = tgt_pts[i];

		B(i * 2, 0) = tgt[0];
		B(i * 2 + 1, 0) = tgt[1];

		A(i * 2, 0) = src[0];
		A(i * 2, 1) = src[1];
		A(i * 2, 2) = 1;
		A(i * 2 + 1, 3) = src[0];
		A(i * 2 + 1, 4) = src[1];
		A(i * 2 + 1, 5) = 1;

		A(i * 2, 6) = -1 * src[0] * tgt[0];
		A(i * 2, 7) = -1 * src[1] * tgt[0];
		A(i * 2 + 1, 6) = -1 * src[0] * tgt[1];
		A(i * 2 + 1, 7) = -1 * src[1] * tgt[1];
	}
}

/*
 * Solve homography using least squares method.
 */
cv::matrixr homography_least_squares(const std::vector<cv::vec2r> &src_pts, const std::vector<cv::vec3r> &tgt_pts) {

	cv::matrixr A, B, H;
	pack_ab(src_pts, tgt_pts, A, B);
	cv::matrixr _H(8, 1);

	cv::matrixr At = A.transposed();
	lu_solve(At * A, At * B, _H);

	if (!_H) {
		throw std::runtime_error("Internal error!~ failure occurred calculating homography.\n");
	}

	H.create(1, 9);
	std::copy(_H.begin(), _H.end(), H.begin());
	H.reshape(3, 3);
	H(2, 2) = 1;

	return H;
}

cv::matrixr homography_solve(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, H_calc_alg alg) {
	switch (alg) {
	case HOMOGRAPHY_8_POINT:
		return homography_8_point(image_points, model_points);
	case HOMOGRAPHY_LEAST_SQUARES:
		return homography_least_squares(image_points, model_points);
	case HOMOGRAPHY_DLT:
		return homography_dlt(image_points, model_points);
	};
}

std::vector<cv::vec2r> source_pts;
std::vector<cv::vec3r> target_pts;

void reprojection_fcn(int m, int n, double* x, double* fvec,int *iflag) {

	if (*iflag == 0)
		return;

	// calculate m_projected
	cv::matrixd _H(3, 3, x); // borrow x and form matrix
	cv::matrixd ptn(3, 1), p_ptn(3, 1), res_ptn(3, 1);

	for (int i = 0; i < m; ++i) {
		ptn(0, 0) = target_pts[i][0]; // model point
		ptn(1, 0) = target_pts[i][1];
		ptn(2, 0) = target_pts[i][2];

		p_ptn(0, 0) = source_pts[i][0]; // photo projection point
		p_ptn(1, 0) = source_pts[i][1];
		p_ptn(2, 0) = 1.;

		cv::cross( _H, ptn, res_ptn);

		res_ptn(0, 0) /= res_ptn(2, 0);
		res_ptn(1, 0) /= res_ptn(2, 0);
		res_ptn(2, 0) = 1.;

		fvec[i] = sqrt(pow(p_ptn(0, 0) - res_ptn(0, 0), 2) + pow(p_ptn(1, 0) - res_ptn(1, 0), 2));
	}
}

int homography_optimize(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points,
                        cv::matrixr &H, double tol) {

	source_pts = image_points;
	target_pts = model_points;

	ASSERT(source_pts.size() > 9);

	int m = source_pts.size();
	int n = 9;

	int info = 0;

	auto *_H = new double[n];

	for (int i = 0; i < 9; ++i) {
		_H[i] = H.data_begin()[i];
	}

	info = cv::lmdif1(reprojection_fcn, m, n, _H, tol);

	for (int i = 0; i < 9; ++i) {
		H.data_begin()[i] = _H[i];
	}

	H /= H(2, 2);

	delete [] _H;

	return info;
}

real_t calc_h_reprojection_error(const cv::matrixr &H, const std::vector<cv::vec2r> &source_pts, const std::vector<cv::vec3r> &target_pts) {

	ASSERT(source_pts.size() == target_pts.size() && H && H.rows() == 3 && H.cols() == 3);

	unsigned ptn_count = source_pts.size();
	real_t err = 0.0;

	// calculate m_projected
	cv::matrixr ptn(3, 1), p_ptn(3, 1), res_ptn(3, 1);

	for (unsigned i = 0; i < ptn_count; ++i) {
		ptn(0, 0) = source_pts[i][0];
		ptn(1, 0) = source_pts[i][1];
		ptn(2, 0) = 1.;

		p_ptn(0, 0) = target_pts[i][0];
		p_ptn(1, 0) = target_pts[i][1];
		p_ptn(2, 0) = target_pts[i][2];

		cv::cross( H, ptn, res_ptn);

		res_ptn(0, 0) /= res_ptn(2, 0);
		res_ptn(1, 0) /= res_ptn(2, 0);
		res_ptn(2, 0) = 1;

		err += cv::distance(res_ptn, p_ptn, cv::Norm::L2);
	}

	return err / ptn_count;
}

<commit_msg>real_t fix<commit_after>#include "homography.hpp"

#include <linalg.hpp>
#include <math.hpp>

cv::matrixr homography_8_point(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points) {

	cv::matrixr H;

	auto n = image_points.size();
	ASSERT(model_points.size() == n);
	cv::matrixr L = cv::matrixr::zeros(2*n, 9);

	for(unsigned k = 0; k < n; k++) {

		real_t X=model_points[k][0];  /* X coord of model point k */
		real_t Y=model_points[k][1];  /* Y coord of model point k */
		real_t W=model_points[k][2];  /* W coord of model point k */
		real_t u=image_points[k][0];  /* u coord of image point k */
		real_t v=image_points[k][1];  /* v coord of image point k */

		int i = 2*k;                 /* line number in matrix L  */

		L(i,0) =    X;
		L(i, 1) =    Y;
		L(i, 2) =    W;
		L(i, 3) =    0;
		L(i, 4) =    0;
		L(i, 5) =    0;
		L(i, 6) = -u*X;
		L(i, 7) = -u*Y;
		L(i, 8) = -u*W;

		i++;

		L(i, 0) =    0;
		L(i, 1) =    0;
		L(i, 2) =    0;
		L(i, 3) =    X;
		L(i, 4) =    Y;
		L(i, 5) =    W;
		L(i, 6) = -v*X;
		L(i, 7) = -v*Y;
		L(i, 8) = -v*W;
	}

	cv::null_solve(L, H);
	H.reshape(3, 3);

	H *= 1. / H(2, 2);

	return H;
}

// Similarity estimation for normalization process.
template<size_t _size>
cv::matrixr homography_dlt_sim_estimation(const std::vector<cv::vectorx<real_t, _size> > &features) {
	cv::matrixr transform = cv::matrixr::eye(3);

	cv::vec2r centroid(0, 0);
	cv::matrixr S;

	for (auto feat : features) {
		centroid += feat;
	}
	centroid /= features.size();

	real_t sum_dist = 0;

	for (auto feat : features) {
		sum_dist+= centroid.distance(feat);
	}
	centroid *= -1;

	real_t scale_v = std::sqrt(2.) / (sum_dist / features.size());

	transform(0, 0) = scale_v;
	transform(1, 1) = scale_v;
	transform(0, 2) = centroid[0];
	transform(1, 2) = centroid[1];

	return transform;
}

template<size_t _size>
void homography_dlt_normalize(std::vector<cv::vectorx<real_t, _size> > &features, const cv::matrixr &S) {
	ASSERT(S && S.rows() == 3 && S.cols() == 3);
	cv::matrixr x(3, 1), xp(3, 1);
	for (unsigned i = 0; i < features.size(); ++i) {
		x(0, 0) = features[i][0];
		x(1, 0) = features[i][1];
		x(2, 0) = (_size == 3) ? features[i][2] : 1.;
		cross(S, x, xp);
		features[i][0] = xp(0, 0) / xp(2, 0);
		features[i][1] = xp(1, 0) / xp(2, 0);
		if(_size == 3)
			features[i][2] = 1.;
	}
}

cv::matrixr homography_dlt(const std::vector<cv::vec2r> &src_pts, const std::vector<cv::vec3r> &tgt_pts) {
	ASSERT(src_pts.size() >= 4 && src_pts.size() == tgt_pts.size());

	cv::matrixr H;

	// 0. Prepare data;
	cv::matrixr srcS, tgtS, invTgtS;
	cv::matrixr A = cv::matrixr::zeros(2 * src_pts.size(), 9);

	// 1. Perform normalization;
	srcS = homography_dlt_sim_estimation<2>(src_pts);
	tgtS = homography_dlt_sim_estimation<3>(tgt_pts);

	auto src_n = src_pts; // source normalized points
	auto tgt_n = tgt_pts; // target normalized points

	invTgtS = tgtS.clone();
	invert(invTgtS);

	homography_dlt_normalize<2>(src_n, srcS);
	homography_dlt_normalize<3>(tgt_n, tgtS);

	// 2. Pack matrix A;
	for (unsigned i = 0; i < src_pts.size(); ++i) {
		A(i * 2 + 0, 0) = -1 * src_n[i][0];
		A(i * 2 + 0, 1) = -1 * src_n[i][1];
		A(i * 2 + 0, 2) = -1;
		A(i * 2 + 0, 6) = tgt_n[i][0] * src_n[i][0];
		A(i * 2 + 0, 7) = tgt_n[i][0] * src_n[i][1];
		A(i * 2 + 0, 8) = tgt_n[i][0];

		A(i * 2 + 1, 3) = -1 * src_n[i][0];
		A(i * 2 + 1, 4) = -1 * src_n[i][1];
		A(i * 2 + 1, 5) = -1;
		A(i * 2 + 1, 6) = tgt_n[i][1] * src_n[i][0];
		A(i * 2 + 1, 7) = tgt_n[i][1] * src_n[i][1];
		A(i * 2 + 1, 8) = tgt_n[i][1];
	}

	// 3. solve nullspace of A for H;
	cv::null_solve(A, H);

	H.reshape(3, 3);

	// 4. denormalize the homography.
	H = invTgtS * H * srcS;

	return H;
}

/*
 * Pack homography matrices A and B by the form used for least squares solving.
 */
void pack_ab(const std::vector<cv::vec2r> &src_pts, const std::vector<cv::vec3r> &tgt_pts, cv::matrixr &A, cv::matrixr &B) {

	ASSERT(src_pts.size() && src_pts.size() == tgt_pts.size());

	// construct matrices
	A = cv::matrixr::zeros(src_pts.size() * 2, 8);
	B.create(src_pts.size() * 2, 1);

	// populate matrices with data.
	for (unsigned i = 0; i < src_pts.size(); i++) {

		auto &src = src_pts[i];
		auto &tgt = tgt_pts[i];

		B(i * 2, 0) = tgt[0];
		B(i * 2 + 1, 0) = tgt[1];

		A(i * 2, 0) = src[0];
		A(i * 2, 1) = src[1];
		A(i * 2, 2) = 1;
		A(i * 2 + 1, 3) = src[0];
		A(i * 2 + 1, 4) = src[1];
		A(i * 2 + 1, 5) = 1;

		A(i * 2, 6) = -1 * src[0] * tgt[0];
		A(i * 2, 7) = -1 * src[1] * tgt[0];
		A(i * 2 + 1, 6) = -1 * src[0] * tgt[1];
		A(i * 2 + 1, 7) = -1 * src[1] * tgt[1];
	}
}

/*
 * Solve homography using least squares method.
 */
cv::matrixr homography_least_squares(const std::vector<cv::vec2r> &src_pts, const std::vector<cv::vec3r> &tgt_pts) {

	cv::matrixr A, B, H;
	pack_ab(src_pts, tgt_pts, A, B);
	cv::matrixr _H(8, 1);

	cv::matrixr At = A.transposed();
	lu_solve(At * A, At * B, _H);

	if (!_H) {
		throw std::runtime_error("Internal error!~ failure occurred calculating homography.\n");
	}

	H.create(1, 9);
	std::copy(_H.begin(), _H.end(), H.begin());
	H.reshape(3, 3);
	H(2, 2) = 1;

	return H;
}

cv::matrixr homography_solve(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points, H_calc_alg alg) {
	switch (alg) {
	case HOMOGRAPHY_8_POINT:
		return homography_8_point(image_points, model_points);
	case HOMOGRAPHY_LEAST_SQUARES:
		return homography_least_squares(image_points, model_points);
	case HOMOGRAPHY_DLT:
		return homography_dlt(image_points, model_points);
	};
}

std::vector<cv::vec2r> source_pts;
std::vector<cv::vec3r> target_pts;

void reprojection_fcn(int m, int n, real_t* x, real_t* fvec,int *iflag) {

	if (*iflag == 0)
		return;

	// calculate m_projected
	cv::matrixd _H(3, 3, x); // borrow x and form matrix
	cv::matrixd ptn(3, 1), p_ptn(3, 1), res_ptn(3, 1);

	for (int i = 0; i < m; ++i) {
		ptn(0, 0) = target_pts[i][0]; // model point
		ptn(1, 0) = target_pts[i][1];
		ptn(2, 0) = target_pts[i][2];

		p_ptn(0, 0) = source_pts[i][0]; // photo projection point
		p_ptn(1, 0) = source_pts[i][1];
		p_ptn(2, 0) = 1.;

		cv::cross( _H, ptn, res_ptn);

		res_ptn(0, 0) /= res_ptn(2, 0);
		res_ptn(1, 0) /= res_ptn(2, 0);
		res_ptn(2, 0) = 1.;

		fvec[i] = sqrt(pow(p_ptn(0, 0) - res_ptn(0, 0), 2) + pow(p_ptn(1, 0) - res_ptn(1, 0), 2));
	}
}

int homography_optimize(const std::vector<cv::vec2r> &image_points, const std::vector<cv::vec3r> &model_points,
                        cv::matrixr &H, real_t tol) {

	source_pts = image_points;
	target_pts = model_points;

	ASSERT(source_pts.size() > 9);

	int m = source_pts.size();
	int n = 9;

	int info = 0;

	auto *_H = new real_t[n];

	for (int i = 0; i < 9; ++i) {
		_H[i] = H.data_begin()[i];
	}

	info = cv::lmdif1(reprojection_fcn, m, n, _H, tol);

	for (int i = 0; i < 9; ++i) {
		H.data_begin()[i] = _H[i];
	}

	H /= H(2, 2);

	delete [] _H;

	return info;
}

real_t calc_h_reprojection_error(const cv::matrixr &H, const std::vector<cv::vec2r> &source_pts, const std::vector<cv::vec3r> &target_pts) {

	ASSERT(source_pts.size() == target_pts.size() && H && H.rows() == 3 && H.cols() == 3);

	unsigned ptn_count = source_pts.size();
	real_t err = 0.0;

	// calculate m_projected
	cv::matrixr ptn(3, 1), p_ptn(3, 1), res_ptn(3, 1);

	for (unsigned i = 0; i < ptn_count; ++i) {
		ptn(0, 0) = source_pts[i][0];
		ptn(1, 0) = source_pts[i][1];
		ptn(2, 0) = 1.;

		p_ptn(0, 0) = target_pts[i][0];
		p_ptn(1, 0) = target_pts[i][1];
		p_ptn(2, 0) = target_pts[i][2];

		cv::cross( H, ptn, res_ptn);

		res_ptn(0, 0) /= res_ptn(2, 0);
		res_ptn(1, 0) /= res_ptn(2, 0);
		res_ptn(2, 0) = 1;

		err += cv::distance(res_ptn, p_ptn, cv::Norm::L2);
	}

	return err / ptn_count;
}

<|endoftext|>


<commit_before>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* rsGetRemoteZoneResc.c
 */

#include "getRemoteZoneResc.hpp"
#include "rodsLog.hpp"
#include "objMetaOpr.hpp"
#include "dataObjOpr.hpp"
#include "physPath.hpp"
#include "regDataObj.hpp"
#include "rcGlobalExtern.hpp"
#include "reGlobalsExtern.hpp"
#include "reDefines.hpp"
#include "dataObjCreate.hpp"
#include "dataObjOpen.hpp"

#include "irods_resource_redirect.hpp"

int
rsGetRemoteZoneResc( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
                     rodsHostAddr_t **rescAddr ) {
    char *remoteOprType;
    int status;
    rescInfo_t *rescInfo = NULL;
    rescGrpInfo_t *myRescGrpInfo = NULL;
    dataObjInfo_t *dataObjInfoHead = NULL;

    *rescAddr = NULL;
    if ( ( remoteOprType =
                getValByKey( &dataObjInp->condInput, REMOTE_ZONE_OPR_KW ) ) == NULL ) {
        rodsLog( LOG_ERROR,
                 "rsGetRemoteZoneResc: EMOTE_ZONE_OPR_KW not defined for %s",
                 dataObjInp->objPath );
        return ( USER_BAD_KEYWORD_ERR );
    }

    if ( strcmp( remoteOprType, REMOTE_CREATE ) == 0 ) {
        status = getRescGrpForCreate( rsComm, dataObjInp, &myRescGrpInfo );
        if ( status < 0 || NULL == myRescGrpInfo ) {
            return status;    // JMC cppcheck - nullptr
        }
        rescInfo = myRescGrpInfo->rescInfo;
    }
    else if ( strcmp( remoteOprType, REMOTE_OPEN ) == 0 ) {
        status = getDataObjInfoIncSpecColl( rsComm, dataObjInp,
                                            &dataObjInfoHead );
        if ( status < 0 ) {
            /* does not exist */
            status = getRescGrpForCreate( rsComm, dataObjInp, &myRescGrpInfo );
            if ( status < 0 || NULL == myRescGrpInfo ) {
                return status;    // JMC cppcheck - nullptr
            }
            rescInfo = myRescGrpInfo->rescInfo;
        }
        else {

            // =-=-=-=-=-=-=-
            // determine the hier string for the dest data obj inp
            std::string hier;
            irods::error ret = irods::resolve_resource_hierarchy( irods::OPEN_OPERATION, rsComm,
                               dataObjInp, hier );
            if ( !ret.ok() ) {
                std::stringstream msg;
                msg << "failed in irods::resolve_resource_hierarchy for [";
                msg << dataObjInp->objPath << "]";
                irods::log( PASSMSG( msg.str(), ret ) );
                return ret.code();
            }

            // =-=-=-=-=-=-=-
            // we resolved the hier str for subsequent api calls, etc.
            addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() );

            int writeFlag;
            /* exist */
            writeFlag = getWriteFlag( dataObjInp->openFlags );
            status = sortObjInfoForOpen( rsComm, &dataObjInfoHead, &dataObjInp->condInput, writeFlag );

            if ( status < 0 ) {
                return status;
            }
            status = applyPreprocRuleForOpen( rsComm, dataObjInp,
                                              &dataObjInfoHead );
            if ( status < 0 || NULL == dataObjInfoHead ) { // JMC cppcheck - nullptr
                freeAllDataObjInfo( dataObjInfoHead );
                return status;
            }
            else {
                rescInfo = dataObjInfoHead->rescInfo;
                freeAllDataObjInfo( dataObjInfoHead );
            }
        }
    }
    else {
        rodsLog( LOG_ERROR,
                 "rsGetRemoteZoneResc: bad EMOTE_ZONE_OPR_KW %s for %s",
                 remoteOprType, dataObjInp->objPath );
        return ( USER_BAD_KEYWORD_ERR );
    }
    *rescAddr = ( rodsHostAddr_t* )malloc( sizeof( rodsHostAddr_t ) );
    bzero( *rescAddr, sizeof( rodsHostAddr_t ) );
    rstrcpy( ( *rescAddr )->hostAddr, rescInfo->rescLoc, NAME_LEN );
    rstrcpy( ( *rescAddr )->zoneName, ZoneInfoHead->zoneName, NAME_LEN );
    if ( myRescGrpInfo != NULL ) {
        freeAllRescGrpInfo( myRescGrpInfo );
    }

    return ( 0 );
}

<commit_msg>[#2008] resolve resource hierarchy for both cross zone create and write operations<commit_after>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* rsGetRemoteZoneResc.c
 */

#include "getRemoteZoneResc.hpp"
#include "rodsLog.hpp"
#include "objMetaOpr.hpp"
#include "dataObjOpr.hpp"
#include "physPath.hpp"
#include "regDataObj.hpp"
#include "rcGlobalExtern.hpp"
#include "reGlobalsExtern.hpp"
#include "reDefines.hpp"
#include "dataObjCreate.hpp"
#include "dataObjOpen.hpp"

#include "irods_resource_redirect.hpp"
#include "irods_resource_backport.hpp"

int
rsGetRemoteZoneResc( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
                     rodsHostAddr_t **rescAddr ) {
    //rescInfo_t *rescInfo = NULL;
    //rescGrpInfo_t *myRescGrpInfo = NULL;

    // =-=-=-=-=-=-=-
    // acquire the operation requested
    char* remoteOprType = getValByKey(
                              &dataObjInp->condInput,
                              REMOTE_ZONE_OPR_KW );
    if ( !remoteOprType ) {
        rodsLog( LOG_ERROR,
                 "rsGetRemoteZoneResc: REMOTE_ZONE_OPR_KW not defined for %s",
                 dataObjInp->objPath );
        return ( USER_BAD_KEYWORD_ERR );
    }

    // =-=-=-=-=-=-=-
    // try to open the object in question, otherwise it is a create
    int status = 0;
    bool do_sort = false;  // only on open
    std::string oper = irods::CREATE_OPERATION;
    dataObjInfo_t *dataObjInfoHead = NULL;
    if ( strcmp( remoteOprType, REMOTE_OPEN ) == 0 ) {
        status = getDataObjInfoIncSpecColl(
                     rsComm,
                     dataObjInp,
                     &dataObjInfoHead );
        if ( status >= 0 ) {
            do_sort = true;
            oper = irods::OPEN_OPERATION;
        }
    }

    // =-=-=-=-=-=-=-
    // determine the hier string for the dest data obj inp
    std::string hier;
    irods::error ret = irods::resolve_resource_hierarchy(
                           oper,
                           rsComm,
                           dataObjInp,
                           hier );
    if ( !ret.ok() ) {
        std::stringstream msg;
        msg << "failed for [";
        msg << dataObjInp->objPath << "]";
        irods::log( PASSMSG( msg.str(), ret ) );
        return ret.code();
    }

    // =-=-=-=-=-=-=-
    // we resolved the hier str for subsequent api calls, etc.
    addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() );

    // =-=-=-=-=-=-=-
    // we resolved the hier str for subsequent api calls, etc.
    std::string location;
    ret = irods::get_loc_for_hier_string( hier, location );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();
    }

    // =-=-=-=-=-=-=-
    // if this was an open then run the sort and override the location
    if ( do_sort ) {
        int writeFlag;
        writeFlag = getWriteFlag( dataObjInp->openFlags );
        status = sortObjInfoForOpen(
                     rsComm,
                     &dataObjInfoHead,
                     &dataObjInp->condInput,
                     writeFlag );
        if ( status < 0 ) {
            rodsLog(
                LOG_ERROR,
                "rsGetRemoteZoneResc - sortObjInfoForOpen failed for [%s]",
                dataObjInp->objPath );
            return status;
        }

        location = dataObjInfoHead->rescInfo->rescLoc;
    }

    // =-=-=-=-=-=-=-
    // set the out variable
    *rescAddr = ( rodsHostAddr_t* )malloc( sizeof( rodsHostAddr_t ) );
    bzero( *rescAddr, sizeof( rodsHostAddr_t ) );
    rstrcpy( ( *rescAddr )->hostAddr, location.c_str(),       NAME_LEN );
    rstrcpy( ( *rescAddr )->zoneName, ZoneInfoHead->zoneName, NAME_LEN );

    return 0;

}

<|endoftext|>


<commit_before>#define TEST_CATEGORY TDataFrameSeq
#include "dataframe_simple_tests.hxx"

#ifdef R__USE_IMT

#include "TROOT.h"
TEST(dataframe_simple, EnableImplicitMT)
{
   ROOT::EnableImplicitMT();
}

#undef TEST_CATEGORY
#define TEST_CATEGORY TDataFrameMT
#include "dataframe_simple_tests.hxx"

#endif
<commit_msg>[TDF] Limit pool size to 4 workers<commit_after>#define TEST_CATEGORY TDataFrameSeq
#include "dataframe_simple_tests.hxx"

#ifdef R__USE_IMT

#include "TROOT.h"
TEST(dataframe_simple, EnableImplicitMT)
{
   ROOT::EnableImplicitMT(4);
}

#undef TEST_CATEGORY
#define TEST_CATEGORY TDataFrameMT
#include "dataframe_simple_tests.hxx"

#endif
<|endoftext|>


<commit_before>#include "wayland.h"
#include <../x/x_keycodes.h>

#include <iostream>
#include <algorithm>

#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <linux/input-event-codes.h>

#include <QuickDraw.h>
#include <quickdraw/region.h>

using namespace wayland;
using namespace Executor;

WaylandVideoDriver::SharedMem::SharedMem(size_t size)
    : size_(size)
{
    fd_ = memfd_create("executor", MFD_CLOEXEC);
    ftruncate(fd_, size_);
    mem_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
}

WaylandVideoDriver::SharedMem::~SharedMem()
{
    if(mem_)
    {
        munmap(mem_, size_);
        close(fd_);
    }
}

WaylandVideoDriver::Buffer::Buffer(shm_t& shm, int w, int h)
    : mem_(w * h * 4),
    wlbuffer_(shm.create_pool(mem_.fd(), mem_.size())
            .create_buffer(0, w, h, w*4, wayland::shm_format::argb8888)),
    width_(w), height_(h)
{
}

void WaylandVideoDriver::setColors(int num_colors, const Executor::vdriver_color_t *color_array)
{
    for(int i = 0; i < num_colors; i++)
    {
        colors_[i] = (0xFF << 24)
                    | ((color_array[i].red >> 8) << 16)
                    | ((color_array[i].green >> 8) << 8)
                    | (color_array[i].blue >> 8);
    }
}

bool WaylandVideoDriver::setMode(int width, int height, int bpp,
                                  bool grayscale_p)
{
    if(xdg_wm_base_)
        return true;

    rootlessRegion_ = { 0, 0, RGN_STOP, RGN_STOP };

    registry_ = display_.get_registry();
    registry_.on_global() = [this] (uint32_t name, const std::string& interface, uint32_t version) {
            if(interface == compositor_t::interface_name)
                registry_.bind(name, compositor_, version);
            else if(interface == shell_t::interface_name)
                registry_.bind(name, shell_, version);
            else if(interface == xdg_wm_base_t::interface_name)
                registry_.bind(name, xdg_wm_base_, version);
            else if(interface == seat_t::interface_name)
                registry_.bind(name, seat_, version);
            else if(interface == shm_t::interface_name)
                registry_.bind(name, shm_, version);
            // TODO: handle changes
        };
    display_.roundtrip();

    // TODO:
    xdg_wm_base_.on_ping() = [this] (uint32_t serial) { xdg_wm_base_.pong(serial); };

    surface_ = compositor_.create_surface();
    xdg_surface_ = xdg_wm_base_.get_xdg_surface(surface_);
    xdg_toplevel_ = xdg_surface_.get_toplevel();
    xdg_toplevel_.set_title("Executor");
    xdg_toplevel_.set_app_id("io.github.autc04.executor");

    xdg_toplevel_.on_configure() = [this] (int32_t x, int32_t y, array_t states) {
        //configuredX = std::max(0,x);
        //configuredY = std::max(0,y);

        if(x && y && !initDone_)
        {
            width_ = x;
            height_ = y;
        }

        std::vector<xdg_toplevel_state> states1 = states;

        std::cout << "toplevel configure " << x << " " << y << "\n";

    };

    auto fillBuffer = [this](Buffer& buf) {
        //uint32_t colors[] = { 0xFFFFFF00, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0x80808080 };
        int w = buf.width(), h = buf.height();
        uint32_t color = 0x80808080;//colors[colorIdx];
        for(int y = 0; y < h; y++)
            for(int x = 0; x < w; x++)
            {
                uint32_t& pixel = ((uint32_t*)buf.data())[y * w + x];
                if(x < w/3 || x > 2*w/3)
                    pixel = color;
                else
                    pixel = 0;
            }
    };

    xdg_surface_.on_configure() = [this, fillBuffer] (uint32_t serial) {
        xdg_surface_.ack_configure(serial);

        if(width_ == buffer_.width() && height_ == buffer_.height())
            return;

        //updateScreenRects(0,nullptr,false);

        buffer_ = Buffer(shm_, width_, height_);

        fillBuffer(buffer_);

        surface_.attach(buffer_.wlbuffer(), 0, 0);
        surface_.commit();
    };
    xdg_toplevel_.on_close() = [this] () { };

    pointer_ = seat_.get_pointer();
    pointer_.on_button() = [this] (uint32_t serial, uint32_t time, uint32_t button, pointer_button_state state) {
        std::cout << "button: " << button << " " << (int)state << std::endl;
        if(button == BTN_LEFT)
            callbacks_->mouseButtonEvent(state == pointer_button_state::pressed);
    };
    pointer_.on_motion() = [this] (uint32_t serial, double x, double y) {
        std::cout << "motion: " << x << " " << y << std::endl;
        callbacks_->mouseMoved(x, y);
    };

    keyboard_ = seat_.get_keyboard();
    keyboard_.on_key() = [this] (uint32_t serial, uint32_t time, uint32_t key, keyboard_key_state state) {
        bool down = state == keyboard_key_state::pressed;

        std::cout << "key: " << std::hex << key << std::dec << " " << (down ? "down" : "up") << std::endl;

        auto mkvkey = x_keycode_to_mac_virt[key + 8];

        callbacks_->keyboardEvent(down, mkvkey);
    };

    keyboard_.on_enter() = [this] (uint32_t serial, wayland::surface_t, wayland::array_t) {
        callbacks_->resumeEvent(true);
    };

    keyboard_.on_leave() = [this] (uint32_t serial, wayland::surface_t) {
        callbacks_->suspendEvent();
    };

    width_ = 1024;
    height_ = 768;
    bpp_ = 8;

    xdg_toplevel_.set_maximized();

	surface_.commit();

    cursorBuffer_ = Buffer(shm_, 16,16);
    cursorSurface_ = compositor_.create_surface();
    hotSpot_ = {0,0};

    display_.roundtrip();

    cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);
    cursorSurface_.commit();
    //pointer_.set_cursor(0, cursorSurface_, hotSpot_.first, hotSpot_.second);
    //display_.roundtrip();
    pointer_.on_enter() = [this](uint32_t serial, surface_t surface, double x, double y) {
        pointer_.set_cursor(serial, cursorSurface_, hotSpot_.first, hotSpot_.second);
        cursorEnterSerial_ = serial;
    };

    rowBytes_ = ((width_ * bpp_ + 31) & ~31) / 8;
    framebuffer_ = new uint8_t[rowBytes_ * height_];
    initDone_ = true;

    isRootless_ = true;
    return true;
}

void WaylandVideoDriver::pumpEvents()
{
    //display_.dispatch();
    display_.roundtrip();
}

void WaylandVideoDriver::setRootlessRegion(RgnHandle rgn)
{
    if((*rgn)->rgnSize == 10)
    {
        rootlessRegion_.clear();
        rootlessRegion_.insert(rootlessRegion_.end(),
            { (*rgn)->rgnBBox.top.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), RGN_STOP,
            (*rgn)->rgnBBox.bottom.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), RGN_STOP,
            RGN_STOP });
    }
    else
    {
        GUEST<uint16_t> *p = (GUEST<uint16_t>*) ((*(Handle)rgn) + 10);
        GUEST<uint16_t> *q = (GUEST<uint16_t>*) ((*(Handle)rgn) + (*rgn)->rgnSize);
        rootlessRegion_.clear();
        rootlessRegion_.insert(rootlessRegion_.end(), p, q);
    }

    RegionProcessor rgnP(rootlessRegion_.begin());

    region_t waylandRgn = compositor_.create_region();

    while(rgnP.bottom() < height_)
    {
        rgnP.advance();

        for(int i = 0; i + 1 < rgnP.row.size(); i += 2)
            waylandRgn.add(rgnP.row[i], rgnP.top(), rgnP.row[i+1] - rgnP.row[i], rgnP.bottom() - rgnP.top());
    }

    surface_.set_input_region(waylandRgn);
}

void WaylandVideoDriver::updateScreenRects(
    int num_rects, const vdriver_rect_t *r,
    bool cursor_p)
{
    std::cout << "update.\n";
    uint32_t *screen = reinterpret_cast<uint32_t*>(buffer_.data());

    RegionProcessor rgnP(rootlessRegion_.begin());

    for(int y = 0; y < height_; y++)
    {
        while(y >= rgnP.bottom())
            rgnP.advance();

        auto rowIt = rgnP.row.begin();
        int x = 0;

        while(x < width_)
        {
            int nextX = std::min(width_, (int)*rowIt++);

            for(; x < nextX; x++)
            {
                uint32_t pixel = colors_[framebuffer_[y * rowBytes_ + x]];
                screen[y * width_ + x] = pixel == 0xFFFFFFFF ? 0 : pixel;
            }

            if(x >= width_)
                break;

            nextX = std::min(width_, (int)*rowIt++);

            for(; x < nextX; x++)
                screen[y * width_ + x] = colors_[framebuffer_[y * rowBytes_ + x]];
        }
    }

    for(int i = 0; i < num_rects; i++)
        surface_.damage_buffer(r[i].left,r[i].top,r[i].right-r[i].left,r[i].bottom-r[i].top);
    surface_.attach(buffer_.wlbuffer(), 0, 0);
    surface_.commit();
    display_.flush();
}

void WaylandVideoDriver::setCursor(char *cursor_data, uint16_t cursor_mask[16], int hotspot_x, int hotspot_y)
{
    uint32_t *dst = reinterpret_cast<uint32_t*>(cursorBuffer_.data());
    uint8_t *data = reinterpret_cast<uint8_t*>(cursor_data);
    uint8_t *mask = reinterpret_cast<uint8_t*>(cursor_mask);
    for(int y = 0; y < 16; y++)
        for(int x = 0; x < 16; x++)
        {
            if(mask[2*y + x/8] & (0x80 >> x%8))
                *dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0xFFFFFFFF;
            else
                *dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0;
        }
    cursorSurface_.damage_buffer(0,0,16,16);
    cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);

    hotSpot_ = { hotspot_x, hotspot_y };
    cursorSurface_.commit();
    pointer_.set_cursor(cursorEnterSerial_, cursorSurface_, hotSpot_.first, hotSpot_.second);
}

bool WaylandVideoDriver::setCursorVisible(bool show_p)
{
    pointer_.set_cursor(cursorEnterSerial_, show_p ? cursorSurface_ : surface_t(), hotSpot_.first, hotSpot_.second);
    return true;
}
<commit_msg>wayland: update only the blit rects, support all depths<commit_after>#include "wayland.h"
#include <../x/x_keycodes.h>

#include <iostream>
#include <algorithm>

#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <linux/input-event-codes.h>

#include <QuickDraw.h>
#include <quickdraw/region.h>

using namespace wayland;
using namespace Executor;

WaylandVideoDriver::SharedMem::SharedMem(size_t size)
    : size_(size)
{
    fd_ = memfd_create("executor", MFD_CLOEXEC);
    ftruncate(fd_, size_);
    mem_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
}

WaylandVideoDriver::SharedMem::~SharedMem()
{
    if(mem_)
    {
        munmap(mem_, size_);
        close(fd_);
    }
}

WaylandVideoDriver::Buffer::Buffer(shm_t& shm, int w, int h)
    : mem_(w * h * 4),
    wlbuffer_(shm.create_pool(mem_.fd(), mem_.size())
            .create_buffer(0, w, h, w*4, wayland::shm_format::argb8888)),
    width_(w), height_(h)
{
}

void WaylandVideoDriver::setColors(int num_colors, const Executor::vdriver_color_t *color_array)
{
    for(int i = 0; i < num_colors; i++)
    {
        colors_[i] = (0xFF << 24)
                    | ((color_array[i].red >> 8) << 16)
                    | ((color_array[i].green >> 8) << 8)
                    | (color_array[i].blue >> 8);
    }
}

bool WaylandVideoDriver::setMode(int width, int height, int bpp,
                                  bool grayscale_p)
{
    if(xdg_wm_base_)
        return true;

    rootlessRegion_ = { 0, 0, RGN_STOP, RGN_STOP };

    registry_ = display_.get_registry();
    registry_.on_global() = [this] (uint32_t name, const std::string& interface, uint32_t version) {
            if(interface == compositor_t::interface_name)
                registry_.bind(name, compositor_, version);
            else if(interface == shell_t::interface_name)
                registry_.bind(name, shell_, version);
            else if(interface == xdg_wm_base_t::interface_name)
                registry_.bind(name, xdg_wm_base_, version);
            else if(interface == seat_t::interface_name)
                registry_.bind(name, seat_, version);
            else if(interface == shm_t::interface_name)
                registry_.bind(name, shm_, version);
            // TODO: handle changes
        };
    display_.roundtrip();

    // TODO:
    xdg_wm_base_.on_ping() = [this] (uint32_t serial) { xdg_wm_base_.pong(serial); };

    surface_ = compositor_.create_surface();
    xdg_surface_ = xdg_wm_base_.get_xdg_surface(surface_);
    xdg_toplevel_ = xdg_surface_.get_toplevel();
    xdg_toplevel_.set_title("Executor");
    xdg_toplevel_.set_app_id("io.github.autc04.executor");

    xdg_toplevel_.on_configure() = [this] (int32_t x, int32_t y, array_t states) {
        //configuredX = std::max(0,x);
        //configuredY = std::max(0,y);

        if(x && y && !initDone_)
        {
            width_ = x;
            height_ = y;
        }

        std::vector<xdg_toplevel_state> states1 = states;

        std::cout << "toplevel configure " << x << " " << y << "\n";

    };

    auto fillBuffer = [this](Buffer& buf) {
        //uint32_t colors[] = { 0xFFFFFF00, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0x80808080 };
        int w = buf.width(), h = buf.height();
        uint32_t color = 0x80808080;//colors[colorIdx];
        for(int y = 0; y < h; y++)
            for(int x = 0; x < w; x++)
            {
                uint32_t& pixel = ((uint32_t*)buf.data())[y * w + x];
                if(x < w/3 || x > 2*w/3)
                    pixel = color;
                else
                    pixel = 0;
            }
    };

    xdg_surface_.on_configure() = [this, fillBuffer] (uint32_t serial) {
        xdg_surface_.ack_configure(serial);

        if(width_ == buffer_.width() && height_ == buffer_.height())
            return;

        //updateScreenRects(0,nullptr,false);

        buffer_ = Buffer(shm_, width_, height_);

        fillBuffer(buffer_);

        surface_.attach(buffer_.wlbuffer(), 0, 0);
        surface_.commit();
    };
    xdg_toplevel_.on_close() = [this] () { };

    pointer_ = seat_.get_pointer();
    pointer_.on_button() = [this] (uint32_t serial, uint32_t time, uint32_t button, pointer_button_state state) {
        std::cout << "button: " << button << " " << (int)state << std::endl;
        if(button == BTN_LEFT)
            callbacks_->mouseButtonEvent(state == pointer_button_state::pressed);
    };
    pointer_.on_motion() = [this] (uint32_t serial, double x, double y) {
        std::cout << "motion: " << x << " " << y << std::endl;
        callbacks_->mouseMoved(x, y);
    };

    keyboard_ = seat_.get_keyboard();
    keyboard_.on_key() = [this] (uint32_t serial, uint32_t time, uint32_t key, keyboard_key_state state) {
        bool down = state == keyboard_key_state::pressed;

        std::cout << "key: " << std::hex << key << std::dec << " " << (down ? "down" : "up") << std::endl;

        auto mkvkey = x_keycode_to_mac_virt[key + 8];

        callbacks_->keyboardEvent(down, mkvkey);
    };

    keyboard_.on_enter() = [this] (uint32_t serial, wayland::surface_t, wayland::array_t) {
        callbacks_->resumeEvent(true);
    };

    keyboard_.on_leave() = [this] (uint32_t serial, wayland::surface_t) {
        callbacks_->suspendEvent();
    };

    width_ = 1024;
    height_ = 768;
    bpp_ = bpp ? bpp : 8;

    xdg_toplevel_.set_maximized();

	surface_.commit();

    cursorBuffer_ = Buffer(shm_, 16,16);
    cursorSurface_ = compositor_.create_surface();
    hotSpot_ = {0,0};

    display_.roundtrip();

    cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);
    cursorSurface_.commit();
    //pointer_.set_cursor(0, cursorSurface_, hotSpot_.first, hotSpot_.second);
    //display_.roundtrip();
    pointer_.on_enter() = [this](uint32_t serial, surface_t surface, double x, double y) {
        pointer_.set_cursor(serial, cursorSurface_, hotSpot_.first, hotSpot_.second);
        cursorEnterSerial_ = serial;
    };

    rowBytes_ = ((width_ * bpp_ + 31) & ~31) / 8;
    framebuffer_ = new uint8_t[rowBytes_ * height_];
    initDone_ = true;

    isRootless_ = true;
    return true;
}

void WaylandVideoDriver::pumpEvents()
{
    //display_.dispatch();
    display_.roundtrip();
}

void WaylandVideoDriver::setRootlessRegion(RgnHandle rgn)
{
    if((*rgn)->rgnSize == 10)
    {
        rootlessRegion_.clear();
        rootlessRegion_.insert(rootlessRegion_.end(),
            { (*rgn)->rgnBBox.top.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), RGN_STOP,
            (*rgn)->rgnBBox.bottom.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), RGN_STOP,
            RGN_STOP });
    }
    else
    {
        GUEST<uint16_t> *p = (GUEST<uint16_t>*) ((*(Handle)rgn) + 10);
        GUEST<uint16_t> *q = (GUEST<uint16_t>*) ((*(Handle)rgn) + (*rgn)->rgnSize);
        rootlessRegion_.clear();
        rootlessRegion_.insert(rootlessRegion_.end(), p, q);
    }

    RegionProcessor rgnP(rootlessRegion_.begin());

    region_t waylandRgn = compositor_.create_region();

    while(rgnP.bottom() < height_)
    {
        rgnP.advance();

        for(int i = 0; i + 1 < rgnP.row.size(); i += 2)
            waylandRgn.add(rgnP.row[i], rgnP.top(), rgnP.row[i+1] - rgnP.row[i], rgnP.bottom() - rgnP.top());
    }

    surface_.set_input_region(waylandRgn);
}

template<int depth>
struct IndexedPixelGetter
{
    uint8_t *src;
    int shift;
    std::array<uint32_t, 256>& colors;

    static constexpr uint8_t mask = (1 << depth) - 1;

    IndexedPixelGetter(std::array<uint32_t, 256>& colors, uint8_t *line, int x)
        : colors(colors)
    {
        src = line + x * depth / 8;
        shift = 8 - (x * depth % 8) - depth;
    }

    uint32_t operator() ()
    {
        auto c = colors[(*src >> shift) & mask];
        shift -= depth;
        if(shift < 0)
        {
            ++src;
            shift = 8 - depth;
        }
        return c;
    }
};

void WaylandVideoDriver::updateScreenRects(
    int num_rects, const vdriver_rect_t *r,
    bool cursor_p)
{
    std::cout << "update.\n";
    for(int i = 0; i < num_rects; i++)
        std::cout << r[i].left << ", " << r[i].top << " - " << r[i].right << ", " << r[i].bottom << std::endl;
    uint32_t *screen = reinterpret_cast<uint32_t*>(buffer_.data());

    for(int i = 0; i < num_rects; i++)
    {
        RegionProcessor rgnP(rootlessRegion_.begin());

        for(int y = r[i].top; y < r[i].bottom; y++)
        {
            while(y >= rgnP.bottom())
                rgnP.advance();

            auto blitLine = [this, &rgnP, screen, y, r, i](auto getPixel) {
                auto rowIt = rgnP.row.begin();
                int x = r[i].left;

                while(x < r[i].right)
                {
                    int nextX = std::min(r[i].right, (int)*rowIt++);

                    for(; x < nextX; x++)
                    {
                        uint32_t pixel = getPixel();
                        screen[y * width_ + x] = pixel == 0xFFFFFFFF ? 0 : pixel;
                    }

                    if(x >= r[i].right)
                        break;

                    nextX = std::min(r[i].right, (int)*rowIt++);

                    for(; x < nextX; x++)
                        screen[y * width_ + x] = getPixel();
                }
            };

            uint8_t *src = framebuffer_ + y * rowBytes_;
            switch(bpp_)
            {
                case 8:
                    src += r[i].left;
                    blitLine([&] { return colors_[*src++]; });
                    break;

                case 1:
                    blitLine(IndexedPixelGetter<1>(colors_, src, r[i].left));
                    break;
                case 2:
                    blitLine(IndexedPixelGetter<2>(colors_, src, r[i].left));
                    break;
                case 4:
                    blitLine(IndexedPixelGetter<4>(colors_, src, r[i].left));
                    break;
                case 16:
                    {
                        auto *src16 = reinterpret_cast<GUEST<uint16_t>*>(src);
                        src16 += r[i].left;
                        blitLine([&] {
                            uint16_t pix = *src16++;
                            auto fiveToEight = [](uint32_t x) {
                                return (x << 3) | (x >> 2);
                            };
                            return 0xFF000000
                                | (fiveToEight((pix >> 10) & 31) << 16)
                                | (fiveToEight((pix >> 5) & 31) << 8)
                                | fiveToEight(pix & 31);
                        });
                    }
                    break;

                case 32:
                    {
                        auto *src32 = reinterpret_cast<GUEST<uint32_t>*>(src);
                        src32 += r[i].left;
                        blitLine([&] { return (*src32++) | 0xFF000000; });
                    }
                    break;

            }
        }
    }

    for(int i = 0; i < num_rects; i++)
        surface_.damage_buffer(r[i].left,r[i].top,r[i].right-r[i].left,r[i].bottom-r[i].top);
    surface_.attach(buffer_.wlbuffer(), 0, 0);
    surface_.commit();
    display_.flush();
}

void WaylandVideoDriver::setCursor(char *cursor_data, uint16_t cursor_mask[16], int hotspot_x, int hotspot_y)
{
    uint32_t *dst = reinterpret_cast<uint32_t*>(cursorBuffer_.data());
    uint8_t *data = reinterpret_cast<uint8_t*>(cursor_data);
    uint8_t *mask = reinterpret_cast<uint8_t*>(cursor_mask);
    for(int y = 0; y < 16; y++)
        for(int x = 0; x < 16; x++)
        {
            if(mask[2*y + x/8] & (0x80 >> x%8))
                *dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0xFFFFFFFF;
            else
                *dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0;
        }
    cursorSurface_.damage_buffer(0,0,16,16);
    cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);

    hotSpot_ = { hotspot_x, hotspot_y };
    cursorSurface_.commit();
    pointer_.set_cursor(cursorEnterSerial_, cursorSurface_, hotSpot_.first, hotSpot_.second);
}

bool WaylandVideoDriver::setCursorVisible(bool show_p)
{
    pointer_.set_cursor(cursorEnterSerial_, show_p ? cursorSurface_ : surface_t(), hotSpot_.first, hotSpot_.second);
    return true;
}
<|endoftext|>


<commit_before>/*
Copyright libCellML Contributors

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 "operatorlibrary.h"

#include <limits>

namespace libcellml {

namespace operators {

BinaryOperator::BinaryOperator() :
    mArg1(RepresentablePtr()),
    mArg2(RepresentablePtr())
{}

ArithmeticOperator::ArithmeticOperator(std::string op) :
    BinaryOperator(),
    mOp(op)
{}

std::string ArithmeticOperator::repr()
{
    return "(" + mArg1->repr() + " " + mOp + " " + mArg2->repr() + ")";
}

Addition::Addition() :
    ArithmeticOperator(std::string("+"))
{}

Subtraction::Subtraction() :
    ArithmeticOperator(std::string("-"))
{}

Multiplication::Multiplication() :
    ArithmeticOperator(std::string("*"))
{}

Division::Division() :
    ArithmeticOperator(std::string("/"))
{}

And::And() :
    ArithmeticOperator(std::string("&&"))
{}

Or::Or() :
    ArithmeticOperator(std::string("||"))
{}

Less::Less() :
    ArithmeticOperator(std::string("<"))
{}

LessOrEqual::LessOrEqual() :
    ArithmeticOperator(std::string("<="))
{}

GreaterOrEqual::GreaterOrEqual() :
    ArithmeticOperator(std::string(">="))
{}

Greater::Greater() :
    ArithmeticOperator(std::string(">"))
{}

Power::Power() :
    BinaryOperator()
{}

std::string Power::repr()
{
    return "std::pow(" + mArg1->repr() + ", " + mArg2->repr() + ")";
}

UnaryOperator::UnaryOperator() :
    mArg(RepresentablePtr())
{}

Positive::Positive() :
    UnaryOperator()
{}

std::string Positive::repr()
{
    return "+(" + mArg->repr() + ")";
}

Negative::Negative() :
    UnaryOperator()
{}

std::string Negative::repr()
{
    return "-(" + mArg->repr() + ")";
}

Not::Not() :
    UnaryOperator()
{}

std::string Not::repr()
{
    return "!(" + mArg->repr() + ")";
}

StdOperator::StdOperator(std::string fun) :
    UnaryOperator(),
    fun(fun)
{}

std::string StdOperator::repr()
{
    return "std::" + fun + "(" + mArg->repr() + ")";
}

AbsoluteValue::AbsoluteValue() :
    StdOperator(std::string("abs"))
{}

Sine::Sine() :
    StdOperator(std::string("sin"))
{}

Cosine::Cosine() :
    StdOperator(std::string("cos"))
{}

Floor::Floor() :
    StdOperator(std::string("floor"))
{}

Variable::Variable(std::string name) : name(name)
{}

std::string Variable::repr()
{
    return name;
}

Constant::Constant (double val) : value(val)
{}

std::string Constant::repr()
{
    std::ostringstream oss;
    oss << std::setprecision(std::numeric_limits<double>::max_digits10) << value;
    return oss.str();
}

Derivative::Derivative (std::string variableName) :
    mVariableName(variableName)
{}

std::string Derivative::repr()
{
    return "D" + mVariableName;
}

Equation::Equation() :
    BinaryOperator()
{}

std::string Equation::repr()
{
    return mArg1->repr() + " = " + mArg2->repr();
}

}

}
<commit_msg>Explain why we shouldn't be using the C++11 way of converting a double to a std::string.<commit_after>/*
Copyright libCellML Contributors

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 "operatorlibrary.h"

#include <limits>

namespace libcellml {

namespace operators {

BinaryOperator::BinaryOperator() :
    mArg1(RepresentablePtr()),
    mArg2(RepresentablePtr())
{}

ArithmeticOperator::ArithmeticOperator(std::string op) :
    BinaryOperator(),
    mOp(op)
{}

std::string ArithmeticOperator::repr()
{
    return "(" + mArg1->repr() + " " + mOp + " " + mArg2->repr() + ")";
}

Addition::Addition() :
    ArithmeticOperator(std::string("+"))
{}

Subtraction::Subtraction() :
    ArithmeticOperator(std::string("-"))
{}

Multiplication::Multiplication() :
    ArithmeticOperator(std::string("*"))
{}

Division::Division() :
    ArithmeticOperator(std::string("/"))
{}

And::And() :
    ArithmeticOperator(std::string("&&"))
{}

Or::Or() :
    ArithmeticOperator(std::string("||"))
{}

Less::Less() :
    ArithmeticOperator(std::string("<"))
{}

LessOrEqual::LessOrEqual() :
    ArithmeticOperator(std::string("<="))
{}

GreaterOrEqual::GreaterOrEqual() :
    ArithmeticOperator(std::string(">="))
{}

Greater::Greater() :
    ArithmeticOperator(std::string(">"))
{}

Power::Power() :
    BinaryOperator()
{}

std::string Power::repr()
{
    return "std::pow(" + mArg1->repr() + ", " + mArg2->repr() + ")";
}

UnaryOperator::UnaryOperator() :
    mArg(RepresentablePtr())
{}

Positive::Positive() :
    UnaryOperator()
{}

std::string Positive::repr()
{
    return "+(" + mArg->repr() + ")";
}

Negative::Negative() :
    UnaryOperator()
{}

std::string Negative::repr()
{
    return "-(" + mArg->repr() + ")";
}

Not::Not() :
    UnaryOperator()
{}

std::string Not::repr()
{
    return "!(" + mArg->repr() + ")";
}

StdOperator::StdOperator(std::string fun) :
    UnaryOperator(),
    fun(fun)
{}

std::string StdOperator::repr()
{
    return "std::" + fun + "(" + mArg->repr() + ")";
}

AbsoluteValue::AbsoluteValue() :
    StdOperator(std::string("abs"))
{}

Sine::Sine() :
    StdOperator(std::string("sin"))
{}

Cosine::Cosine() :
    StdOperator(std::string("cos"))
{}

Floor::Floor() :
    StdOperator(std::string("floor"))
{}

Variable::Variable(std::string name) : name(name)
{}

std::string Variable::repr()
{
    return name;
}

Constant::Constant (double val) : value(val)
{}

std::string Constant::repr()
{
    // Use the C++03 way of converting a double to a std::string rather than the
    // C++11 way (i.e. std::to_string()). Indeed, the latter has too many
    // limitations (e.g. 23.43 ---> 23.430000, 1e-09 ---> 0.000000), as can be
    // seen at https://en.cppreference.com/w/cpp/string/basic_string/to_string.
    std::ostringstream oss;
    oss << std::setprecision(std::numeric_limits<double>::max_digits10) << value;
    return oss.str();
}

Derivative::Derivative (std::string variableName) :
    mVariableName(variableName)
{}

std::string Derivative::repr()
{
    return "D" + mVariableName;
}

Equation::Equation() :
    BinaryOperator()
{}

std::string Equation::repr()
{
    return mArg1->repr() + " = " + mArg2->repr();
}

}

}
<|endoftext|>


<commit_before>/*
 * xtensor-fftw
 * Copyright (c) 2017, Patrick Bos
 * Distributed under the terms of the BSD 3-Clause License.
 *
 * The full license is in the file LICENSE, distributed with this software.
 */

#ifndef XTENSOR_FFTW_CONFIG_HPP
#define XTENSOR_FFTW_CONFIG_HPP

#define XTENSOR_FFTW_VERSION_MAJOR 0
#define XTENSOR_FFTW_VERSION_MINOR 1
#define XTENSOR_FFTW_VERSION_PATCH 1

#endif //XTENSOR_FFTW_CONFIG_HPP
<commit_msg>Release 0.1.2<commit_after>/*
 * xtensor-fftw
 * Copyright (c) 2017, Patrick Bos
 * Distributed under the terms of the BSD 3-Clause License.
 *
 * The full license is in the file LICENSE, distributed with this software.
 */

#ifndef XTENSOR_FFTW_CONFIG_HPP
#define XTENSOR_FFTW_CONFIG_HPP

#define XTENSOR_FFTW_VERSION_MAJOR 0
#define XTENSOR_FFTW_VERSION_MINOR 1
#define XTENSOR_FFTW_VERSION_PATCH 2

#endif //XTENSOR_FFTW_CONFIG_HPP
<|endoftext|>