<commit_before>#include "BetaRand.h"

BetaRand::BetaRand(double shape1, double shape2)
{
    setParameters(shape1, shape2);
}

std::string BetaRand::name()
{
    return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}

void BetaRand::setParameters(double shape1, double shape2)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);

    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);

    pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

void BetaRand::setAlpha(double shape1)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);
    pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

void BetaRand::setBeta(double shape2)
{
    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);
    pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

double BetaRand::f(double x) const
{
    if (x < 0 || x > 1)
        return 0;
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) < MIN_POSITIVE)
        return pdfCoef * std::pow(x - x * x, alpha - 1);
    double rv = std::pow(x, alpha - 1);
    rv *= std::pow(1 - x, beta - 1);
    return pdfCoef * rv;
}

double BetaRand::F(double x) const
{
    if (x <= 0)
        return 0;
    if (x >= 1)
        return 1;
    return x;
}

double BetaRand::variate() const
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) > MIN_POSITIVE || alpha < 1)
        return variateForDifferentParameters();
    if (alpha == 1)
        return UniformRand::standardVariate();
    if (alpha <= edgeForGenerators)
        return variateForSmallEqualParameters();
    return variateForLargeEqualParameters();
}

void BetaRand::sample(QVector<double> &outputData)
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) > MIN_POSITIVE || alpha < 1) {
        for (double &var : outputData)
            var = variateForDifferentParameters();
    }
    else if (alpha == 1) {
        for (double &var : outputData)
            var = UniformRand::standardVariate();
    }
    else if (alpha <= edgeForGenerators) {
        for (double &var : outputData)
            var = variateForSmallEqualParameters();
    }
    else {
        for (double &var : outputData)
            var = variateForLargeEqualParameters();
    }
}

double BetaRand::variateForSmallEqualParameters() const
{
    double alpha = X.getShape();
    int iter = 0;
    do {
        double u1 = UniformRand::standardVariate();
        double u2 = UniformRand::standardVariate();
        if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1))
            return u1;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForLargeEqualParameters() const
{
    int iter = 0;
    do {
        double n = N.variate();
        if (n < 0 || n > 1)
            continue;
        double u = UniformRand::standardVariate();
        if (u < N.f(n) / (variateCoef * f(n)))
            return n;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForDifferentParameters() const
{
    double x = X.variate();
    return x / (x + Y.variate());
}

void BetaRand::setVariateConstants()
{
    double alpha = X.getShape();
    /// We need to storage variate coefficient only if alpha = beta and large enough
    if (alpha > edgeForGenerators && std::fabs(alpha - Y.getShape()) < MIN_POSITIVE)
    {
        double t = 1.0 / (alpha + alpha + 1);
        variateCoef = std::sqrt(0.5 * M_PI * M_E * M_E * M_E * t);
        variateCoef *= std::pow(0.25 * (1 - 3 * t), alpha - 1);
        variateCoef *= pdfCoef; /// /= Beta(alpha, alpha)

        N.setMean(0.5);
        N.setVar(0.25 * t);
    }
}
<commit_msg>Added cdf to beta rand<commit_after>#include "BetaRand.h"

BetaRand::BetaRand(double shape1, double shape2)
{
    setParameters(shape1, shape2);
}

std::string BetaRand::name()
{
    return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}

void BetaRand::setParameters(double shape1, double shape2)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);

    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);

    pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

void BetaRand::setAlpha(double shape1)
{
    double alpha = std::max(shape1, MIN_POSITIVE);
    X.setParameters(alpha, 1);
    pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

void BetaRand::setBeta(double shape2)
{
    double beta = std::max(shape2, MIN_POSITIVE);
    Y.setParameters(beta, 1);
    pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
    setVariateConstants();
}

double BetaRand::f(double x) const
{
    if (x < 0 || x > 1)
        return 0;
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) < MIN_POSITIVE)
        return pdfCoef * std::pow(x - x * x, alpha - 1);
    double rv = std::pow(x, alpha - 1);
    rv *= std::pow(1 - x, beta - 1);
    return pdfCoef * rv;
}

double BetaRand::F(double x) const
{
    if (x <= 0)
        return 0;
    if (x >= 1)
        return 1;
    return RandMath::incompleteBetaFun(x, X.getShape(), Y.getShape());
}

double BetaRand::variate() const
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) > MIN_POSITIVE || alpha < 1)
        return variateForDifferentParameters();
    if (alpha == 1)
        return UniformRand::standardVariate();
    if (alpha <= edgeForGenerators)
        return variateForSmallEqualParameters();
    return variateForLargeEqualParameters();
}

void BetaRand::sample(QVector<double> &outputData)
{
    double alpha = X.getShape(), beta = Y.getShape();
    if (std::fabs(alpha - beta) > MIN_POSITIVE || alpha < 1) {
        for (double &var : outputData)
            var = variateForDifferentParameters();
    }
    else if (alpha == 1) {
        for (double &var : outputData)
            var = UniformRand::standardVariate();
    }
    else if (alpha <= edgeForGenerators) {
        for (double &var : outputData)
            var = variateForSmallEqualParameters();
    }
    else {
        for (double &var : outputData)
            var = variateForLargeEqualParameters();
    }
}

double BetaRand::variateForSmallEqualParameters() const
{
    double alpha = X.getShape();
    int iter = 0;
    do {
        double u1 = UniformRand::standardVariate();
        double u2 = UniformRand::standardVariate();
        if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1))
            return u1;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForLargeEqualParameters() const
{
    int iter = 0;
    do {
        double n = N.variate();
        if (n < 0 || n > 1)
            continue;
        double u = UniformRand::standardVariate();
        if (u < N.f(n) / (variateCoef * f(n)))
            return n;
    } while (++iter <= 1e9); /// one billion should be enough
    return 0; /// fail
}

double BetaRand::variateForDifferentParameters() const
{
    double x = X.variate();
    return x / (x + Y.variate());
}

void BetaRand::setVariateConstants()
{
    double alpha = X.getShape();
    /// We need to storage variate coefficient only if alpha = beta and large enough
    if (alpha > edgeForGenerators && std::fabs(alpha - Y.getShape()) < MIN_POSITIVE)
    {
        double t = 1.0 / (alpha + alpha + 1);
        variateCoef = std::sqrt(0.5 * M_PI * M_E * M_E * M_E * t);
        variateCoef *= std::pow(0.25 * (1 - 3 * t), alpha - 1);
        variateCoef *= pdfCoef; /// /= Beta(alpha, alpha)

        N.setMean(0.5);
        N.setVar(0.25 * t);
    }
}
<|endoftext|>


<commit_before>#include <cmath>

#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/Bool.h"
#include "vetexcanopen.h"

static const double SCALE_MAX_X = 100.0f;
static const double SCALE_MIN_X = 20.0f;
static const double SCALE_MAX_Y = 100.0f;
static const double SCALE_MIN_Y = 20.0f;
static const double SCALE_MAX_R = 100.0f;
static const double SCALE_MIN_R = 20.0f;
static const double THROTLE_SCALE_FACTOR = 40.0f;

class VetexDriver
{
public:
  VetexDriver():
    enabled_(false),
    throtle_scale_factor_(THROTLE_SCALE_FACTOR)
  {

  }

  ~VetexDriver()
  {

  }

  bool run()
  {
    ros::NodeHandle ph("~");
    ros::NodeHandle nh;

	  twist_sub_ = nh.subscribe("vetexvels", 1000, &VetexDriver::twistCallback,this);
	  enable_sub_ = nh.subscribe("vetexenable", 1000, &VetexDriver::enableCallback,this);

    if(init())
    {
      ROS_INFO_STREAM("Vetex driver initialized");
    }
    else
    {
      ROS_ERROR_STREAM("Vetex driver failed to initialize, aborting");
      vetex_terminate();
      return false;
    }

    ros::Duration loop_duration(0.1f);
    setEnable(true);
	  while (ros::ok())
    {
		  ros::spinOnce();
      loop_duration.sleep();
	  }

    setEnable(false);
    ros::Duration(1.0f).sleep();
	  vetex_terminate();

    return true;
  }

protected:

  bool init()
  {
	  // Initialize the vetex can stuff.
    ros::NodeHandle n("~");

	  n.param("max_speed_x", max_speed_x_, 0.1); // m/sec
	  n.param("min_speed_x", min_speed_x_, 0.01);// m/sec
	  n.param("max_speed_y", max_speed_y_, 0.1); // m/sec
	  n.param("min_speed_y", min_speed_y_, 0.01);// m/sec
	  n.param("max_speed_r", max_speed_r_, 0.5); // m/sec
	  n.param("min_speed_r", min_speed_r_, 0.05);// m/sec
    n.param("throtle_scale_factor", throtle_scale_factor_, THROTLE_SCALE_FACTOR);// m/sec

    ROS_INFO_STREAM("Driver Parameters :\n"<<
      "\n\tmax_speed_x: "<<max_speed_x_<<
      "\n\tmax_speed_y: "<<max_speed_y_<<
      "\n\tmax_speed_r: "<<max_speed_r_<<
      "\n\tmin_speed_x: "<<min_speed_x_<<
      "\n\tmin_speed_y: "<<min_speed_y_<<
      "\n\tmin_speed_r: "<<min_speed_r_<<
      "\n\tthrotle_scale: "<<throtle_scale_factor_<<"\n");

    vetex_initialize();

    return true;
  }

  void setEnable(bool enable)
  {
    if(enable)
    {
      vetex_enable_movement();
      ros::Duration(0.5f).sleep();
      vetex_set_all_percentages(0, 0, 0);
      ROS_INFO_STREAM("Movement enabled");
      enabled_ = true;
    }
    else
    {
      vetex_set_all_percentages(0, 0, 0);
      vetex_disable_movement();
      ROS_INFO_STREAM("Movement disabled");
      enabled_ = false;
    }

  }

  void twistCallback(const geometry_msgs::Twist::ConstPtr& msg)
  {
	  ROS_INFO("Received %f, %f, %f",msg->linear.x, msg->linear.y,msg->angular.z);

	  if ( ! enabled_)
    {
      ROS_WARN_STREAM("Movement is currently disabled");
	  }

	  // Scale parameters are stored in the ros parameter server.
	  // The scaling factor will be a multiplication that changes
	  // velocity into a percentage from -100 to 100.
	  // They are retrieved just before the spinonce in the main function.

    double xf = computeScaleFactor(SCALE_MAX_X,SCALE_MIN_X, max_speed_x_,min_speed_x_,msg->linear.x);
    double yf = computeScaleFactor(SCALE_MAX_Y,SCALE_MIN_Y, max_speed_y_,min_speed_y_,msg->linear.y);
    double rf = -computeScaleFactor(SCALE_MAX_R,SCALE_MIN_R, max_speed_r_,min_speed_r_, msg->angular.z); // rotation is flipped

    ROS_INFO_STREAM("Scale factors x: "<<xf<<" y: "<<yf<<" r: "<<rf);
	  vetex_set_all_percentages(xf, yf, rf);
  }

  void enableCallback(const std_msgs::Bool::ConstPtr& msg)
  {
	  ROS_INFO("Received %d", msg->data);
    setEnable(msg->data);
  }

  double computeScaleFactor(const double &max_factor,const double &min_factor,
    const double &max_speed,const double &min_speed,
    const double &command_speed)
  {
    double af = std::abs(command_speed);
    int sign = command_speed < 0 ? -1 : 1;
    if(af < min_speed)
    {
      af = 0;
    }
    else if(af > max_speed)
    {
      af = throtle_scale_factor_;
    }
    else
    {
      af = max_factor - ((max_factor - min_factor)*(max_speed - af))/(max_speed - min_speed);
      af = (af > throtle_scale_factor_) ? throtle_scale_factor_ : af;
    }

    return af*sign;
  }

protected:

  ros::Subscriber twist_sub_;
  ros::Subscriber enable_sub_;

  bool enabled_;
  double max_speed_x_;
  double min_speed_x_;
  double max_speed_y_;
  double min_speed_y_;
  double max_speed_r_;
  double min_speed_r_;
  double throtle_scale_factor_;

};

int main (int argc, char **argv)
{
  ros::init(argc, argv, "vetex_driver");
  ros::NodeHandle nh;
  VetexDriver vd;
  if(vd.run())
  {
    return 0;
  }
  else
  {
    return -1;
  }

}
<commit_msg>Cleaned up vetex logging and added frame reorientation to match URDF<commit_after>#include <cmath>

#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "std_msgs/Bool.h"
#include "vetexcanopen.h"

static const double SCALE_MAX_X = 100.0f;
static const double SCALE_MIN_X = 20.0f;
static const double SCALE_MAX_Y = 100.0f;
static const double SCALE_MIN_Y = 20.0f;
static const double SCALE_MAX_R = 100.0f;
static const double SCALE_MIN_R = 20.0f;
static const double THROTLE_SCALE_FACTOR = 40.0f;

class VetexDriver
{
public:
  VetexDriver():
    enabled_(false),
    throtle_scale_factor_(THROTLE_SCALE_FACTOR)
  {

  }

  ~VetexDriver()
  {

  }

  bool run()
  {
    ros::NodeHandle ph("~");
    ros::NodeHandle nh;

	  twist_sub_ = nh.subscribe("vetexvels", 1000, &VetexDriver::twistCallback,this);
	  enable_sub_ = nh.subscribe("vetexenable", 1000, &VetexDriver::enableCallback,this);

    if(init())
    {
      ROS_INFO_STREAM("Vetex driver initialized");
    }
    else
    {
      ROS_ERROR_STREAM("Vetex driver failed to initialize, aborting");
      vetex_terminate();
      return false;
    }

    ros::Duration loop_duration(0.1f);
    setEnable(true);
	  while (ros::ok())
    {
		  ros::spinOnce();
      loop_duration.sleep();
	  }

    setEnable(false);
    ros::Duration(1.0f).sleep();
	  vetex_terminate();

    return true;
  }

protected:

  bool init()
  {
	  // Initialize the vetex can stuff.
    ros::NodeHandle n("~");

	  n.param("max_speed_x", max_speed_x_, 0.1); // m/sec
	  n.param("min_speed_x", min_speed_x_, 0.01);// m/sec
	  n.param("max_speed_y", max_speed_y_, 0.1); // m/sec
	  n.param("min_speed_y", min_speed_y_, 0.01);// m/sec
	  n.param("max_speed_r", max_speed_r_, 0.5); // m/sec
	  n.param("min_speed_r", min_speed_r_, 0.05);// m/sec
    n.param("throtle_scale_factor", throtle_scale_factor_, THROTLE_SCALE_FACTOR);// m/sec

    ROS_INFO_STREAM("Driver Parameters :\n"<<
      "\n\tmax_speed_x: "<<max_speed_x_<<
      "\n\tmax_speed_y: "<<max_speed_y_<<
      "\n\tmax_speed_r: "<<max_speed_r_<<
      "\n\tmin_speed_x: "<<min_speed_x_<<
      "\n\tmin_speed_y: "<<min_speed_y_<<
      "\n\tmin_speed_r: "<<min_speed_r_<<
      "\n\tthrotle_scale: "<<throtle_scale_factor_<<"\n");

    vetex_initialize();

    return true;
  }

  void setEnable(bool enable)
  {
    if(enable)
    {
      vetex_enable_movement();
      ros::Duration(0.5f).sleep();
      vetex_set_all_percentages(0, 0, 0);
      ROS_INFO_STREAM("Movement enabled");
      enabled_ = true;
    }
    else
    {
      vetex_set_all_percentages(0, 0, 0);
      vetex_disable_movement();
      ROS_INFO_STREAM("Movement disabled");
      enabled_ = false;
    }

  }

  void twistCallback(const geometry_msgs::Twist::ConstPtr& msg)
  {
	  ROS_DEBUG("Received %f, %f, %f",msg->linear.x, msg->linear.y,msg->angular.z);

	  if ( ! enabled_)
    {
      ROS_WARN_STREAM("Movement is currently disabled");
	  }

	  // Scale parameters are stored in the ros parameter server.
	  // The scaling factor will be a multiplication that changes
	  // velocity into a percentage from -100 to 100.
	  // They are retrieved just before the spinonce in the main function.

    //xf,yf, rf - are base velocities in the base coordiate system (as specified in the URDF)
    double xf = computeScaleFactor(SCALE_MAX_X,SCALE_MIN_X, max_speed_x_,min_speed_x_,msg->linear.x);
    double yf = computeScaleFactor(SCALE_MAX_Y,SCALE_MIN_Y, max_speed_y_,min_speed_y_,msg->linear.y);
    double rf = computeScaleFactor(SCALE_MAX_R,SCALE_MIN_R, max_speed_r_,min_speed_r_, msg->angular.z); // rotation is flipped
    ROS_DEBUG_STREAM("Scale factors(in URDF frame) x: "<<xf<<" y: "<<yf<<" r: "<<rf);

    // rxf, ryf, rrf - are reoriented base velocites as assumed by the controller(note,
    // the rotation orientation is flipped because the controller is not a
    // right-handed frame - this is probably due to mimicing the hand control outputs which
    // aren't really a coordinate frame)
    double rxf = yf;
    double ryf = -xf;
    double rrf = -rf;
    ROS_DEBUG_STREAM("Reoriented factors(in base controller 'frame') x: "<<rxf<<" y: "<<ryf<<" r: "<<rrf);

	  vetex_set_all_percentages(rxf, ryf, rrf);
  }

  void enableCallback(const std_msgs::Bool::ConstPtr& msg)
  {
	  ROS_INFO("Received %d", msg->data);
    setEnable(msg->data);
  }

  double computeScaleFactor(const double &max_factor,const double &min_factor,
    const double &max_speed,const double &min_speed,
    const double &command_speed)
  {
    double af = std::abs(command_speed);
    int sign = command_speed < 0 ? -1 : 1;
    if(af < min_speed)
    {
      af = 0;
    }
    else if(af > max_speed)
    {
      af = throtle_scale_factor_;
    }
    else
    {
      af = max_factor - ((max_factor - min_factor)*(max_speed - af))/(max_speed - min_speed);
      af = (af > throtle_scale_factor_) ? throtle_scale_factor_ : af;
    }

    return af*sign;
  }

protected:

  ros::Subscriber twist_sub_;
  ros::Subscriber enable_sub_;

  bool enabled_;
  double max_speed_x_;
  double min_speed_x_;
  double max_speed_y_;
  double min_speed_y_;
  double max_speed_r_;
  double min_speed_r_;
  double throtle_scale_factor_;

};

int main (int argc, char **argv)
{
  ros::init(argc, argv, "vetex_driver");
  ros::NodeHandle nh;
  VetexDriver vd;
  if(vd.run())
  {
    return 0;
  }
  else
  {
    return -1;
  }

}
<|endoftext|>


<commit_before>#include <SDL2/SDL.h>
#include <iostream>

#include "spacetyper/gl.h"
#include "spacetyper/shader.h"
#include "spacetyper/spriterender.h"
#include "spacetyper/spritefader.h"

#include "spacetyper/background.h"
#include "spacetyper/debuggl.h"
#include "spacetyper/scalablesprite.h"
#include "spacetyper/fonts.h"
#include "spacetyper/texturecache.h"
#include "spacetyper/dictionary.h"
#include "spacetyper/enemies.h"
#include "spacetyper/enemyword.h"
#include "spacetyper/bulletlist.h"
#include "spacetyper/interpolate.h"

int main(int argc, char** argv) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0) {
    std::cerr << "Failed to init SDL: " << SDL_GetError() << "\n";
    return -1;
  }

  SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);

  int width = 800;
  int height = 600;

  SDL_Window* window = SDL_CreateWindow("Space Typer", SDL_WINDOWPOS_UNDEFINED,
                                        SDL_WINDOWPOS_UNDEFINED, width, height,
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

  if (window == NULL) {
    std::cerr << "Failed to create window " << SDL_GetError() << "\n";
    return -1;
  }

  SDL_GL_CreateContext(window);
  std::cout << "Created OpenGL " << glGetString(GL_VERSION) << " context"
            << "\n";

  const GLenum err = glewInit();
  if (GLEW_OK != err) {
    std::cerr << "Failed to init glew, error: " << glewGetErrorString(err)
              << "\n";
    return -4;
  }

  SetupOpenglDebug();

  TextureCache cache;
  Shader shader("shaders/sprite");
  Shader font_shader("shaders/font");
  Shader back_shader("shaders/back");
  Font font(&font_shader, "SourceCodePro-Regular.ttf", 30, " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;:,.-_<>|1234567890!\"#¤%&/()'=?@£$€¥{[]}\\'*");
  // (cache.GetTexture("metalPanel_blueCorner.png"), 62, 14, 33, 14, vec2f(240, 240));
  std::shared_ptr<ScalableSprite> target { new ScalableSprite("crossair_white.png", vec2f(100, 100), &cache) };
  SpriteRenderer renderer(&shader);

  Dictionary dictionary;

  Layer background(&renderer);
  Layer objects(&renderer);
  Layer foreground(&renderer);
  Background smallStars(25, width, height, cache.GetTexture("starSmall.png"), 20, &background);
  Background bigStars(15, width, height, cache.GetTexture("starBig.png"), 50, &background);

  SpriteFader fader(&foreground);

  // smoke effects
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_008.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_009.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_010.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_011.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_012.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_013.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_014.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_015.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_016.png"));

  // "laser"/explosion effects
  fader.RegisterTexture(cache.GetTexture("explosion/laserBlue08.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserBlue10.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserGreen14.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserGreen16.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserRed08.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserRed10.png"));

  Sprite player(cache.GetTexture("player.png"));
  objects.Add(&player);

  vec2f shipPos(width / 2, height - player.GetHeight() / 2 - 10);
  player.SetPosition(shipPos);

  mat4f projection =
      mat4f::Ortho(0.0f, static_cast<GLfloat>(width),
                 static_cast<GLfloat>(height), 0.0f, -1.0f, 1.0f);
  Use(&shader);
  shader.SetInteger("image", 0);
  shader.SetMatrix4("projection", projection);

  Use(&font_shader);
  font_shader.SetInteger("image", 0);
  font_shader.SetMatrix4("projection", projection);

  Use(&back_shader);
  back_shader.SetMatrix4("projection", projection);

  glViewport(0, 0, width, height);
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  TextBackgroundRenderer text_back(&back_shader);

  Uint64 NOW = SDL_GetPerformanceCounter();
  Uint64 LAST = 0;

  SDL_StartTextInput();

  BulletList bullets(&objects);
  Enemies enemies(&fader, &cache, &font, &text_back, &objects, &dictionary, width, &bullets);
  EnemyWord* current_word = nullptr;

  enemies.SpawnEnemies(5);

  FloatInterpolate player_rotation(0.0f);
  const float ROTATION_TIME = 0.5f;
  const float SCALE_TIME = 0.6f;

  FloatInterpolate target_scale(1.0f);

  bool running = true;
  while (running) {
    LAST = NOW;
    NOW = SDL_GetPerformanceCounter();
    const float dt = (NOW - LAST) * 1.0f / SDL_GetPerformanceFrequency();
    SDL_Event e;

    while (SDL_PollEvent(&e) != 0) {
      if (e.type == SDL_QUIT) {
        running = false;
      }
      else if( e.type == SDL_TEXTINPUT ) {
        const std::string& input = e.text.text;
        if( current_word == nullptr ) {
          current_word = enemies.DetectWord(input);
          if( current_word != nullptr ) {
            const float target_rotation = enemies.FireAt(shipPos, current_word);
            player_rotation.Clear().BackOut(target_rotation, ROTATION_TIME);
            target_scale.SetValue(19.0f).Clear().CircOut(1.0f, SCALE_TIME);
          }
        }
        else {
          const bool hit = current_word->Type(input);
          if( hit ) {
            const float target_rotation = enemies.FireAt(shipPos, current_word);
            player_rotation.Clear().BackOut(target_rotation, ROTATION_TIME);
          }
          if( current_word->IsAlive() == false ) {
            enemies.Remove(current_word);
            current_word = nullptr;
            const float target_rotation = 0.0f;
            player_rotation.Clear().BackOut(target_rotation, ROTATION_TIME);
          }
        }
      }
    }

    smallStars.Update(dt);
    bigStars.Update(dt);
    enemies.Update(dt);
    bullets.Update(dt);
    fader.Update(dt);
    player_rotation.Update(dt);
    target_scale.Update(dt);
    player.SetRotation(player_rotation);

    glClearColor(42.0f / 255, 45.0f / 255, 51.0f / 255, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    background.Render();
    objects.Render();
    enemies.Render();
    foreground.Render();
    // dont render ninepatch unless we are in a meny = not yet implemented :)
    if( current_word != nullptr ) {
      target->SetSize(current_word->GetSize() * target_scale.GetValue());
      renderer.DrawNinepatch(*target.get(), current_word->GetPosition() - target->GetSize()/2.0f);
    }
    SDL_GL_SwapWindow(window);
  }

  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}
<commit_msg>fixed scaling<commit_after>#include <SDL2/SDL.h>
#include <iostream>

#include "spacetyper/gl.h"
#include "spacetyper/shader.h"
#include "spacetyper/spriterender.h"
#include "spacetyper/spritefader.h"

#include "spacetyper/background.h"
#include "spacetyper/debuggl.h"
#include "spacetyper/scalablesprite.h"
#include "spacetyper/fonts.h"
#include "spacetyper/texturecache.h"
#include "spacetyper/dictionary.h"
#include "spacetyper/enemies.h"
#include "spacetyper/enemyword.h"
#include "spacetyper/bulletlist.h"
#include "spacetyper/interpolate.h"

int main(int argc, char** argv) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0) {
    std::cerr << "Failed to init SDL: " << SDL_GetError() << "\n";
    return -1;
  }

  SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);

  int width = 800;
  int height = 600;

  SDL_Window* window = SDL_CreateWindow("Space Typer", SDL_WINDOWPOS_UNDEFINED,
                                        SDL_WINDOWPOS_UNDEFINED, width, height,
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

  if (window == NULL) {
    std::cerr << "Failed to create window " << SDL_GetError() << "\n";
    return -1;
  }

  SDL_GL_CreateContext(window);
  std::cout << "Created OpenGL " << glGetString(GL_VERSION) << " context"
            << "\n";

  const GLenum err = glewInit();
  if (GLEW_OK != err) {
    std::cerr << "Failed to init glew, error: " << glewGetErrorString(err)
              << "\n";
    return -4;
  }

  SetupOpenglDebug();

  TextureCache cache;
  Shader shader("shaders/sprite");
  Shader font_shader("shaders/font");
  Shader back_shader("shaders/back");
  Font font(&font_shader, "SourceCodePro-Regular.ttf", 30, " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;:,.-_<>|1234567890!\"#¤%&/()'=?@£$€¥{[]}\\'*");
  // (cache.GetTexture("metalPanel_blueCorner.png"), 62, 14, 33, 14, vec2f(240, 240));
  ScalableSprite target("crossair_white.png", vec2f(100, 100), &cache);
  SpriteRenderer renderer(&shader);

  Dictionary dictionary;

  Layer background(&renderer);
  Layer objects(&renderer);
  Layer foreground(&renderer);
  Background smallStars(25, width, height, cache.GetTexture("starSmall.png"), 20, &background);
  Background bigStars(15, width, height, cache.GetTexture("starBig.png"), 50, &background);

  SpriteFader fader(&foreground);

  // smoke effects
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_008.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_009.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_010.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_011.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_012.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_013.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_014.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_015.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/spaceEffects_016.png"));

  // "laser"/explosion effects
  fader.RegisterTexture(cache.GetTexture("explosion/laserBlue08.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserBlue10.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserGreen14.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserGreen16.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserRed08.png"));
  fader.RegisterTexture(cache.GetTexture("explosion/laserRed10.png"));

  Sprite player(cache.GetTexture("player.png"));
  objects.Add(&player);

  vec2f shipPos(width / 2, height - player.GetHeight() / 2 - 10);
  player.SetPosition(shipPos);

  mat4f projection =
      mat4f::Ortho(0.0f, static_cast<GLfloat>(width),
                 static_cast<GLfloat>(height), 0.0f, -1.0f, 1.0f);
  Use(&shader);
  shader.SetInteger("image", 0);
  shader.SetMatrix4("projection", projection);

  Use(&font_shader);
  font_shader.SetInteger("image", 0);
  font_shader.SetMatrix4("projection", projection);

  Use(&back_shader);
  back_shader.SetMatrix4("projection", projection);

  glViewport(0, 0, width, height);
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  TextBackgroundRenderer text_back(&back_shader);

  Uint64 NOW = SDL_GetPerformanceCounter();
  Uint64 LAST = 0;

  SDL_StartTextInput();

  BulletList bullets(&objects);
  Enemies enemies(&fader, &cache, &font, &text_back, &objects, &dictionary, width, &bullets);
  EnemyWord* current_word = nullptr;

  enemies.SpawnEnemies(5);

  FloatInterpolate player_rotation(0.0f);
  const float ROTATION_TIME = 0.5f;
  const float SCALE_TIME = 0.6f;

  FloatInterpolate target_scale(1.0f);

  bool running = true;
  while (running) {
    LAST = NOW;
    NOW = SDL_GetPerformanceCounter();
    const float dt = (NOW - LAST) * 1.0f / SDL_GetPerformanceFrequency();
    SDL_Event e;

    while (SDL_PollEvent(&e) != 0) {
      if (e.type == SDL_QUIT) {
        running = false;
      }
      else if( e.type == SDL_TEXTINPUT ) {
        const std::string& input = e.text.text;
        if( current_word == nullptr ) {
          current_word = enemies.DetectWord(input);
          if( current_word != nullptr ) {
            const float target_rotation = enemies.FireAt(shipPos, current_word);
            player_rotation.Clear().BackOut(target_rotation, ROTATION_TIME);
            target_scale.SetValue(19.0f).Clear().CircOut(1.0f, SCALE_TIME);
          }
        }
        else {
          const bool hit = current_word->Type(input);
          if( hit ) {
            const float target_rotation = enemies.FireAt(shipPos, current_word);
            player_rotation.Clear().BackOut(target_rotation, ROTATION_TIME);
          }
          if( current_word->IsAlive() == false ) {
            enemies.Remove(current_word);
            current_word = nullptr;
            const float target_rotation = 0.0f;
            player_rotation.Clear().BackOut(target_rotation, ROTATION_TIME);
          }
        }
      }
    }

    smallStars.Update(dt);
    bigStars.Update(dt);
    enemies.Update(dt);
    bullets.Update(dt);
    fader.Update(dt);
    player_rotation.Update(dt);
    target_scale.Update(dt);
    player.SetRotation(player_rotation);

    glClearColor(42.0f / 255, 45.0f / 255, 51.0f / 255, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    background.Render();
    objects.Render();
    enemies.Render();
    foreground.Render();
    // dont render ninepatch unless we are in a meny = not yet implemented :)
    if( current_word != nullptr ) {
      const vec2f extra_size(40, 40);
      const vec2f size = current_word->GetSize();
      const vec2f size_and_extra = size + extra_size;
      const vec2f scaled_size = size_and_extra * target_scale.GetValue();
      target.SetSize(scaled_size);
      renderer.DrawNinepatch(target, current_word->GetPosition() - scaled_size/2.0f);
    }
    SDL_GL_SwapWindow(window);
  }

  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************\
**
**  tInputFile.cpp: Member functions for class tInputFile.
**
**  (see tInputFile.h for a description of this class)
**
**  Greg Tucker, November 1997
**
**  $Id: tInputFile.cpp,v 1.15 2002-09-26 17:33:43 arnaud Exp $
\****************************************************************************/

#if !defined(HAVE_NO_NAMESPACE)
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
#include "../tAssert.h"
#include <string.h>
#include <stdlib.h>
//#include "../Definitions.h"
//#include "../Classes.h"
#include "tInputFile.h"
#include "../errors/errors.h"

/****************************************************************************\
**
**  tInputFile Constructor
**
**  Looks for a file called filename, opens it if found or generates an
**  error if not. Then reads the base name for output files and creates
**  a file called <filename>.inputs which will act as a log file for
**  parameters read. (This is often useful when the original input file
**  gets lost or modified).
**
**  Modifications:
**    - 2/02: error check for inoutfile added (GT)
**
\****************************************************************************/
tInputFile::tInputFile( const char *filename )
  :
  infile(), inoutfile()
{
   char inoutname[kMaxNameLength];

   // Open file
   infile.open( filename );
   if( !infile.good() )
   {
      cerr << "tInputFile::tInputFile: Unable to open '" << filename << "'." << endl;
      ReportFatalError( "The file may not exist or may be mis-named." );
   }

   // Create log file for inputs
   ReadItem( inoutname, "OUTFILENAME" );
   strcat( inoutname, ".inputs" );
   inoutfile.open( inoutname );
   if( !inoutfile.good() )
     {
       cerr << "Unable to open '" << inoutname << "'.\n";
       cerr << "(Error generated in module tInputFile, function tInputFile::tInputFile( const char * ) )\n";
       ReportFatalError( "The specified path name may not exist.\n" );
     }

}

/****************************************************************************\
**
**  tInputFile::ReadItem
**
**  Reads one parameter from the file. The format is assumed to be a line
**  of text that begins with the code "itemCode", followed by a line containing
**  the parameter to be read. The function is overloaded according to the
**  type of data desired (datType simply governs which overloaded function
**  will be called; it is not used by the routines).
**
**  Inputs:  datType -- dummy variable indicating the data type to be read
**                      (in the case of the string version, the string read
**                      is placed here)
**           itemCode -- string that describes the parameter to be read
**  Returns:  the item read (except in the case of the string version)
**  Modifications:
**    - revised to allow arbitrary ordering of items in infile and/or
**      ReadItem calls in code; routine searches through
**      list until it either finds the right itemCode or reaches EOF.
**      12/23/97 SL
**
\****************************************************************************/
// read a line in headerLine and discards the any remaining characters
static
void readLine(char *headerLine, ifstream& infile){
  infile.getline( headerLine, kMaxNameLength );
  // still some characters left on the current line ?
  if ( !infile.eof() && infile.rdstate() & ios::failbit){
    // clear failbit
    infile.clear(infile.rdstate() & ~ios::failbit);
    // discard characters.
    char c;
    while( infile.get(c) && c != '\n');
  }
}

static
void readUntilKeyword(char *headerLine, ifstream& infile,
		      const char *itemCode){
  do {
    readLine(headerLine, infile);
  } while( !( infile.eof() ) &&
	   ( headerLine[0]==kCommentMark ||
	     strncmp( itemCode, headerLine, strlen( itemCode ) )!=0 ) );
}

static
void skipCommentsAndReadValue(char *headerLine, ifstream& infile){
  do {
    readLine(headerLine, infile);
  } while( !( infile.eof() ) &&
	   ( headerLine[0]==kCommentMark ) );
}

int tInputFile::ReadItem( const int & /*datType*/, const char *itemCode )
{
   //cout << "ReadItem( int )...";
   int item;
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // NB: Should check for eof on reading each line

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() )
     goto fail;

   // skip any comment and read value
   skipCommentsAndReadValue(headerLine, infile);
   if( headerLine[0]!=kCommentMark )
     {
       item = atoi(headerLine);
       inoutfile << itemCode << endl << item << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return item;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}

long tInputFile::ReadItem( const long & /*datType*/, const char *itemCode )
{
   //cout << "ReadItem( long )...";
   long item;
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // NB: Should check for eof on reading each line

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() )
     goto fail;

   // skip any comment and read value
   skipCommentsAndReadValue(headerLine, infile);
   if( headerLine[0]!=kCommentMark )
     {
       item = atol(headerLine);
       inoutfile << itemCode << endl << item << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return item;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}

double tInputFile::ReadItem( const double & /*datType*/, const char *itemCode )
{
   //cout << "ReadItem( double )...";
   double item;
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // NB: Should check for eof on reading each line

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() )
     goto fail;

   // skip any comment and read value
   skipCommentsAndReadValue(headerLine, infile);
   if( headerLine[0]!=kCommentMark )
     {
       item = atof(headerLine);
       inoutfile << itemCode << endl << item << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return item;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}

void tInputFile::ReadItem(  char * theString, const char *itemCode )
{
   //cout << "ReadItem( char )...";
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() )
     goto fail;

   // skip any comment and read value
   do {
     readLine(headerLine, infile);
   } while( !( infile.eof() ) &&
	    ( headerLine[0]==kCommentMark ) );
   if( headerLine[0]!=kCommentMark )
     {
       strcpy(theString,headerLine);
       inoutfile << itemCode << endl << theString << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}
<commit_msg>paranoia !<commit_after>/****************************************************************************\
**
**  tInputFile.cpp: Member functions for class tInputFile.
**
**  (see tInputFile.h for a description of this class)
**
**  Greg Tucker, November 1997
**
**  $Id: tInputFile.cpp,v 1.16 2002-09-27 15:30:14 arnaud Exp $
\****************************************************************************/

#if !defined(HAVE_NO_NAMESPACE)
# include <iostream>
using namespace std;
#else
# include <iostream.h>
#endif
#include "../tAssert.h"
#include <string.h>
#include <stdlib.h>
//#include "../Definitions.h"
//#include "../Classes.h"
#include "tInputFile.h"
#include "../errors/errors.h"

/****************************************************************************\
**
**  tInputFile Constructor
**
**  Looks for a file called filename, opens it if found or generates an
**  error if not. Then reads the base name for output files and creates
**  a file called <filename>.inputs which will act as a log file for
**  parameters read. (This is often useful when the original input file
**  gets lost or modified).
**
**  Modifications:
**    - 2/02: error check for inoutfile added (GT)
**
\****************************************************************************/
tInputFile::tInputFile( const char *filename )
  :
  infile(), inoutfile()
{
   char inoutname[kMaxNameLength];

   // Open file
   infile.open( filename );
   if( !infile.good() )
   {
      cerr << "tInputFile::tInputFile: Unable to open '" << filename << "'." << endl;
      ReportFatalError( "The file may not exist or may be mis-named." );
   }

   // Create log file for inputs
   ReadItem( inoutname, "OUTFILENAME" );
   strcat( inoutname, ".inputs" );
   inoutfile.open( inoutname );
   if( !inoutfile.good() )
     {
       cerr << "Unable to open '" << inoutname << "'.\n";
       cerr << "(Error generated in module tInputFile, function tInputFile::tInputFile( const char * ) )\n";
       ReportFatalError( "The specified path name may not exist.\n" );
     }

}

/****************************************************************************\
**
**  tInputFile::ReadItem
**
**  Reads one parameter from the file. The format is assumed to be a line
**  of text that begins with the code "itemCode", followed by a line containing
**  the parameter to be read. The function is overloaded according to the
**  type of data desired (datType simply governs which overloaded function
**  will be called; it is not used by the routines).
**
**  Inputs:  datType -- dummy variable indicating the data type to be read
**                      (in the case of the string version, the string read
**                      is placed here)
**           itemCode -- string that describes the parameter to be read
**  Returns:  the item read (except in the case of the string version)
**  Modifications:
**    - revised to allow arbitrary ordering of items in infile and/or
**      ReadItem calls in code; routine searches through
**      list until it either finds the right itemCode or reaches EOF.
**      12/23/97 SL
**
\****************************************************************************/
// read a line in headerLine and discards the any remaining characters
static
void readLine(char *headerLine, ifstream& infile){
  infile.getline( headerLine, kMaxNameLength );
  // still some characters left on the current line ?
  if ( !infile.eof() && !infile.bad() && infile.rdstate() & ios::failbit){
    // clear failbit
    infile.clear(infile.rdstate() & ~ios::failbit);
    // discard characters.
    char c;
    while( infile.get(c) && c != '\n');
  }
}

static
void readUntilKeyword(char *headerLine, ifstream& infile,
		      const char *itemCode){
  do {
    readLine(headerLine, infile);
  } while( !infile.eof() && !infile.bad() &&
	   ( headerLine[0]==kCommentMark ||
	     strncmp( itemCode, headerLine, strlen( itemCode ) )!=0 ) );
}

static
void skipCommentsAndReadValue(char *headerLine, ifstream& infile){
  do {
    readLine(headerLine, infile);
  } while( !infile.eof() && !infile.bad() &&
	   ( headerLine[0]==kCommentMark ) );
}

int tInputFile::ReadItem( const int & /*datType*/, const char *itemCode )
{
   //cout << "ReadItem( int )...";
   int item;
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() || infile.bad() )
     goto fail;

   // skip any comment and read value
   skipCommentsAndReadValue(headerLine, infile);
   if( headerLine[0]!=kCommentMark )
     {
       item = atoi(headerLine);
       inoutfile << itemCode << endl << item << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return item;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}

long tInputFile::ReadItem( const long & /*datType*/, const char *itemCode )
{
   //cout << "ReadItem( long )...";
   long item;
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() || infile.bad() )
     goto fail;

   // skip any comment and read value
   skipCommentsAndReadValue(headerLine, infile);
   if( headerLine[0]!=kCommentMark )
     {
       item = atol(headerLine);
       inoutfile << itemCode << endl << item << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return item;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}

double tInputFile::ReadItem( const double & /*datType*/, const char *itemCode )
{
   //cout << "ReadItem( double )...";
   double item;
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() || infile.bad() )
     goto fail;

   // skip any comment and read value
   skipCommentsAndReadValue(headerLine, infile);
   if( headerLine[0]!=kCommentMark )
     {
       item = atof(headerLine);
       inoutfile << itemCode << endl << item << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return item;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}

void tInputFile::ReadItem(  char * theString, const char *itemCode )
{
   //cout << "ReadItem( char )...";
   char headerLine[kMaxNameLength];

   assert( infile.good() );

   // look for itemCode
   readUntilKeyword(headerLine, infile, itemCode);
   if ( infile.eof() || infile.bad() )
     goto fail;

   // skip any comment and read value
   do {
     readLine(headerLine, infile);
   } while( !infile.eof() && !infile.bad() &&
	    ( headerLine[0]==kCommentMark ) );
   if( headerLine[0]!=kCommentMark )
     {
       strcpy(theString,headerLine);
       inoutfile << itemCode << endl << theString << endl;
     }
   else
     {
       goto fail;
     }
   infile.seekg( 0, ios::beg );
   return;

 fail:
   cerr << "I expected to read the parameter '" << itemCode
	<< "', but reached EOF first" << endl;
   ReportFatalError( "Missing parameter in input file" );
}
<|endoftext|>


<commit_before>#include "vtrc-general-config.h"

#if VTRC_OPENSSL_ENABLED

#include <iostream>

#include "vtrc-common/vtrc-transport-ssl.h"
#include "vtrc-common/vtrc-protocol-accessor-iface.h"
#include "vtrc-common/vtrc-delayed-call.h"

#include "vtrc-listener-ssl.h"
#include "vtrc-listener-impl.h"
#include "vtrc-connection-impl.h"

#include "vtrc-memory.h"
#include "vtrc-ref.h"

//
//
//

namespace vtrc { namespace server { namespace listeners {

    namespace {

        namespace bssl  = boost::asio::ssl;
        namespace bip   = basio::ip;

        typedef bip::tcp::acceptor  acceptor_type;
        typedef bip::tcp::endpoint  endpoint_type;

        typedef common::transport_ssl                  connection_type;
        typedef connection_impl<connection_type>       connection_impl_type;
        typedef typename connection_type::socket_type  socket_type;

        typedef vtrc::function<
            void (const common::connection_iface *)
        > close_closure;

        struct commection_impl: public connection_impl_type {

            typedef commection_impl this_type;
            std::string             name_;
            common::delayed_call    keepalive_calls_;

            commection_impl( listener &listen,
                                  vtrc::shared_ptr<socket_type> sock,
                                  const close_closure &on_close_cb,
                                  const std::string &name )
                :connection_impl_type(listen, sock, on_close_cb)
                ,name_(name)
                ,keepalive_calls_(listen.get_application( ).get_io_service( ))
            { }

            void on_init_timeout( const bsys::error_code &error )
            {
                if( !error ) {
                    close( );
                }
            }

            std::string name(  ) const
            {
                return name_;
            }

            void set_name( const std::string &name )
            {
                name_ = name;
            }

            bool is_local( ) const
            {
                return false;
            }

            void start_read_clos( bsys::error_code const & /*err*/,
                                  common::connection_iface_wptr &inst )
            {
                common::connection_iface_sptr lck(inst.lock( ));
                if( lck ) {
                    start_reading( );
                }
            }

            void ssl_handshake_handler( bsys::error_code const & err,
                                        common::connection_iface_wptr &inst )
            {
                common::connection_iface_sptr lck(inst.lock( ));
                if( !lck ) {
                    return;
                }

                keepalive_calls_.cancel( );

                if( !err ) {
                    protocol_->init_success(
                                vtrc::bind( &this_type::start_read_clos, this,
                                            vtrc::placeholders::error,
                                            this->weak_from_this( )));
                } else {
                    close( );
                }
            }

            void init( )
            {
                namespace ph = vtrc::placeholders;

                keepalive_calls_.call_from_now(
                            vtrc::bind( &this_type::on_init_timeout, this,
                                        ph::error ),
                            boost::posix_time::seconds( 5 ));

                get_socket( ).async_handshake( bssl::stream_base::server,
                    vtrc::bind( &this_type::ssl_handshake_handler, this,
                                 ph::error,
                                 this->weak_from_this( ) ) );
            }

            static vtrc::shared_ptr<this_type> create( listener &listnr,
                                     vtrc::shared_ptr<socket_type> sock,
                                     const close_closure &on_close_cb )
            {
                vtrc::shared_ptr<this_type> new_inst
                        (vtrc::make_shared<this_type>(vtrc::ref(listnr),
                                            sock, vtrc::ref(on_close_cb),
                                            "" ) );

                rpc::session_options const &opts(listnr.get_options( ));

                new_inst->protocol_.reset(
                        new protocol_layer_s( new_inst->app_,
                                                new_inst.get( ), opts ) );

                return new_inst;
            }
        };

        endpoint_type make_endpoint( const std::string &address,
                                     unsigned short port )
        {
            return endpoint_type(bip::address::from_string(address), port);
        }

        struct listener_ssl: public listener {

            typedef listener_ssl this_type;

            basio::io_service              &ios_;
            endpoint_type                   endpoint_;
            vtrc::unique_ptr<acceptor_type> acceptor_;
            bool                            working_;
            bool                            no_delay_;
            basio::ssl::context             context_;
            ssl::setup_function_type        setup_cb_;

            listener_ssl( application &app,
                          const rpc::session_options &opts,
                          const std::string &address,
                          unsigned short port,
                          ssl::setup_function_type setup_cb,
                          bool no_delay )
                :listener(app, opts)
                ,ios_(app.get_io_service( ))
                ,endpoint_(make_endpoint(address, port))
                ,working_(false)
                ,no_delay_(no_delay)
                ,context_(bssl::context::sslv23)
                ,setup_cb_(setup_cb)
            { }

            void on_client_destroy( vtrc::weak_ptr<listener> inst,
                                    const common::connection_iface *conn )
            {
                vtrc::shared_ptr<listener> lock( inst.lock( ) );
                if( lock ) {
                    this->stop_connection( conn );
                }
            }

            close_closure get_on_close_cb( )
            {
                return vtrc::bind( &this_type::on_client_destroy, this,
                                   weak_from_this( ), vtrc::placeholders::_1 );
            }

            void start( )
            {
                setup_cb_( context_ );
//                context_.set_options(
//                      bssl::context::default_workarounds
//                    | bssl::context::no_sslv2
//                    | bssl::context::single_dh_use);
//                context_.set_password_callback(
//                            vtrc::bind( &server::get_password, this ) );
//                context_.use_certificate_chain_file("server.crt");
//                context_.use_private_key_file("server.key", bssl::context::pem);
//                context_.use_tmp_dh_file("dh1024.pem");

                working_ = true;
                acceptor_.reset(new acceptor_type(ios_, endpoint_));
                acceptor_->listen( 5 );
                start_accept( );
                call_on_start( );
            }

            void start_accept( )
            {
                vtrc::shared_ptr<socket_type> new_sock
                                            ( new socket_type(ios_, context_) );

//                    ( vtrc::make_shared<socket_type>( vtrc::ref(ios_),
//                                                      vtrc::ref(context_)));

                acceptor_->async_accept( new_sock->lowest_layer( ),
                    vtrc::bind( &this_type::on_accept, this,
                                 vtrc::placeholders::error, new_sock,
                                 weak_from_this( )));
            }

            void stop ( )
            {
                working_ = false;
                acceptor_->close( );
                //stop_impl( );
            }

            bool is_active( ) const
            {
                return working_;
            }

            bool is_local( ) const
            {
                return false;
            }

            void on_accept( const bsys::error_code &error,
                            vtrc::shared_ptr<socket_type> sock,
                            vtrc::weak_ptr<listener> &inst )
            {
                vtrc::shared_ptr<listener> locked( inst.lock( ));
                if( !locked ) {
                    return;
                }

                if( !error ) {
                    vtrc::shared_ptr<commection_impl> new_conn;
                    try {
                        new_conn = commection_impl::create( *this, sock,
                                                            get_on_close_cb( ));

                        connection_setup( new_conn );

                        namespace ph = vtrc::placeholders;

                        new_conn->get_protocol( )
                                 .set_precall( vtrc::bind(
                                                  &this_type::mk_precall, this,
                                                   ph::_1, ph::_2, ph::_3 ) );
                        new_conn->get_protocol( )
                                 .set_postcall( vtrc::bind(
                                                  &this_type::mk_postcall, this,
                                                   ph::_1, ph::_2 ) );

                        get_application( ).get_clients( )->store( new_conn );
                        new_connection( new_conn.get( ) );

                        new_conn->init( );

                    } catch( ... ) {
                        if( new_conn.get( ) )  {
                            get_application( ).get_clients( )
                                             ->drop( new_conn.get( ) );
                        }
                    }
                    start_accept( );
                } else {
                    if( working_ ) {
                        stop( );
                        call_on_accept_failed( error );
                    } else {
                        call_on_stop( );
                    }
                }
            }

            std::string name( ) const
            {
                std::ostringstream oss;

                oss << "ssl://" << endpoint_.address( ).to_string( )
                    << ":"
                    << endpoint_.port( );

                return oss.str( );
            }

            void connection_setup( vtrc::shared_ptr<commection_impl> &con )
            {
                con->set_no_delay( no_delay_ );
                std::ostringstream oss;
                oss << "ssl://" << con->get_socket( )
                                        .lowest_layer( ).remote_endpoint( );
                con->set_name( oss.str( ) );
            }

        };
    }

    namespace tcp_ssl {

        listener_sptr create(application &app,
                             const rpc::session_options &opts,
                             const std::string &address,
                             unsigned short service,
                             vtrc::server::ssl::setup_function_type setup,
                             bool tcp_nodelay)
        {

            vtrc::shared_ptr<listener_ssl>new_l
                    (vtrc::make_shared<listener_ssl>(
                             vtrc::ref(app), vtrc::ref(opts),
                             vtrc::ref(address), service,
                             setup, tcp_nodelay ));
            return new_l;
        }

        listener_sptr create( application &app,
                              const std::string &address,
                              unsigned short service,
                              vtrc::server::ssl::setup_function_type setup,
                              bool tcp_nodelay )
        {
            const rpc::session_options
                    def_opts( common::defaults::session_options( ) );

            return create( app, def_opts, address,
                           service, setup, tcp_nodelay );
        }

    }

}}}

#endif
<commit_msg>noexcept<commit_after>#include "vtrc-general-config.h"

#if VTRC_OPENSSL_ENABLED

#include <iostream>

#include "vtrc-common/vtrc-transport-ssl.h"
#include "vtrc-common/vtrc-protocol-accessor-iface.h"
#include "vtrc-common/vtrc-delayed-call.h"

#include "vtrc-listener-ssl.h"
#include "vtrc-listener-impl.h"
#include "vtrc-connection-impl.h"

#include "vtrc-memory.h"
#include "vtrc-ref.h"

//
//
//

namespace vtrc { namespace server { namespace listeners {

    namespace {

        namespace bssl  = boost::asio::ssl;
        namespace bip   = basio::ip;

        typedef bip::tcp::acceptor  acceptor_type;
        typedef bip::tcp::endpoint  endpoint_type;

        typedef common::transport_ssl                  connection_type;
        typedef connection_impl<connection_type>       connection_impl_type;
        typedef connection_type::socket_type  socket_type;

        typedef vtrc::function<
            void (const common::connection_iface *)
        > close_closure;

        struct commection_impl: public connection_impl_type {

            typedef commection_impl this_type;
            std::string             name_;
            common::delayed_call    keepalive_calls_;

            commection_impl( listener &listen,
                                  vtrc::shared_ptr<socket_type> sock,
                                  const close_closure &on_close_cb,
                                  const std::string &name )
                :connection_impl_type(listen, sock, on_close_cb)
                ,name_(name)
                ,keepalive_calls_(listen.get_application( ).get_io_service( ))
            { }

            void on_init_timeout( const bsys::error_code &error )
            {
                if( !error ) {
                    close( );
                }
            }

            std::string name(  ) const
            {
                return name_;
            }

            void set_name( const std::string &name )
            {
                name_ = name;
            }

            bool is_local( ) const
            {
                return false;
            }

            void start_read_clos( bsys::error_code const & /*err*/,
                                  common::connection_iface_wptr &inst )
            {
                common::connection_iface_sptr lck(inst.lock( ));
                if( lck ) {
                    start_reading( );
                }
            }

            void ssl_handshake_handler( bsys::error_code const & err,
                                        common::connection_iface_wptr &inst )
            {
                common::connection_iface_sptr lck(inst.lock( ));
                if( !lck ) {
                    return;
                }

                keepalive_calls_.cancel( );

                if( !err ) {
                    protocol_->init_success(
                                vtrc::bind( &this_type::start_read_clos, this,
                                            vtrc::placeholders::error,
                                            this->weak_from_this( )));
                } else {
                    close( );
                }
            }

            void init( )
            {
                namespace ph = vtrc::placeholders;

                keepalive_calls_.call_from_now(
                            vtrc::bind( &this_type::on_init_timeout, this,
                                        ph::error ),
                            boost::posix_time::seconds( 5 ));

                get_socket( ).async_handshake( bssl::stream_base::server,
                    vtrc::bind( &this_type::ssl_handshake_handler, this,
                                 ph::error,
                                 this->weak_from_this( ) ) );
            }

            static vtrc::shared_ptr<this_type> create( listener &listnr,
                                     vtrc::shared_ptr<socket_type> sock,
                                     const close_closure &on_close_cb )
            {
                vtrc::shared_ptr<this_type> new_inst
                        (vtrc::make_shared<this_type>(vtrc::ref(listnr),
                                            sock, vtrc::ref(on_close_cb),
                                            "" ) );

                rpc::session_options const &opts(listnr.get_options( ));

                new_inst->protocol_.reset(
                        new protocol_layer_s( new_inst->app_,
                                                new_inst.get( ), opts ) );

                return new_inst;
            }
        };

        endpoint_type make_endpoint( const std::string &address,
                                     unsigned short port )
        {
            return endpoint_type(bip::address::from_string(address), port);
        }

        struct listener_ssl: public listener {

            typedef listener_ssl this_type;

            basio::io_service              &ios_;
            endpoint_type                   endpoint_;
            vtrc::unique_ptr<acceptor_type> acceptor_;
            bool                            working_;
            bool                            no_delay_;
            basio::ssl::context             context_;
            ssl::setup_function_type        setup_cb_;

            listener_ssl( application &app,
                          const rpc::session_options &opts,
                          const std::string &address,
                          unsigned short port,
                          ssl::setup_function_type setup_cb,
                          bool no_delay )
                :listener(app, opts)
                ,ios_(app.get_io_service( ))
                ,endpoint_(make_endpoint(address, port))
                ,working_(false)
                ,no_delay_(no_delay)
                ,context_(bssl::context::sslv23)
                ,setup_cb_(setup_cb)
            { }

            void on_client_destroy( vtrc::weak_ptr<listener> inst,
                                    const common::connection_iface *conn )
            {
                vtrc::shared_ptr<listener> lock( inst.lock( ) );
                if( lock ) {
                    this->stop_connection( conn );
                }
            }

            close_closure get_on_close_cb( )
            {
                return vtrc::bind( &this_type::on_client_destroy, this,
                                   weak_from_this( ), vtrc::placeholders::_1 );
            }

            void start( )
            {
                setup_cb_( context_ );
//                context_.set_options(
//                      bssl::context::default_workarounds
//                    | bssl::context::no_sslv2
//                    | bssl::context::single_dh_use);
//                context_.set_password_callback(
//                            vtrc::bind( &server::get_password, this ) );
//                context_.use_certificate_chain_file("server.crt");
//                context_.use_private_key_file("server.key", bssl::context::pem);
//                context_.use_tmp_dh_file("dh1024.pem");

                working_ = true;
                acceptor_.reset(new acceptor_type(ios_, endpoint_));
                acceptor_->listen( 5 );
                start_accept( );
                call_on_start( );
            }

            void start_accept( )
            {
                vtrc::shared_ptr<socket_type> new_sock
                                            ( new socket_type(ios_, context_) );

//                    ( vtrc::make_shared<socket_type>( vtrc::ref(ios_),
//                                                      vtrc::ref(context_)));

                acceptor_->async_accept( new_sock->lowest_layer( ),
                    vtrc::bind( &this_type::on_accept, this,
                                 vtrc::placeholders::error, new_sock,
                                 weak_from_this( )));
            }

            void stop ( )
            {
                working_ = false;
                acceptor_->close( );
                //stop_impl( );
            }

            bool is_active( ) const
            {
                return working_;
            }

            bool is_local( ) const
            {
                return false;
            }

            void on_accept( const bsys::error_code &error,
                            vtrc::shared_ptr<socket_type> sock,
                            vtrc::weak_ptr<listener> &inst )
            {
                vtrc::shared_ptr<listener> locked( inst.lock( ));
                if( !locked ) {
                    return;
                }

                if( !error ) {
                    vtrc::shared_ptr<commection_impl> new_conn;
                    try {
                        new_conn = commection_impl::create( *this, sock,
                                                            get_on_close_cb( ));

                        connection_setup( new_conn );

                        namespace ph = vtrc::placeholders;

                        new_conn->get_protocol( )
                                 .set_precall( vtrc::bind(
                                                  &this_type::mk_precall, this,
                                                   ph::_1, ph::_2, ph::_3 ) );
                        new_conn->get_protocol( )
                                 .set_postcall( vtrc::bind(
                                                  &this_type::mk_postcall, this,
                                                   ph::_1, ph::_2 ) );

                        get_application( ).get_clients( )->store( new_conn );
                        new_connection( new_conn.get( ) );

                        new_conn->init( );

                    } catch( ... ) {
                        if( new_conn.get( ) )  {
                            get_application( ).get_clients( )
                                             ->drop( new_conn.get( ) );
                        }
                    }
                    start_accept( );
                } else {
                    if( working_ ) {
                        stop( );
                        call_on_accept_failed( error );
                    } else {
                        call_on_stop( );
                    }
                }
            }

            std::string name( ) const
            {
                std::ostringstream oss;

                oss << "ssl://" << endpoint_.address( ).to_string( )
                    << ":"
                    << endpoint_.port( );

                return oss.str( );
            }

            void connection_setup( vtrc::shared_ptr<commection_impl> &con )
            {
                con->set_no_delay( no_delay_ );
                std::ostringstream oss;
                oss << "ssl://" << con->get_socket( )
                                        .lowest_layer( ).remote_endpoint( );
                con->set_name( oss.str( ) );
            }

        };
    }

    namespace tcp_ssl {

        listener_sptr create(application &app,
                             const rpc::session_options &opts,
                             const std::string &address,
                             unsigned short service,
                             vtrc::server::ssl::setup_function_type setup,
                             bool tcp_nodelay)
        {

            vtrc::shared_ptr<listener_ssl>new_l
                    (vtrc::make_shared<listener_ssl>(
                             vtrc::ref(app), vtrc::ref(opts),
                             vtrc::ref(address), service,
                             setup, tcp_nodelay ));
            return new_l;
        }

        listener_sptr create( application &app,
                              const std::string &address,
                              unsigned short service,
                              vtrc::server::ssl::setup_function_type setup,
                              bool tcp_nodelay )
        {
            const rpc::session_options
                    def_opts( common::defaults::session_options( ) );

            return create( app, def_opts, address,
                           service, setup, tcp_nodelay );
        }

    }

}}}

#endif
<|endoftext|>


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

#include <cstring>

#include <algorithm>

#include <sstream>

#include <string>

#include <vector>

namespace generic
{

// cstrlen
//////////////////////////////////////////////////////////////////////////////
template <::std::size_t N>
inline constexpr ::std::size_t cstrlen(char const (&)[N]) noexcept
{
  return N - 1;
}

//////////////////////////////////////////////////////////////////////////////
inline constexpr ::std::size_t cstrlen(char const* const p) noexcept
{
  return *p ? 1 + cstrlen(p + 1) : 0;
}

// join
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
  typename C::value_type const sep) noexcept
{
  if (container.size())
  {
    typename C::value_type r(*container.begin());

    auto const end(container.end());

    for (auto i(::std::next(container.begin())); i != end; ++i)
    {
      r += sep + *i;
    }

    return r;
  }
  else
  {
    return typename C::value_type();
  }
}

//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
  typename C::value_type::value_type const sep) noexcept
{
  if (container.size())
  {
    typename C::value_type r(container.front());

    auto const end(container.end());

    for (typename C::const_iterator i(container.begin() + 1); i != end; ++i)
    {
      r += sep + *i;
    }

    return r;
  }
  else
  {
    return typename C::value_type();
  }
}

// split
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline ::std::vector<::std::basic_string<CharT, Traits, Allocator> >
split(::std::basic_string<CharT, Traits, Allocator> const& s,
  CharT const delim) noexcept
{
  ::std::stringstream ss(s);

  ::std::string item;

  ::std::vector<typename ::std::decay<decltype(s)>::type> r;

  while (::std::getline(ss, item, delim))
  {
    r.push_back(item);
  }

  return r;
}

//////////////////////////////////////////////////////////////////////////////
inline ::std::vector<::std::string>
split(::std::string const& s,
  char const* const delims = "\f\n\r\t\v") noexcept
{
  ::std::vector<typename ::std::decay<decltype(s)>::type> r;

  auto const S(s.size());
  decltype(s.size()) i{};

  while (i < S)
  {
    while ((i < S) && ::std::strchr(delims, s[i]))
    {
      ++i;
    }

    if (i == S)
    {
      break;
    }
    // else do nothing

    auto j(i + 1);

    while ((j < S) && !::std::strchr(delims, s[j]))
    {
      ++j;
    }

    r.push_back(s.substr(i, j - i));

    i = j + 1;
  }

  return r;
}

// trim
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
ltrim(::std::basic_string<CharT, Traits, Allocator>& s,
  CharT const* cs = " ") noexcept
{
  s.erase(s.begin(),
    ::std::find_if(s.begin(), s.end(),
      [cs](char const c) noexcept {
        return !::std::strrchr(cs, c);
      }
    )
  );

  return s;
}

template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
rtrim(::std::basic_string<CharT, Traits, Allocator>& s,
  CharT const* cs = " ") noexcept
{
  s.erase(::std::find_if(s.rbegin(), s.rend(),
      [cs](char const c) noexcept {
        return !::std::strrchr(cs, c);
      }
    ).base(),
    s.end()
  );

  return s;
}

template<class CharT, class Traits, class Allocator>
inline ::std::basic_string<CharT, Traits, Allocator>&
trim(::std::basic_string<CharT, Traits, Allocator>& s,
  CharT const* cs = " ") noexcept
{
  return ltrim(rtrim(s, cs), cs);
}

}

#endif // GENERIC_STRING_HPP
<commit_msg>some fixes<commit_after>#ifndef GNR_STRING_HPP
# define GNR_STRING_HPP
# pragma once

#include <cstring>

#include <algorithm>

#include <sstream>

#include <string>

#include <vector>

namespace gnr
{

// cstrlen
//////////////////////////////////////////////////////////////////////////////
template <std::size_t N>
inline constexpr std::size_t cstrlen(char const (&)[N]) noexcept
{
  return N - 1;
}

//////////////////////////////////////////////////////////////////////////////
inline constexpr std::size_t cstrlen(char const* const p) noexcept
{
  return *p ? 1 + cstrlen(p + 1) : 0;
}

// join
//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
  typename C::value_type const sep) noexcept
{
  if (container.size())
  {
    typename C::value_type r(*container.begin());

    auto const end(container.end());

    for (auto i(std::next(container.begin())); i != end; ++i)
    {
      r += sep + *i;
    }

    return r;
  }
  else
  {
    return typename C::value_type();
  }
}

//////////////////////////////////////////////////////////////////////////////
template <typename C>
inline typename C::value_type join(C const& container,
  typename C::value_type::value_type const sep) noexcept
{
  if (container.size())
  {
    typename C::value_type r(container.front());

    auto const end(container.end());

    for (typename C::const_iterator i(container.begin() + 1); i != end; ++i)
    {
      r += sep + *i;
    }

    return r;
  }
  else
  {
    return typename C::value_type();
  }
}

// split
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline std::vector<std::basic_string<CharT, Traits, Allocator> >
split(std::basic_string<CharT, Traits, Allocator> const& s,
  CharT const delim) noexcept
{
  std::stringstream ss(s);

  std::string item;

  std::vector<typename std::decay<decltype(s)>::type> r;

  while (std::getline(ss, item, delim))
  {
    r.push_back(item);
  }

  return r;
}

//////////////////////////////////////////////////////////////////////////////
inline std::vector<std::string>
split(std::string const& s,
  char const* const delims = "\f\n\r\t\v") noexcept
{
  std::vector<typename std::decay<decltype(s)>::type> r;

  auto const S(s.size());
  decltype(s.size()) i{};

  while (i < S)
  {
    while ((i < S) && std::strchr(delims, s[i]))
    {
      ++i;
    }

    if (i == S)
    {
      break;
    }
    // else do nothing

    auto j(i + 1);

    while ((j < S) && !std::strchr(delims, s[j]))
    {
      ++j;
    }

    r.push_back(s.substr(i, j - i));

    i = j + 1;
  }

  return r;
}

// trim
//////////////////////////////////////////////////////////////////////////////
template<class CharT, class Traits, class Allocator>
inline std::basic_string<CharT, Traits, Allocator>&
ltrim(std::basic_string<CharT, Traits, Allocator>& s,
  CharT const* cs = " ") noexcept
{
  s.erase(s.begin(),
    std::find_if(s.begin(), s.end(),
      [cs](char const c) noexcept {
        return !std::strrchr(cs, c);
      }
    )
  );

  return s;
}

template<class CharT, class Traits, class Allocator>
inline std::basic_string<CharT, Traits, Allocator>&
rtrim(std::basic_string<CharT, Traits, Allocator>& s,
  CharT const* cs = " ") noexcept
{
  s.erase(std::find_if(s.rbegin(), s.rend(),
      [cs](char const c) noexcept {
        return !std::strrchr(cs, c);
      }
    ).base(),
    s.end()
  );

  return s;
}

template<class CharT, class Traits, class Allocator>
inline std::basic_string<CharT, Traits, Allocator>&
trim(std::basic_string<CharT, Traits, Allocator>& s,
  CharT const* cs = " ") noexcept
{
  return ltrim(rtrim(s, cs), cs);
}

}

#endif // GNR_STRING_HPP
<|endoftext|>


<commit_before>#include "mitkPointSet.h"

#include <mitkOperation.h>
#include <mitkOperationActor.h>

#include <qapplication.h>//@todo because of quickimplementation UpdateAllWidgets
#include <qwidgetlist.h>//@todo because of quickimplementation UpdateAllWidgets

#include <mitkPointOperation.h>
#include "mitkStatusBar.h"
#include "mitkInteractionConst.h"

inline void UpdateAllWidgets()//@todo global quickimplementation. is to be changed into Modified Data...
{
    QWidgetList *list = QApplication::allWidgets();
    QWidgetListIt it( *list );         // iterate over the widgets
    QWidget * w;
    while ( (w=it.current()) != 0 ) {  // for each widget...
        ++it;
        w->update();
    }
    delete list;                      // delete the list, not the widgets

}

//##ModelId=3F0177E901BD
mitk::PointSet::PointSet()
{
  m_PointSet = PointSetType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_PointSet->SetPointData(pointData);
  m_Geometry3D->Initialize();
}

//##ModelId=3F0177E901BE
mitk::PointSet::~PointSet()
{}

//##ModelId=3F0177E901C1
int mitk::PointSet::GetSize()
{
  return m_PointSet->GetNumberOfPoints();
}

//##ModelId=3F0177E901CC
const mitk::PointSet::PointSetType::Pointer mitk::PointSet::GetPointSet() const
{
  return m_PointSet;
}

//##ModelId=3F0177E901DE
//##Documentation
//##@brief searches a point in the list with a given precision
int mitk::PointSet::SearchPoint(ITKPoint3D point, float distance )
{
//in is the given point to search
//out is the point which is checked to be the searched point
//pout is a pointer on out to work with itkPointSet
  PointType in, out;

  //converting point:
  in[0] = point[0];
  in[1] = point[1];
  in[2] = point[2];
  out.Fill(0);

  //searching the first point in the Set, that is +- distance far away from the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_PointSet->GetPoints()->End();
 	for (it = m_PointSet->GetPoints()->Begin(), i=0; it != end; it++, i++)
	{
    bool ok = m_PointSet->GetPoints()->GetElementIfIndexExists(it->Index(), &out);//could be optimized
    if (!ok)
      return -1;
    else if (in == out)//if totaly equal
      return it->Index();

    //distance calculation
		if ( ( in[0] >= ( out[0] - distance ) ) && ( in[0] <= ( out[0] + distance ) ) &&
			 ( in[1] >= ( out[1] - distance ) ) && ( in[1] <= ( out[1] + distance ) ) &&
			 ( in[2] >= ( out[2] - distance ) ) && ( in[2] <= ( out[2] + distance ) ) )
      return it->Index();
	}
	return -1;
}

//##ModelId=3F0177E901CE
//##Documentation
//##@brief check if index exists. If it doesn't exist, then return 0,0,0
const mitk::PointSet::PointType mitk::PointSet::GetPoint(int position)
{
  PointType out;
  out.Fill(0);

  if (m_PointSet->GetPoints()->IndexExists(position))
  {
    m_PointSet->GetPoint(position, &out);
    return out;
  }
  else
    return out;
}

const mitk::ITKPoint3D mitk::PointSet::GetItkPoint(int position)
{
	mitk::ITKPoint3D itkout;
  PointType out;
  out.Fill(0);

  //if the Index exists... if not, then return 0,0,0
  if (m_PointSet->GetPoints()->IndexExists(position))
  {
    m_PointSet->GetPoint(position, &out);
  }

  itkout[0] = out[0];
  itkout[1] = out[1];
  itkout[2] = out[2];
  return itkout;
}

bool mitk::PointSet::IndexExists(int position)
{
  return m_PointSet->GetPoints()->IndexExists(position);
}

//##ModelId=3F0177E901DC
bool mitk::PointSet::GetSelectInfo(int position)
{
  if (m_PointSet->GetPoints()->IndexExists(position))
	{
    bool selected = false;
    m_PointSet->GetPointData(position, &selected);
    return selected;
	}
	else
		return false;
}

//##ModelId=3F05B07B0147
const int mitk::PointSet::GetNumberOfSelected()
{
    int numberOfSelected = 0;
    for (PointDataIterator it = m_PointSet->GetPointData()->Begin(); it != m_PointSet->GetPointData()->End(); it++)
    {
        if (it->Value() == true)
            numberOfSelected++;
    }
    return numberOfSelected;
}

//##ModelId=3F0177E901BF
//##Documentation
//## @brief executes the given Operation
void mitk::PointSet::ExecuteOperation(Operation* operation)
/*Notes
	a new point is set to unselected. if it is to be selected, then define in StateMachine as a additional sideeffect
*/
{
	mitk::PointOperation *pointOp = dynamic_cast<mitk::PointOperation *>(operation);
	if (pointOp == NULL)
	{
		(StatusBar::GetInstance())->DisplayText("Recieved wrong type of operation!See mitkPointSetInteractor.cpp", 10000);
		return;
	}

	switch (operation->GetOperationType())
	{
	case OpNOTHING:
		break;
	//case OpADD://!!!!!#### shall not be used! Use Insert instead to know the position for undo-operation ####!!!!!
	//	{
 //     unsigned long idoffset = m_PointSet->GetNumberOfPoints();
 //     mitk::ITKPoint3D a0 = pointOp->GetPoint();
 //     PointType a1;
 //     a1[0] = a0[0];
 //     a1[1] = a0[1];
 //     a1[2] = a0[2];
 //     m_PointSet->SetPoint(idoffset, a1);
 //     m_PointSet->SetPointData(idoffset, false);
	//	}
	//	break;
  //case OpDELETE://!!!!####shall not be used anymore! Use remove(index) instead to know the position for undo-operation####!!!!
		//{
  //    m_PointSet->GetPoints()->DeleteIndex(m_PointSet->GetNumberOfPoints()-1);
		//}
		//break;
	case OpINSERT://inserts the point at the given position
		{
      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      m_PointSet->GetPoints()->InsertElement(position, pt);
      m_PointSet->GetPointData()->InsertElement(position, false);
		}
		break;
	case OpMOVE://moves the point given by index
		{
			PointType pt;
      pt.CastFrom(pointOp->GetPoint());
      m_PointSet->SetPoint(pointOp->GetIndex(), pt);
		}
		break;
	case OpREMOVE://removes the point at given by position
		{
      m_PointSet->GetPoints()->DeleteIndex((unsigned)pointOp->GetIndex());
      m_PointSet->GetPointData()->DeleteIndex((unsigned)pointOp->GetIndex());
		}
		break;
	case OpSELECTPOINT://select the given point
		{
      m_PointSet->SetPointData(pointOp->GetIndex(), true);
		}
		break;
	case OpDESELECTPOINT://unselect the given point
		{
		  m_PointSet->SetPointData(pointOp->GetIndex(), false);
		}
		break;
	default:
		NULL;
	}
	//to tell the mappers, that the data is modifierd and has to be updated
	this->Modified();

  ((const itk::Object*)this)->InvokeEvent(itk::EndEvent());

  UpdateAllWidgets();
}

//##ModelId=3F0177E901EE
void mitk::PointSet::UpdateOutputInformation()
{
  const PointSetType::BoundingBoxType *bb = m_PointSet->GetBoundingBox();
  BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
  float mitkBounds[6];

  //for assignment see Geometry3d::SetBoundingBox(const float bounds)
  mitkBounds[0] = itkBounds[0];
  mitkBounds[1] = itkBounds[1];
  mitkBounds[2] = itkBounds[2];
  mitkBounds[3] = itkBounds[3];
  mitkBounds[4] = itkBounds[4];
  mitkBounds[5] = itkBounds[5];
//@TODO check if order is correct 012345 or 024135; Bounds/BoundingBox and so on.

  m_Geometry3D->SetBoundingBox(mitkBounds);
}

//##ModelId=3F0177E901FB
void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}
//##ModelId=3F0177E901FD
bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}
//##ModelId=3F0177E901FF
bool mitk::PointSet::VerifyRequestedRegion()
{
    return false;
}
//##ModelId=3F0177E9020B
void mitk::PointSet::SetRequestedRegion(itk::DataObject*)
{
}

<commit_msg>removed code that was commented out: Operations that should not be used anymore.<commit_after>#include "mitkPointSet.h"

#include <mitkOperation.h>
#include <mitkOperationActor.h>

#include <qapplication.h>//@todo because of quickimplementation UpdateAllWidgets
#include <qwidgetlist.h>//@todo because of quickimplementation UpdateAllWidgets

#include <mitkPointOperation.h>
#include "mitkStatusBar.h"
#include "mitkInteractionConst.h"

inline void UpdateAllWidgets()//@todo global quickimplementation. is to be changed into Modified Data...
{
    QWidgetList *list = QApplication::allWidgets();
    QWidgetListIt it( *list );         // iterate over the widgets
    QWidget * w;
    while ( (w=it.current()) != 0 ) {  // for each widget...
        ++it;
        w->update();
    }
    delete list;                      // delete the list, not the widgets

}

//##ModelId=3F0177E901BD
mitk::PointSet::PointSet()
{
  m_PointSet = PointSetType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_PointSet->SetPointData(pointData);
  m_Geometry3D->Initialize();
}

//##ModelId=3F0177E901BE
mitk::PointSet::~PointSet()
{}

//##ModelId=3F0177E901C1
int mitk::PointSet::GetSize()
{
  return m_PointSet->GetNumberOfPoints();
}

//##ModelId=3F0177E901CC
const mitk::PointSet::PointSetType::Pointer mitk::PointSet::GetPointSet() const
{
  return m_PointSet;
}

//##ModelId=3F0177E901DE
//##Documentation
//##@brief searches a point in the list with a given precision
int mitk::PointSet::SearchPoint(ITKPoint3D point, float distance )
{
//in is the given point to search
//out is the point which is checked to be the searched point
//pout is a pointer on out to work with itkPointSet
  PointType in, out;

  //converting point:
  in[0] = point[0];
  in[1] = point[1];
  in[2] = point[2];
  out.Fill(0);

  //searching the first point in the Set, that is +- distance far away from the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_PointSet->GetPoints()->End();
 	for (it = m_PointSet->GetPoints()->Begin(), i=0; it != end; it++, i++)
	{
    bool ok = m_PointSet->GetPoints()->GetElementIfIndexExists(it->Index(), &out);//could be optimized
    if (!ok)
      return -1;
    else if (in == out)//if totaly equal
      return it->Index();

    //distance calculation
		if ( ( in[0] >= ( out[0] - distance ) ) && ( in[0] <= ( out[0] + distance ) ) &&
			 ( in[1] >= ( out[1] - distance ) ) && ( in[1] <= ( out[1] + distance ) ) &&
			 ( in[2] >= ( out[2] - distance ) ) && ( in[2] <= ( out[2] + distance ) ) )
      return it->Index();
	}
	return -1;
}

//##ModelId=3F0177E901CE
//##Documentation
//##@brief check if index exists. If it doesn't exist, then return 0,0,0
const mitk::PointSet::PointType mitk::PointSet::GetPoint(int position)
{
  PointType out;
  out.Fill(0);

  if (m_PointSet->GetPoints()->IndexExists(position))
  {
    m_PointSet->GetPoint(position, &out);
    return out;
  }
  else
    return out;
}

const mitk::ITKPoint3D mitk::PointSet::GetItkPoint(int position)
{
	mitk::ITKPoint3D itkout;
  PointType out;
  out.Fill(0);

  //if the Index exists... if not, then return 0,0,0
  if (m_PointSet->GetPoints()->IndexExists(position))
  {
    m_PointSet->GetPoint(position, &out);
  }

  itkout[0] = out[0];
  itkout[1] = out[1];
  itkout[2] = out[2];
  return itkout;
}

bool mitk::PointSet::IndexExists(int position)
{
  return m_PointSet->GetPoints()->IndexExists(position);
}

//##ModelId=3F0177E901DC
bool mitk::PointSet::GetSelectInfo(int position)
{
  if (m_PointSet->GetPoints()->IndexExists(position))
	{
    bool selected = false;
    m_PointSet->GetPointData(position, &selected);
    return selected;
	}
	else
		return false;
}

//##ModelId=3F05B07B0147
const int mitk::PointSet::GetNumberOfSelected()
{
    int numberOfSelected = 0;
    for (PointDataIterator it = m_PointSet->GetPointData()->Begin(); it != m_PointSet->GetPointData()->End(); it++)
    {
        if (it->Value() == true)
            numberOfSelected++;
    }
    return numberOfSelected;
}

//##ModelId=3F0177E901BF
//##Documentation
//## @brief executes the given Operation
void mitk::PointSet::ExecuteOperation(Operation* operation)
/*Notes
	a new point is set to unselected. if it is to be selected, then define in StateMachine as a additional sideeffect
*/
{
	mitk::PointOperation *pointOp = dynamic_cast<mitk::PointOperation *>(operation);
	if (pointOp == NULL)
	{
		(StatusBar::GetInstance())->DisplayText("Recieved wrong type of operation!See mitkPointSetInteractor.cpp", 10000);
		return;
	}

	switch (operation->GetOperationType())
	{
	case OpNOTHING:
		break;
	case OpINSERT://inserts the point at the given position
		{
      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      m_PointSet->GetPoints()->InsertElement(position, pt);
      m_PointSet->GetPointData()->InsertElement(position, false);
		}
		break;
	case OpMOVE://moves the point given by index
		{
			PointType pt;
      pt.CastFrom(pointOp->GetPoint());
      m_PointSet->SetPoint(pointOp->GetIndex(), pt);
		}
		break;
	case OpREMOVE://removes the point at given by position
		{
      m_PointSet->GetPoints()->DeleteIndex((unsigned)pointOp->GetIndex());
      m_PointSet->GetPointData()->DeleteIndex((unsigned)pointOp->GetIndex());
		}
		break;
	case OpSELECTPOINT://select the given point
		{
      m_PointSet->SetPointData(pointOp->GetIndex(), true);
		}
		break;
	case OpDESELECTPOINT://unselect the given point
		{
		  m_PointSet->SetPointData(pointOp->GetIndex(), false);
		}
		break;
	default:
		NULL;
	}
	//to tell the mappers, that the data is modifierd and has to be updated
	this->Modified();

  ((const itk::Object*)this)->InvokeEvent(itk::EndEvent());

  UpdateAllWidgets();
}

//##ModelId=3F0177E901EE
void mitk::PointSet::UpdateOutputInformation()
{
  const PointSetType::BoundingBoxType *bb = m_PointSet->GetBoundingBox();
  BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
  float mitkBounds[6];

  //for assignment see Geometry3d::SetBoundingBox(const float bounds)
  mitkBounds[0] = itkBounds[0];
  mitkBounds[1] = itkBounds[1];
  mitkBounds[2] = itkBounds[2];
  mitkBounds[3] = itkBounds[3];
  mitkBounds[4] = itkBounds[4];
  mitkBounds[5] = itkBounds[5];
//@TODO check if order is correct 012345 or 024135; Bounds/BoundingBox and so on.

  m_Geometry3D->SetBoundingBox(mitkBounds);
}

//##ModelId=3F0177E901FB
void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}
//##ModelId=3F0177E901FD
bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}
//##ModelId=3F0177E901FF
bool mitk::PointSet::VerifyRequestedRegion()
{
    return false;
}
//##ModelId=3F0177E9020B
void mitk::PointSet::SetRequestedRegion(itk::DataObject*)
{
}

<|endoftext|>


<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsestartup.hh"
#include "bsemain.hh"
#include "bse/internal.hh"
#include "bse/bseserver.hh"
#include <bse/bseapi_handles.hh>

namespace Bse {

// == BSE Initialization ==

/** Create SFI glue layer context.
 * Create and push an SFI glue layer context for the calling thread, to enable communications with the
 * main BSE thread library.
 */
SfiGlueContext*
init_glue_context (const gchar *client, const std::function<void()> &caller_wakeup)
{
  return _bse_glue_context_create (client, caller_wakeup);
}

/** Initialize and start BSE.
 * Initialize the BSE library and start the main BSE thread. Arguments specific to BSE are removed
 * from @a argc / @a argv.
 */
void
init_async (int *argc, char **argv, const char *app_name, const StringVector &args)
{
  _bse_init_async (argc, argv, app_name, args);
}

/// Check wether init_async() still needs to be called.
bool
init_needed ()
{
  return _bse_initialized() == false;
}

// == TaskRegistry ==
static std::mutex         task_registry_mutex_;
static TaskRegistry::List task_registry_tasks_;

void
TaskRegistry::add (const std::string &name, int pid, int tid)
{
  Bse::TaskStatus task (pid, tid);
  task.name = name;
  task.update();
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  task_registry_tasks_.push_back (task);
}

bool
TaskRegistry::remove (int tid)
{
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  for (auto it = task_registry_tasks_.begin(); it != task_registry_tasks_.end(); it++)
    if (it->task_id == tid)
      {
        task_registry_tasks_.erase (it);
        return true;
      }
  return false;
}

void
TaskRegistry::update ()
{
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  for (auto &task : task_registry_tasks_)
    task.update();
}

TaskRegistry::List
TaskRegistry::list ()
{
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  return task_registry_tasks_;
}

/// Retrieve a handle for the Bse::Server instance managing the Bse thread.
ServerHandle
init_server_instance () // bse.hh
{
  ServerH server;
  server = BSE_SERVER.__handle__();
  return server;
}

} // Bse

#include "bse/bseapi_handles.cc"        // build IDL client interface
<commit_msg>BSE: bsestartup: fix includes<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#include "bsestartup.hh"
#include "bsemain.hh"
#include "bse/internal.hh"
#include "bse/bseserver.hh"
#include <bse/bse.hh>

namespace Bse {

// == BSE Initialization ==

/** Create SFI glue layer context.
 * Create and push an SFI glue layer context for the calling thread, to enable communications with the
 * main BSE thread library.
 */
SfiGlueContext*
init_glue_context (const gchar *client, const std::function<void()> &caller_wakeup)
{
  return _bse_glue_context_create (client, caller_wakeup);
}

/** Initialize and start BSE.
 * Initialize the BSE library and start the main BSE thread. Arguments specific to BSE are removed
 * from @a argc / @a argv.
 */
void
init_async (int *argc, char **argv, const char *app_name, const StringVector &args)
{
  _bse_init_async (argc, argv, app_name, args);
}

/// Check wether init_async() still needs to be called.
bool
init_needed ()
{
  return _bse_initialized() == false;
}

// == TaskRegistry ==
static std::mutex         task_registry_mutex_;
static TaskRegistry::List task_registry_tasks_;

void
TaskRegistry::add (const std::string &name, int pid, int tid)
{
  Bse::TaskStatus task (pid, tid);
  task.name = name;
  task.update();
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  task_registry_tasks_.push_back (task);
}

bool
TaskRegistry::remove (int tid)
{
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  for (auto it = task_registry_tasks_.begin(); it != task_registry_tasks_.end(); it++)
    if (it->task_id == tid)
      {
        task_registry_tasks_.erase (it);
        return true;
      }
  return false;
}

void
TaskRegistry::update ()
{
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  for (auto &task : task_registry_tasks_)
    task.update();
}

TaskRegistry::List
TaskRegistry::list ()
{
  std::lock_guard<std::mutex> locker (task_registry_mutex_);
  return task_registry_tasks_;
}

/// Retrieve a handle for the Bse::Server instance managing the Bse thread.
ServerHandle
init_server_instance () // bse.hh
{
  ServerH server;
  server = BSE_SERVER.__handle__();
  return server;
}

} // Bse

#include "bse/bseapi_handles.cc"        // build IDL client interface
<|endoftext|>