<commit_before>/* bzflag
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "LagInfo.h"

float LagInfo::threshold = 0.0;
float LagInfo::jitterthreshold = 0.0;
float LagInfo::lossthreshold = 0.0;
float LagInfo::max       = 0.0;
float LagInfo::jittermax       = 0.0;
float LagInfo::lossmax       = 0.0;

LagInfo::LagInfo(PlayerInfo *_info)
  : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),
    jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),
    jittercount(0), jitterlastwarn(0), jitterwarncount(0), losscount(0),
    losslastwarn(0), losswarncount(0), pingpending(false), pingseqno(0),
    pingssent(0), lasttimestamp(0.0f) {
}

void LagInfo::reset()
{
  nextping       = info->now;
  nextping      += 10.0;
  lastupdate     = info->now;
}

int LagInfo::getLag() const
{
  return int(lagavg * 1000);
}

int LagInfo::getJitter() const
{
  return int(jitteravg * 1000);
}

int LagInfo::getLoss() const
{
  return int(lostavg * 100);
}

float LagInfo::getLagAvg() const
{
  return lagavg;
}

void LagInfo::getLagStats(char* msg, bool isAdmin) const
{
  msg[0] = 0;
  if (!info->isPlaying() || !info->isHuman())
    return;

  // don't wait for ping to come back
  int lag = int(lagavg * 1000);
  if (pingpending) {
    float timepassed = (float)(info->now - lastping);
    int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);
    if (lastLag > lag)
      lag = lastLag;
  }

  int numchars;
  if (isAdmin)
    numchars = sprintf(msg, "[%3d] %-24.24s: %3d", info->getPlayerIndex(),

	  TextUtils::str_trunc_continued (info->getCallSign(), 22).c_str(), lag);
  else
    numchars = sprintf(msg, "%-24.24s: %3d",
	  TextUtils::str_trunc_continued (info->getCallSign(), 22).c_str(), lag);

  if (info->isObserver()) {
    sprintf(msg+numchars, "ms");
  } else {
    numchars += sprintf(msg + numchars, " +- %2dms", int(jitteravg * 1000));
    if (lostavg >= 0.01f)
      sprintf(msg + numchars, " %d%% lost/ooo", int(lostavg * 100));
  }
}

// update absolute latency based on LagPing messages
void LagInfo::updatePingLag(void *buf, bool &warn, bool &kick, bool &jittwarn,
			    bool &jittkick, bool &plosswarn, bool &plosskick) {
  uint16_t _pingseqno;
  nboUnpackUShort(buf, _pingseqno);
  if (pingseqno == _pingseqno) {
    float timepassed = float(info->now - lastping);
    // time is smoothed exponentially using a dynamic smoothing factor
    lagavg   = lagavg * (1 - lagalpha) + lagalpha * timepassed;
    lagalpha = lagalpha / (0.9f + lagalpha);
    lagcount++;
    jittercount++;
    losscount++;

    // if lag has been good for some time, forget old warnings
    if (lagavg < threshold && lagcount - laglastwarn >= 20)
      lagwarncount = 0;

    // if jitter has been good for some time, forget old warnings
    if (jitteravg < jitterthreshold && jittercount - jitterlastwarn >= 20)
      jitterwarncount = 0;

    // if loss has been good for some time, forget old warnings
    if (lostavg < lossthreshold && losscount - losslastwarn >=20)
      losswarncount = 0;

    // warn players from time to time whose lag is > threshold (-lagwarn)
    if (!info->isObserver() && (threshold > 0) && lagavg > threshold
	&& lagcount - laglastwarn > 2 * lagwarncount) {
      laglastwarn = lagcount;
      warn = true;
      kick = (++lagwarncount > max);
    } else {
      warn = false;
      kick = false;
    }

    // warn players from time to time whose jitter is > jitterthreshold (-jitterwarn)
    if (!info->isObserver() && (jitterthreshold > 0)
	&& jitteravg > jitterthreshold
	&& jittercount - jitterlastwarn > 2 * jitterwarncount) {
      jitterlastwarn = jittercount;
      jittwarn = true;
      jittkick = (++jitterwarncount > jittermax);
    } else {
      jittwarn = false;
      jittkick = false;
    }

    // warn players from time to time whose packetloss is > lossthreshold (-packetlosswarn)
    if (!info->isObserver() && (lossthreshold > 0)
	&& lostavg > lossthreshold
	&& losscount - losslastwarn > 2 * losswarncount) {
      losslastwarn = losscount;
      plosswarn = true;
      plosskick = (++losswarncount > lossmax);
    } else {
      plosswarn = false;
      plosskick = false;
    }

    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
    pingpending = false;
  } else {
    warn = false;
    kick = false;
    jittwarn = false;
    jittkick = false;
    plosswarn = false;
    plosskick = false;
  }
  return;
}

void LagInfo::updateLag(TimeKeeper const& timestamp, bool ooo) {
  if (!info->isPlaying())
    return;
  if (ooo) {
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }
  // don't calc jitter if more than 2 seconds between packets
  if (lasttimestamp && timestamp - lasttimestamp < 2.0f) {
    const float jitter = fabs((float)(info->now - lastupdate)
			      - (timestamp - lasttimestamp));
    // time is smoothed exponentially using a dynamic smoothing factor
    jitteravg   = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);
    jitteralpha = jitteralpha / (0.99f + jitteralpha);
    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
  }
  lasttimestamp = timestamp;
  lastupdate    = info->now;
}

int LagInfo::getNextPingSeqno(bool &warn, bool &kick) {

  warn = false;
  kick = false;

  if (!info->isPlaying() || !info->isHuman())
    return -1;

  if (info->now <= nextping)
    // no time for pinging
    return -1;

  pingseqno = (pingseqno + 1) % 10000;
  if (pingpending) {
    // ping lost
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }

  pingpending = true;
  lastping    = info->now;
  nextping    = info->now;
  nextping   += 10.0f;
  pingssent++;
  return pingseqno;
}

// update absolute latency based on LagPing messages
void LagInfo::updateLatency(float &waitTime) {
  if (!info->isPlaying() || !info->isHuman())
    return;
  float delta = (float)(nextping - info->now);
  if (delta < waitTime)
    waitTime  = delta;
}

void LagInfo::setThreshold(float _threshold, float _max) {
  threshold = _threshold;
  max       = _max;
}

void LagInfo::setJitterThreshold(float _jitterthreshold, float _jittermax) {
  jitterthreshold = _jitterthreshold;
  jittermax       = _jittermax;
}

void LagInfo::setPacketLossThreshold(float _lossthreshold, float _lossmax) {
  lossthreshold = _lossthreshold * 10;
  lossmax       = _lossmax;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>quell warning, nuke an unneeded fabs. <commit_after>/* bzflag
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "LagInfo.h"

float LagInfo::threshold = 0.0;
float LagInfo::jitterthreshold = 0.0;
float LagInfo::lossthreshold = 0.0;
float LagInfo::max       = 0.0;
float LagInfo::jittermax       = 0.0;
float LagInfo::lossmax       = 0.0;

LagInfo::LagInfo(PlayerInfo *_info)
  : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),
    jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),
    jittercount(0), jitterlastwarn(0), jitterwarncount(0), losscount(0),
    losslastwarn(0), losswarncount(0), pingpending(false), pingseqno(0),
    pingssent(0), lasttimestamp(0.0f) {
}

void LagInfo::reset()
{
  nextping       = info->now;
  nextping      += 10.0;
  lastupdate     = info->now;
}

int LagInfo::getLag() const
{
  return int(lagavg * 1000);
}

int LagInfo::getJitter() const
{
  return int(jitteravg * 1000);
}

int LagInfo::getLoss() const
{
  return int(lostavg * 100);
}

float LagInfo::getLagAvg() const
{
  return lagavg;
}

void LagInfo::getLagStats(char* msg, bool isAdmin) const
{
  msg[0] = 0;
  if (!info->isPlaying() || !info->isHuman())
    return;

  // don't wait for ping to come back
  int lag = int(lagavg * 1000);
  if (pingpending) {
    float timepassed = (float)(info->now - lastping);
    int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);
    if (lastLag > lag)
      lag = lastLag;
  }

  int numchars;
  if (isAdmin)
    numchars = sprintf(msg, "[%3d] %-24.24s: %3d", info->getPlayerIndex(),

	  TextUtils::str_trunc_continued (info->getCallSign(), 22).c_str(), lag);
  else
    numchars = sprintf(msg, "%-24.24s: %3d",
	  TextUtils::str_trunc_continued (info->getCallSign(), 22).c_str(), lag);

  if (info->isObserver()) {
    sprintf(msg+numchars, "ms");
  } else {
    numchars += sprintf(msg + numchars, " +- %2dms", int(jitteravg * 1000));
    if (lostavg >= 0.01f)
      sprintf(msg + numchars, " %d%% lost/ooo", int(lostavg * 100));
  }
}

// update absolute latency based on LagPing messages
void LagInfo::updatePingLag(void *buf, bool &warn, bool &kick, bool &jittwarn,
			    bool &jittkick, bool &plosswarn, bool &plosskick) {
  uint16_t _pingseqno;
  nboUnpackUShort(buf, _pingseqno);
  if (pingseqno == _pingseqno) {
    float timepassed = float(info->now - lastping);
    // time is smoothed exponentially using a dynamic smoothing factor
    lagavg   = lagavg * (1 - lagalpha) + lagalpha * timepassed;
    lagalpha = lagalpha / (0.9f + lagalpha);
    lagcount++;
    jittercount++;
    losscount++;

    // if lag has been good for some time, forget old warnings
    if (lagavg < threshold && lagcount - laglastwarn >= 20)
      lagwarncount = 0;

    // if jitter has been good for some time, forget old warnings
    if (jitteravg < jitterthreshold && jittercount - jitterlastwarn >= 20)
      jitterwarncount = 0;

    // if loss has been good for some time, forget old warnings
    if (lostavg < lossthreshold && losscount - losslastwarn >=20)
      losswarncount = 0;

    // warn players from time to time whose lag is > threshold (-lagwarn)
    if (!info->isObserver() && (threshold > 0) && lagavg > threshold
	&& lagcount - laglastwarn > 2 * lagwarncount) {
      laglastwarn = lagcount;
      warn = true;
      kick = (++lagwarncount > max);
    } else {
      warn = false;
      kick = false;
    }

    // warn players from time to time whose jitter is > jitterthreshold (-jitterwarn)
    if (!info->isObserver() && (jitterthreshold > 0)
	&& jitteravg > jitterthreshold
	&& jittercount - jitterlastwarn > 2 * jitterwarncount) {
      jitterlastwarn = jittercount;
      jittwarn = true;
      jittkick = (++jitterwarncount > jittermax);
    } else {
      jittwarn = false;
      jittkick = false;
    }

    // warn players from time to time whose packetloss is > lossthreshold (-packetlosswarn)
    if (!info->isObserver() && (lossthreshold > 0)
	&& lostavg > lossthreshold
	&& losscount - losslastwarn > 2 * losswarncount) {
      losslastwarn = losscount;
      plosswarn = true;
      plosskick = (++losswarncount > lossmax);
    } else {
      plosswarn = false;
      plosskick = false;
    }

    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
    pingpending = false;
  } else {
    warn = false;
    kick = false;
    jittwarn = false;
    jittkick = false;
    plosswarn = false;
    plosskick = false;
  }
  return;
}

void LagInfo::updateLag(TimeKeeper const& timestamp, bool ooo) {
  if (!info->isPlaying())
    return;
  if (ooo) {
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }
  // don't calc jitter if more than 2 seconds between packets
  if (lasttimestamp && timestamp - lasttimestamp < 2.0f) {
    const float jitter = fabsf((float)(info->now - lastupdate)
			     - (float)(timestamp - lasttimestamp));
    // time is smoothed exponentially using a dynamic smoothing factor
    jitteravg   = jitteravg * (1 - jitteralpha) + jitteralpha * jitter;
    jitteralpha = jitteralpha / (0.99f + jitteralpha);
    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
  }
  lasttimestamp = timestamp;
  lastupdate    = info->now;
}

int LagInfo::getNextPingSeqno(bool &warn, bool &kick) {

  warn = false;
  kick = false;

  if (!info->isPlaying() || !info->isHuman())
    return -1;

  if (info->now <= nextping)
    // no time for pinging
    return -1;

  pingseqno = (pingseqno + 1) % 10000;
  if (pingpending) {
    // ping lost
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }

  pingpending = true;
  lastping    = info->now;
  nextping    = info->now;
  nextping   += 10.0f;
  pingssent++;
  return pingseqno;
}

// update absolute latency based on LagPing messages
void LagInfo::updateLatency(float &waitTime) {
  if (!info->isPlaying() || !info->isHuman())
    return;
  float delta = (float)(nextping - info->now);
  if (delta < waitTime)
    waitTime  = delta;
}

void LagInfo::setThreshold(float _threshold, float _max) {
  threshold = _threshold;
  max       = _max;
}

void LagInfo::setJitterThreshold(float _jitterthreshold, float _jittermax) {
  jitterthreshold = _jitterthreshold;
  jittermax       = _jittermax;
}

void LagInfo::setPacketLossThreshold(float _lossthreshold, float _lossmax) {
  lossthreshold = _lossthreshold * 10;
  lossmax       = _lossmax;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include "datum.h"

#include <boost/pool/singleton_pool.hpp>

#include "timer.h"

namespace cyclus {

typedef boost::singleton_pool<Datum, sizeof(Datum)> DatumPool;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Datum* Datum::AddValBase(const char* field, boost::spirit::hold_any val,
                         std::vector<int>* shape) {
  vals_.push_back(std::pair<const char*, boost::spirit::hold_any>(field, val));
  std::vector<int> s;
  if (shape == NULL)
    shapes_.push_back(s);
  else
    shapes_.push_back(*shape);
  return this;
}

Datum* Datum::AddVal(const char* field, boost::spirit::hold_any val,
                     std::vector<int>* shape) {
  fields_.push_back(std::string(field));
  return AddValBase(field, val, shape);
}

Datum* Datum::AddVal(std::string field, boost::spirit::hold_any val,
                     std::vector<int>* shape) {
  fields_.push_back(field);
  return AddValBase(field.c_str(), val, shape);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Datum::Record() {
  manager_->AddDatum(this);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Datum::Datum(Recorder* m, std::string title) : title_(title), manager_(m) {
  // The (vect) size to reserve is chosen to be just bigger than most/all cyclus
  // core tables.  This prevents extra reallocations in the underlying
  // vector as vals are added to the datum.
  vals_.reserve(10);
  shapes_.reserve(10);
  fields_.reserve(10);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Datum::~Datum() {}

std::string Datum::title() {
  return title_;
}

const Datum::Vals& Datum::vals() {
  return vals_;
}

const Datum::Shapes& Datum::shapes() {
  return shapes_;
}

const Datum::Fields& Datum::fields() {
  return fields_;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void* Datum::operator new(size_t size) {
  if (size != sizeof(Datum)) {
    return ::operator new(size);
  }

  while (true) {
    void* ptr = DatumPool::malloc();
    if (ptr != NULL) {
      return ptr;
    }

    std::new_handler globalNewHandler = std::set_new_handler(0);
    std::set_new_handler(globalNewHandler);

    if (globalNewHandler) {
      globalNewHandler();
    } else {
      throw std::bad_alloc();
    }
  }
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Datum::operator delete(void* rawMemory) throw() {
  if (rawMemory == 0) {
    return;
  }
  DatumPool::free(rawMemory);
}

}  // namespace cyclus
<commit_msg>remove timer from datum<commit_after>#include "datum.h"

#include <boost/pool/singleton_pool.hpp>

namespace cyclus {

typedef boost::singleton_pool<Datum, sizeof(Datum)> DatumPool;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Datum* Datum::AddValBase(const char* field, boost::spirit::hold_any val,
                         std::vector<int>* shape) {
  vals_.push_back(std::pair<const char*, boost::spirit::hold_any>(field, val));
  std::vector<int> s;
  if (shape == NULL)
    shapes_.push_back(s);
  else
    shapes_.push_back(*shape);
  return this;
}

Datum* Datum::AddVal(const char* field, boost::spirit::hold_any val,
                     std::vector<int>* shape) {
  fields_.push_back(std::string(field));
  return AddValBase(field, val, shape);
}

Datum* Datum::AddVal(std::string field, boost::spirit::hold_any val,
                     std::vector<int>* shape) {
  fields_.push_back(field);
  return AddValBase(field.c_str(), val, shape);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Datum::Record() {
  manager_->AddDatum(this);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Datum::Datum(Recorder* m, std::string title) : title_(title), manager_(m) {
  // The (vect) size to reserve is chosen to be just bigger than most/all cyclus
  // core tables.  This prevents extra reallocations in the underlying
  // vector as vals are added to the datum.
  vals_.reserve(10);
  shapes_.reserve(10);
  fields_.reserve(10);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Datum::~Datum() {}

std::string Datum::title() {
  return title_;
}

const Datum::Vals& Datum::vals() {
  return vals_;
}

const Datum::Shapes& Datum::shapes() {
  return shapes_;
}

const Datum::Fields& Datum::fields() {
  return fields_;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void* Datum::operator new(size_t size) {
  if (size != sizeof(Datum)) {
    return ::operator new(size);
  }

  while (true) {
    void* ptr = DatumPool::malloc();
    if (ptr != NULL) {
      return ptr;
    }

    std::new_handler globalNewHandler = std::set_new_handler(0);
    std::set_new_handler(globalNewHandler);

    if (globalNewHandler) {
      globalNewHandler();
    } else {
      throw std::bad_alloc();
    }
  }
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Datum::operator delete(void* rawMemory) throw() {
  if (rawMemory == 0) {
    return;
  }
  DatumPool::free(rawMemory);
}

}  // namespace cyclus
<|endoftext|>


<commit_before>#include <stdlib.h>
#include "nan.h"
#include "v8-debug.h"

namespace nodex {

  class Debug {
    public:

      static NAN_METHOD(Call) {
        NanScope();

        if (args.Length() < 1) {
          return NanThrowError("Error");
        }

        v8::Handle<v8::Function> fn = v8::Handle<v8::Function>::Cast(args[0]);
        v8::Debug::Call(fn);

        NanReturnUndefined();
      };

      static NAN_METHOD(Signal) {
        NanScope();

        v8::Isolate* debug_isolate = v8::Debug::GetDebugContext()->GetIsolate();

        size_t length;
        const char* msg = NanCString(args[0], &length);
        uint16_t* command = (uint16_t*)malloc(sizeof(uint16_t) * (length + 1));
        command[length] = 0;
        for (int i = 0; i < length; i++) {
          command[i] = msg[i];
        }
        v8::Debug::SendCommand(debug_isolate, command, length);

        NanReturnUndefined();
      };

      static NAN_METHOD(Mirror) {
        NanScope();

        if (args.Length() < 1) {
          return NanThrowError("Invalid number of arguments");
        }

        NanReturnValue(v8::Debug::GetMirror(args[0]));
      }

    private:
      Debug() {}
      ~Debug() {}
  };

  void Initialize(v8::Handle<v8::Object> target) {
    NanScope();
    NODE_SET_METHOD(target, "call", Debug::Call);
    NODE_SET_METHOD(target, "signal", Debug::Signal);
    NODE_SET_METHOD(target, "mirror", Debug::Mirror);
  }

  NODE_MODULE(debug, Initialize)
}<commit_msg>Fix compatibility with 0.10.x<commit_after>#include <stdlib.h>
#include "nan.h"
#include "v8-debug.h"

namespace nodex {

  class Debug {
    public:

      static NAN_METHOD(Call) {
        NanScope();

        if (args.Length() < 1) {
          return NanThrowError("Error");
        }

        v8::Handle<v8::Function> fn = v8::Handle<v8::Function>::Cast(args[0]);
        v8::Debug::Call(fn);

        NanReturnUndefined();
      };

      static NAN_METHOD(Signal) {
        NanScope();

        size_t length;
        const char* msg = NanCString(args[0], &length);
        uint16_t* command = (uint16_t*)malloc(sizeof(uint16_t) * (length + 1));
        command[length] = 0;
        for (int i = 0; i < length; i++) {
          command[i] = msg[i];
        }
#if (NODE_MODULE_VERSION > 0x000B)
        v8::Isolate* debug_isolate = v8::Debug::GetDebugContext()->GetIsolate();
        v8::Debug::SendCommand(debug_isolate, command, length);
#else
        v8::Debug::SendCommand(command, length);
#endif
        NanReturnUndefined();
      };

      static NAN_METHOD(Mirror) {
        NanScope();

        if (args.Length() < 1) {
          return NanThrowError("Invalid number of arguments");
        }

        NanReturnValue(v8::Debug::GetMirror(args[0]));
      }

    private:
      Debug() {}
      ~Debug() {}
  };

  void Initialize(v8::Handle<v8::Object> target) {
    NanScope();
    NODE_SET_METHOD(target, "call", Debug::Call);
    NODE_SET_METHOD(target, "signal", Debug::Signal);
    NODE_SET_METHOD(target, "mirror", Debug::Mirror);
  }

  NODE_MODULE(debug, Initialize)
}<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>

#include "glog/logging.h"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"

#include "obzerver/logger.hpp"
#include "obzerver/utility.hpp"
#include "obzerver/benchmarker.hpp"
#include "obzerver/camera_tracker.hpp"
#include "obzerver/object_tracker.hpp"

void mouseCallback(int event, int x, int y, int flags, void* data) {
  if (event == cv::EVENT_LBUTTONDOWN) {
    bool* pause = (bool*) data;
    *pause = !(*pause);
  } else if (event == cv::EVENT_RBUTTONDOWN) {
    std::cout << "Right click at " << x << " , " << y << std::endl;
  }
}

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

  cv::CommandLineParser cmd(argc, argv,
              "{ v  | video | | specify video file}"
              "{ d  | display | false | Show visualization }"
              "{ c  | clear | false | Clear Terminal }"
              "{ p  | pause | false | Start in pause mode }"
              "{ ds | downsample | 1.0 | downsample (resize) factor (0.5: half) }"
              "{ l  | logfile | | specify log file (empty: log to stderr)}"
              "{ nf | numfeatures | 300 | Number of features to track for stablization}"
              "{ np | numparticles | 1000 | Number of particles}"
              "{ hi | history | 90 | Length of history (frames) }"
              "{ k  | skip | 0 | Starting frame }"
              "{ f  | fps | 30.0 | frames per second }"
              "{ h  | help | false | print help message }"
  );

  /* Params and Command Line */

  const std::string video_src = cmd.get<std::string>("video");
  const bool display = cmd.get<bool>("display");
  const bool clear = cmd.get<bool>("clear");
  const float downsample_factor = cmd.get<float>("downsample");
  bool pause = cmd.get<bool>("pause");
  const std::string logfile = cmd.get<std::string>("logfile");
  const unsigned long int start_frame = cmd.get<unsigned long int>("skip");
  const float fps = cmd.get<float>("fps");

  const std::size_t param_max_features = cmd.get<std::size_t>("numfeatures");
  const std::size_t param_num_particles = cmd.get<std::size_t>("numparticles");
  const std::size_t param_hist_len = cmd.get<std::size_t>("history");
  const std::size_t param_pylk_winsize = 30;
  const unsigned int param_pylk_iters = 30;
  const double param_pylk_eps = 0.01;

  const int param_ffd_threshold = 30;

  if (cmd.get<bool>("help") || video_src.empty())
  {
    cmd.printParams();
    return 1;
  }

  const bool use_webam  = (video_src.compare("cam") == 0);

  /* Logger */

  obz_log_config(argv[0], logfile);

  /* Variables */
  unsigned long int frame_counter = 0;
  cv::Mat frame;
  cv::Mat frame_gray;
  cv::Mat debug_frame;
  cv::Mat stab_frame;

  StepBenchmarker& ticker = StepBenchmarker::GetInstance();
  cv::VideoCapture capture;
  cv::Ptr<cv::FeatureDetector> feature_detector = new cv::FastFeatureDetector(param_ffd_threshold, true);
  CameraTracker camera_tracker(param_hist_len, feature_detector, param_max_features, param_pylk_winsize, param_pylk_iters, param_pylk_eps);
  trackbar_data_t trackbar_data(&capture, &frame_counter);
  ObjectTracker object_tracker(param_num_particles, param_hist_len, fps);

  LOG(INFO) << "Video Source: " << video_src;

  int opengl_flags = 0;
  try {
    cv::namedWindow("dummy", cv::WINDOW_OPENGL);
    opengl_flags = cv::WINDOW_OPENGL;
    cv::destroyWindow("dummy");
  } catch (const cv::Exception& ex) {
    LOG(WARNING) << "OpenCV without OpenGL support.";
  }

  try {
    if (use_webam && !capture.open(0)) {
      LOG(ERROR) << "Can not webcam";
      return 1;
    } else if (!use_webam && !capture.open(video_src)) {
      LOG(ERROR) << "Can not open file: " << video_src;
      return 1;
    }
    if (!use_webam && start_frame > 0 && start_frame < capture.get(CV_CAP_PROP_FRAME_COUNT)) {
      frame_counter = start_frame;
      capture.set(CV_CAP_PROP_POS_FRAMES, frame_counter);
    }
    if (!use_webam) {
      LOG(INFO) << "Openning file: " << video_src << " frames: " << capture.get(CV_CAP_PROP_FRAME_COUNT);
    }
    if (display) {
      const long int num_frames = use_webam ? 0 : capture.get(CV_CAP_PROP_FRAME_COUNT);
      cv::namedWindow("Original", cv::WINDOW_AUTOSIZE | opengl_flags);
      cv::namedWindow("DiffStab", cv::WINDOW_NORMAL | opengl_flags);
      cv::namedWindow("Debug", cv::WINDOW_NORMAL | opengl_flags);
      if (num_frames > 0) {
        cv::createTrackbar("Browse", "Original", 0, num_frames, trackbarCallback, &trackbar_data);
        cv::setTrackbarPos("Browse", "Original", frame_counter);
      }
      cv::setMouseCallback("Original", mouseCallback, (void*) &pause);
    }

    ticker.reset();
    while (capture.read(frame)) {
      ticker.tick("ML_Frame_Capture");
      if (downsample_factor < 1.0 && downsample_factor > 0.0) {
        cv::resize(frame, frame, cv::Size(0, 0), downsample_factor, downsample_factor, cv::INTER_CUBIC);
        ticker.tick("ML_Downsampling");
      }
      LOG(INFO) << "Frame: " << frame_counter << " [" << frame.cols << " x " << frame.rows << "]";
      if (display && !use_webam && (frame_counter % 10 == 0)) cv::setTrackbarPos("Browse", "Original", frame_counter);
      cv::cvtColor(frame, frame_gray, cv::COLOR_BGR2GRAY);
      ticker.tick("ML_Frame_2_Gray");
      bool ct_success = camera_tracker.Update(frame_gray, frame);
      cv::Point2d center;
      double _w=0.0, _h=0.0, _f=-1.0;
      if (!ct_success) {
        LOG(WARNING) << "Camera Tracker Failed";
        // TODO
      } else {
        object_tracker.Update(camera_tracker.GetStablizedGray(), // TODO
                              camera_tracker.GetLatestDiff(),
                              camera_tracker.GetLatestSOF(),
                              camera_tracker.GetLatestCameraTransform());

        LOG(INFO) << "Tracking status: " << object_tracker.GetStatus();
        if (object_tracker.IsTracking()) {
          _f = object_tracker.GetObject().GetPeriodicity().GetDominantFrequency(1); // TODO
          LOG(INFO) << "Object: "
                    << object_tracker.GetObjectBoundingBox()
                    << " Periodicity:"
                    << _f;
          //LOG(INFO) << "Spectrum: " << cv::Mat(object_tracker.GetObject().GetPeriodicity().GetSpectrum(), false);
        }

//        if (object_tracker.GetStatus() != TRACKING_STATUS_TRACKING) {
//          if (!self_similariy.IsEmpty()) self_similariy.Reset();
//        } else {
//          self_similariy.Update(camera_tracker.GetStablized()(object_tracker.GetBoundingBox()).clone());
//          if (self_similariy.IsFull()) {
//            periodicity.Update(self_similariy.GetSimMatrix());
//            LOG(INFO) << "Dominant Frequency: " << periodicity.GetDominantFrequency();
//          }
//        }
//        center.x = sampler.Integrate(integrand_mean_x, NULL);
//        center.y = sampler.Integrate(integrand_mean_y, NULL);
//        _w = sqrt(sampler.Integrate(integrand_var_x, (void*) &(center.x)));
//        _h = sqrt(sampler.Integrate(integrand_var_y, (void*) &(center.y)));
//        LOG(INFO) << center << " : " << _w<< " - " <<  _h;
      }

      if (display) {
//        cv::Mat diff_frame = camera_tracker.GetLatestDiff();
        cv::Mat diff_frame;
        if (object_tracker.IsTracking()) {
          diff_frame = object_tracker.GetObject().GetSelfSimilarity().GetSimMatrixRendered();
          cv::imwrite("data/sim.bmp", diff_frame);
        }
        cv::Mat debug_frame = camera_tracker.GetStablizedGray();
        object_tracker.DrawParticles(debug_frame);
        if (camera_tracker.GetTrackedFeaturesCurr().size()) {
          drawFeaturePointsTrajectory(frame,
                                      camera_tracker.GetHomographyOutliers(),
                                      camera_tracker.GetTrackedFeaturesPrev(),
                                      camera_tracker.GetTrackedFeaturesCurr(),
                                      2,
                                      CV_RGB(127,127,127), CV_RGB(255, 0, 0), CV_RGB(255, 0, 0));
        }

        cv::rectangle(diff_frame, cv::Rect(center.x - _w/2, center.y-_h/2, _w, _h), CV_RGB(255, 255, 255));

        std::stringstream ss;
        ss << std::setprecision(5) << "Periodicity: " << _f;
        cv::putText(frame, ss.str(), cv::Point(40,40), 1, CV_FONT_HERSHEY_PLAIN, cv::Scalar(255, 0, 0));
        //cv::circle(diff_frame, center, 10, CV_RGB(255, 255, 255));
        if (frame.data) cv::imshow("Original", frame);
        if (diff_frame.data) cv::imshow("DiffStab", diff_frame);
        if (debug_frame.data) cv::imshow("Debug", debug_frame);
        cv::waitKey(10);
        ticker.tick("ML_Visualization");
      }
      ticker.dump(clear);
      while (display && pause) cv::waitKey(100);
      frame_counter++;
      ticker.reset();
    }
  } catch (const cv::Exception& ex) {
    LOG(ERROR) << "Exception: " << ex.what();
    if (capture.isOpened()) capture.release();
    ticker.dump();
    return 1;
  }
  return 0;
}
<commit_msg>Fix opengl check bug when graphics is off<commit_after>#include <iostream>
#include <iomanip>

#include "glog/logging.h"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"

#include "obzerver/logger.hpp"
#include "obzerver/utility.hpp"
#include "obzerver/benchmarker.hpp"
#include "obzerver/camera_tracker.hpp"
#include "obzerver/object_tracker.hpp"

void mouseCallback(int event, int x, int y, int flags, void* data) {
  if (event == cv::EVENT_LBUTTONDOWN) {
    bool* pause = (bool*) data;
    *pause = !(*pause);
  } else if (event == cv::EVENT_RBUTTONDOWN) {
    std::cout << "Right click at " << x << " , " << y << std::endl;
  }
}

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

  cv::CommandLineParser cmd(argc, argv,
              "{ v  | video | | specify video file}"
              "{ d  | display | false | Show visualization }"
              "{ c  | clear | false | Clear Terminal }"
              "{ p  | pause | false | Start in pause mode }"
              "{ ds | downsample | 1.0 | downsample (resize) factor (0.5: half) }"
              "{ l  | logfile | | specify log file (empty: log to stderr)}"
              "{ nf | numfeatures | 300 | Number of features to track for stablization}"
              "{ np | numparticles | 1000 | Number of particles}"
              "{ hi | history | 90 | Length of history (frames) }"
              "{ k  | skip | 0 | Starting frame }"
              "{ f  | fps | 30.0 | frames per second }"
              "{ h  | help | false | print help message }"
  );

  /* Params and Command Line */

  const std::string video_src = cmd.get<std::string>("video");
  const bool display = cmd.get<bool>("display");
  const bool clear = cmd.get<bool>("clear");
  const float downsample_factor = cmd.get<float>("downsample");
  bool pause = cmd.get<bool>("pause");
  const std::string logfile = cmd.get<std::string>("logfile");
  const unsigned long int start_frame = cmd.get<unsigned long int>("skip");
  const float fps = cmd.get<float>("fps");

  const std::size_t param_max_features = cmd.get<std::size_t>("numfeatures");
  const std::size_t param_num_particles = cmd.get<std::size_t>("numparticles");
  const std::size_t param_hist_len = cmd.get<std::size_t>("history");
  const std::size_t param_pylk_winsize = 30;
  const unsigned int param_pylk_iters = 30;
  const double param_pylk_eps = 0.01;

  const int param_ffd_threshold = 30;

  if (cmd.get<bool>("help") || video_src.empty())
  {
    cmd.printParams();
    return 1;
  }

  const bool use_webam  = (video_src.compare("cam") == 0);

  /* Logger */

  obz_log_config(argv[0], logfile);

  /* Variables */
  unsigned long int frame_counter = 0;
  cv::Mat frame;
  cv::Mat frame_gray;
  cv::Mat debug_frame;
  cv::Mat stab_frame;

  StepBenchmarker& ticker = StepBenchmarker::GetInstance();
  cv::VideoCapture capture;
  cv::Ptr<cv::FeatureDetector> feature_detector = new cv::FastFeatureDetector(param_ffd_threshold, true);
  CameraTracker camera_tracker(param_hist_len, feature_detector, param_max_features, param_pylk_winsize, param_pylk_iters, param_pylk_eps);
  trackbar_data_t trackbar_data(&capture, &frame_counter);
  ObjectTracker object_tracker(param_num_particles, param_hist_len, fps);

  LOG(INFO) << "Video Source: " << video_src;

  int opengl_flags = 0;
  if (display)
  {
      try {
        cv::namedWindow("dummy", cv::WINDOW_OPENGL);
        opengl_flags = cv::WINDOW_OPENGL;
        cv::destroyWindow("dummy");
      } catch (const cv::Exception& ex) {
        LOG(WARNING) << "OpenCV without OpenGL support.";
      }
  }

  try {
    if (use_webam && !capture.open(0)) {
      LOG(ERROR) << "Can not webcam";
      return 1;
    } else if (!use_webam && !capture.open(video_src)) {
      LOG(ERROR) << "Can not open file: " << video_src;
      return 1;
    }
    if (!use_webam && start_frame > 0 && start_frame < capture.get(CV_CAP_PROP_FRAME_COUNT)) {
      frame_counter = start_frame;
      capture.set(CV_CAP_PROP_POS_FRAMES, frame_counter);
    }
    if (!use_webam) {
      LOG(INFO) << "Openning file: " << video_src << " frames: " << capture.get(CV_CAP_PROP_FRAME_COUNT);
    }
    if (display) {
      const long int num_frames = use_webam ? 0 : capture.get(CV_CAP_PROP_FRAME_COUNT);
      cv::namedWindow("Original", cv::WINDOW_AUTOSIZE | opengl_flags);
      cv::namedWindow("DiffStab", cv::WINDOW_NORMAL | opengl_flags);
      cv::namedWindow("Debug", cv::WINDOW_NORMAL | opengl_flags);
      if (num_frames > 0) {
        cv::createTrackbar("Browse", "Original", 0, num_frames, trackbarCallback, &trackbar_data);
        cv::setTrackbarPos("Browse", "Original", frame_counter);
      }
      cv::setMouseCallback("Original", mouseCallback, (void*) &pause);
    }

    ticker.reset();
    while (capture.read(frame)) {
      ticker.tick("ML_Frame_Capture");
      if (downsample_factor < 1.0 && downsample_factor > 0.0) {
        cv::resize(frame, frame, cv::Size(0, 0), downsample_factor, downsample_factor, cv::INTER_CUBIC);
        ticker.tick("ML_Downsampling");
      }
      LOG(INFO) << "Frame: " << frame_counter << " [" << frame.cols << " x " << frame.rows << "]";
      if (display && !use_webam && (frame_counter % 10 == 0)) cv::setTrackbarPos("Browse", "Original", frame_counter);
      cv::cvtColor(frame, frame_gray, cv::COLOR_BGR2GRAY);
      ticker.tick("ML_Frame_2_Gray");
      bool ct_success = camera_tracker.Update(frame_gray, frame);
      cv::Point2d center;
      double _w=0.0, _h=0.0, _f=-1.0;
      if (!ct_success) {
        LOG(WARNING) << "Camera Tracker Failed";
        // TODO
      } else {
        object_tracker.Update(camera_tracker.GetStablizedGray(), // TODO
                              camera_tracker.GetLatestDiff(),
                              camera_tracker.GetLatestSOF(),
                              camera_tracker.GetLatestCameraTransform());

        LOG(INFO) << "Tracking status: " << object_tracker.GetStatus();
        if (object_tracker.IsTracking()) {
          _f = object_tracker.GetObject().GetPeriodicity().GetDominantFrequency(1); // TODO
          LOG(INFO) << "Object: "
                    << object_tracker.GetObjectBoundingBox()
                    << " Periodicity:"
                    << _f;
          //LOG(INFO) << "Spectrum: " << cv::Mat(object_tracker.GetObject().GetPeriodicity().GetSpectrum(), false);
        }

//        if (object_tracker.GetStatus() != TRACKING_STATUS_TRACKING) {
//          if (!self_similariy.IsEmpty()) self_similariy.Reset();
//        } else {
//          self_similariy.Update(camera_tracker.GetStablized()(object_tracker.GetBoundingBox()).clone());
//          if (self_similariy.IsFull()) {
//            periodicity.Update(self_similariy.GetSimMatrix());
//            LOG(INFO) << "Dominant Frequency: " << periodicity.GetDominantFrequency();
//          }
//        }
//        center.x = sampler.Integrate(integrand_mean_x, NULL);
//        center.y = sampler.Integrate(integrand_mean_y, NULL);
//        _w = sqrt(sampler.Integrate(integrand_var_x, (void*) &(center.x)));
//        _h = sqrt(sampler.Integrate(integrand_var_y, (void*) &(center.y)));
//        LOG(INFO) << center << " : " << _w<< " - " <<  _h;
      }

      if (display) {
//        cv::Mat diff_frame = camera_tracker.GetLatestDiff();
        cv::Mat diff_frame;
        if (object_tracker.IsTracking()) {
          diff_frame = object_tracker.GetObject().GetSelfSimilarity().GetSimMatrixRendered();
          cv::imwrite("data/sim.bmp", diff_frame);
        }
        cv::Mat debug_frame = camera_tracker.GetStablizedGray();
        object_tracker.DrawParticles(debug_frame);
        if (camera_tracker.GetTrackedFeaturesCurr().size()) {
          drawFeaturePointsTrajectory(frame,
                                      camera_tracker.GetHomographyOutliers(),
                                      camera_tracker.GetTrackedFeaturesPrev(),
                                      camera_tracker.GetTrackedFeaturesCurr(),
                                      2,
                                      CV_RGB(127,127,127), CV_RGB(255, 0, 0), CV_RGB(255, 0, 0));
        }

        cv::rectangle(diff_frame, cv::Rect(center.x - _w/2, center.y-_h/2, _w, _h), CV_RGB(255, 255, 255));

        std::stringstream ss;
        ss << std::setprecision(5) << "Periodicity: " << _f;
        cv::putText(frame, ss.str(), cv::Point(40,40), 1, CV_FONT_HERSHEY_PLAIN, cv::Scalar(255, 0, 0));
        //cv::circle(diff_frame, center, 10, CV_RGB(255, 255, 255));
        if (frame.data) cv::imshow("Original", frame);
        if (diff_frame.data) cv::imshow("DiffStab", diff_frame);
        if (debug_frame.data) cv::imshow("Debug", debug_frame);
        cv::waitKey(10);
        ticker.tick("ML_Visualization");
      }
      ticker.dump(clear);
      while (display && pause) cv::waitKey(100);
      frame_counter++;
      ticker.reset();
    }
  } catch (const cv::Exception& ex) {
    LOG(ERROR) << "Exception: " << ex.what();
    if (capture.isOpened()) capture.release();
    ticker.dump();
    return 1;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include "tmfs.hh"

static std::string _get_real_path(const std::string & str)
{
  const auto clean_path = fs::path(str);

  fs::path real_path(tmfs::instance().hfs_root());
  real_path /= "Backups.backupdb"; // ${hfs_root}/Backups.backupdb/

  // ok let's copy the 4 first part of the virtual path
  // (/, ${comp_name}, ${date}, ${disk_name})
  auto it = clean_path.begin();
  for (int i = 0; i < 4 && it != clean_path.end(); ++i, ++it)
    real_path /= *it;

  // let's resolv all the parts of the path
  struct stat stbuf;
  for (; it != clean_path.end(); ++it)
  {
    real_path /= *it;
    // Does the file exists ?
    if (stat(real_path.string().c_str(), &stbuf))
      return real_path.string();

    // Is the file a dir_id ?
    if (S_ISREG(stbuf.st_mode) && stbuf.st_size == 0 && stbuf.st_nlink > 0)
    {
      // build the real path
      std::ostringstream os;
      os << tmfs::instance().hfs_root() << "/.HFS+ Private Directory Data\r/dir_" << stbuf.st_nlink;

      // check if it's really a ${dir_id}
      if (stat(os.str().c_str(), &stbuf))
        continue; // it's not
      real_path = os.str(); // it is
    }
  }
  return real_path.string();
}

std::string get_real_path(const std::string & str)
{
  auto result = _get_real_path(str);
  std::cout << "get_real_path(\"" << str << "\") -> "  << result << std::endl;
  return result;
}<commit_msg>Apply the fix suggested by cnagyxyz<commit_after>#include "tmfs.hh"

static std::string _get_real_path(const std::string & str)
{
  const auto clean_path = fs::path(str);

  fs::path real_path(tmfs::instance().hfs_root());
  real_path /= "Backups.backupdb"; // ${hfs_root}/Backups.backupdb/

  // ok let's copy the 4 first part of the virtual path
  // (/, ${comp_name}, ${date}, ${disk_name})
  auto it = clean_path.begin();
  for (int i = 1; i < 4 && it != clean_path.end(); ++i, ++it)
    real_path /= *it;

  // let's resolv all the parts of the path
  struct stat stbuf;
  for (; it != clean_path.end(); ++it)
  {
    real_path /= *it;
    // Does the file exists ?
    if (stat(real_path.string().c_str(), &stbuf))
      return real_path.string();

    // Is the file a dir_id ?
    if (S_ISREG(stbuf.st_mode) && stbuf.st_size == 0 && stbuf.st_nlink > 0)
    {
      // build the real path
      std::ostringstream os;
      os << tmfs::instance().hfs_root() << "/.HFS+ Private Directory Data\r/dir_" << stbuf.st_nlink;

      // check if it's really a ${dir_id}
      if (stat(os.str().c_str(), &stbuf))
        continue; // it's not
      real_path = os.str(); // it is
    }
  }
  return real_path.string();
}

std::string get_real_path(const std::string & str)
{
  auto result = _get_real_path(str);
  std::cout << "get_real_path(\"" << str << "\") -> "  << result << std::endl;
  return result;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Luke San Antonio
 * All rights reserved.
 */
#include "pipeline.h"
#include <algorithm>
#include "../common/log.h"
namespace survive
{
  namespace gfx
  {
    namespace
    {
      template <class T>
      void init_array_buffer(GLuint attrib,
                             std::vector<T> const& buf,
                             GLuint& buf_value,
                             GLint size, GLenum type,
                             bool normalized) noexcept
      {
        glGenBuffers(1, &buf_value);
        glBindBuffer(GL_ARRAY_BUFFER, buf_value);
        glBufferData(GL_ARRAY_BUFFER, buf.size() * sizeof(T),
                     &buf[0], GL_STATIC_DRAW);
        glVertexAttribPointer(attrib, size, type, normalized, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glEnableVertexAttribArray(attrib);
      }
    }

    /*!
     * Swallow a mesh for our own purposes.
     */
    Pipeline_Mesh* Pipeline::prepare_mesh(Mesh&& mesh) noexcept
    {
      // Make a "pipeline mesh" or rather something that will store some
      // useful things about the mesh for the purposes of rendering it with
      // opengl.
      auto pipemesh = Pipeline_Mesh{std::move(mesh)};

      // Initialize the vao and buffer and such.
      glGenVertexArrays(1, &pipemesh.vao);
      glBindVertexArray(pipemesh.vao);

      // Initialize the vertices.
      init_array_buffer(0, pipemesh.mesh.vertices, pipemesh.vertice_buffer,
                        3, GL_FLOAT, GL_FALSE);
      // Initialize normals.
      if(pipemesh.mesh.normals.size())
      {
        init_array_buffer(1, pipemesh.mesh.normals, pipemesh.normals_buffer,
                          3, GL_FLOAT, GL_TRUE);
      }
      // Initialize texture coordinates.
      if(pipemesh.mesh.tex_coords.size())
      {
        init_array_buffer(2, pipemesh.mesh.tex_coords,
                          pipemesh.tex_coords_buffer, 2, GL_FLOAT, GL_FALSE);
      }

      glGenBuffers(1, &pipemesh.face_index_buffer);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pipemesh.face_index_buffer);
      glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                   pipemesh.mesh.faces.size() * sizeof(GLuint),
                   &pipemesh.mesh.faces[0], GL_STATIC_DRAW);

      glBindVertexArray(0);

      // Move *that* into the vector.
      mesh_.push_back(std::move(pipemesh));

      // Now that we have a permanent spot for it. Give it to the client.
      return &mesh_.back();
    }
    Mesh Pipeline::remove_mesh(Pipeline_Mesh& mesh) noexcept
    {
      using std::begin; using std::end;
      auto new_end = std::remove_if(begin(mesh_), end(mesh_),
      [&mesh](auto& val)
      {
        // Check to see which element the pointer is pointing to.
        return &mesh == &val;
      });

      // First uninitialize the vao and buffers.
      uninit_pipeline_mesh_(mesh);

      // Capture that mesh!
      Mesh&& old_mesh_data = std::move(mesh.mesh);
      // Remove it from our vector.
      mesh_.erase(new_end, end(mesh_));

      // Move the original mesh out.
      return old_mesh_data;
    }
    void Pipeline::render_pipeline_mesh(Pipeline_Mesh* mesh) noexcept
    {
      glBindVertexArray(mesh->vao);
      glDrawElements(GL_TRIANGLES, mesh->mesh.faces.size() * 3,
                     GL_UNSIGNED_INT, 0);
      // Unbind vao?
      //glBindVertexArray(0);
    }
    // Uninitialize a mesh as far as opengl is concerned *unprepare it*.
    void Pipeline::uninit_pipeline_mesh_(Pipeline_Mesh& mesh) noexcept
    {
      glDeleteBuffers(1, &mesh.vertice_buffer);
      glDeleteBuffers(1, &mesh.normals_buffer);
      glDeleteBuffers(1, &mesh.tex_coords_buffer);
      glDeleteBuffers(1, &mesh.face_index_buffer);
      glDeleteVertexArrays(1, &mesh.vao);
    }
  }
}
<commit_msg>We now explicitely set all the ids in a Pipeline_Mesh to zero.<commit_after>/*
 * Copyright (C) 2014 Luke San Antonio
 * All rights reserved.
 */
#include "pipeline.h"
#include <algorithm>
#include "../common/log.h"
namespace survive
{
  namespace gfx
  {
    namespace
    {
      template <class T>
      void init_array_buffer(GLuint attrib,
                             std::vector<T> const& buf,
                             GLuint& buf_value,
                             GLint size, GLenum type,
                             bool normalized) noexcept
      {
        glGenBuffers(1, &buf_value);
        glBindBuffer(GL_ARRAY_BUFFER, buf_value);
        glBufferData(GL_ARRAY_BUFFER, buf.size() * sizeof(T),
                     &buf[0], GL_STATIC_DRAW);
        glVertexAttribPointer(attrib, size, type, normalized, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glEnableVertexAttribArray(attrib);
      }
    }

    /*!
     * Swallow a mesh for our own purposes.
     */
    Pipeline_Mesh* Pipeline::prepare_mesh(Mesh&& mesh) noexcept
    {
      // Make a "pipeline mesh" or rather something that will store some
      // useful things about the mesh for the purposes of rendering it with
      // opengl.
      auto pipemesh = Pipeline_Mesh{std::move(mesh), 0,0,0,0,0};

      // Initialize the vao and buffer and such.
      glGenVertexArrays(1, &pipemesh.vao);
      glBindVertexArray(pipemesh.vao);

      // Initialize the vertices.
      init_array_buffer(0, pipemesh.mesh.vertices, pipemesh.vertice_buffer,
                        3, GL_FLOAT, GL_FALSE);
      // Initialize normals.
      if(pipemesh.mesh.normals.size())
      {
        init_array_buffer(1, pipemesh.mesh.normals, pipemesh.normals_buffer,
                          3, GL_FLOAT, GL_TRUE);
      }
      // Initialize texture coordinates.
      if(pipemesh.mesh.tex_coords.size())
      {
        init_array_buffer(2, pipemesh.mesh.tex_coords,
                          pipemesh.tex_coords_buffer, 2, GL_FLOAT, GL_FALSE);
      }

      glGenBuffers(1, &pipemesh.face_index_buffer);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pipemesh.face_index_buffer);
      glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                   pipemesh.mesh.faces.size() * sizeof(GLuint),
                   &pipemesh.mesh.faces[0], GL_STATIC_DRAW);

      glBindVertexArray(0);

      // Move *that* into the vector.
      mesh_.push_back(std::move(pipemesh));

      // Now that we have a permanent spot for it. Give it to the client.
      return &mesh_.back();
    }
    Mesh Pipeline::remove_mesh(Pipeline_Mesh& mesh) noexcept
    {
      using std::begin; using std::end;
      auto new_end = std::remove_if(begin(mesh_), end(mesh_),
      [&mesh](auto& val)
      {
        // Check to see which element the pointer is pointing to.
        return &mesh == &val;
      });

      // First uninitialize the vao and buffers.
      uninit_pipeline_mesh_(mesh);

      // Capture that mesh!
      Mesh&& old_mesh_data = std::move(mesh.mesh);
      // Remove it from our vector.
      mesh_.erase(new_end, end(mesh_));

      // Move the original mesh out.
      return old_mesh_data;
    }
    void Pipeline::render_pipeline_mesh(Pipeline_Mesh* mesh) noexcept
    {
      glBindVertexArray(mesh->vao);
      glDrawElements(GL_TRIANGLES, mesh->mesh.faces.size() * 3,
                     GL_UNSIGNED_INT, 0);
      // Unbind vao?
      //glBindVertexArray(0);
    }
    // Uninitialize a mesh as far as opengl is concerned *unprepare it*.
    void Pipeline::uninit_pipeline_mesh_(Pipeline_Mesh& mesh) noexcept
    {
      glDeleteBuffers(1, &mesh.vertice_buffer);
      glDeleteBuffers(1, &mesh.normals_buffer);
      glDeleteBuffers(1, &mesh.tex_coords_buffer);
      glDeleteBuffers(1, &mesh.face_index_buffer);
      glDeleteVertexArrays(1, &mesh.vao);
    }
  }
}
<|endoftext|>


<commit_before>#include "ajp/ajp_client.hxx"
#include "strmap.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_response.hxx"
#include "async.hxx"
#include "lease.hxx"
#include "direct.hxx"
#include "istream/istream_file.hxx"
#include "istream/istream_pipe.hxx"
#include "istream/istream.hxx"
#include "istream/sink_fd.hxx"
#include "direct.hxx"
#include "tpool.hxx"
#include "RootPool.hxx"
#include "fb_pool.hxx"
#include "ssl/ssl_init.hxx"
#include "ssl/ssl_client.hxx"
#include "system/SetupProcess.hxx"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "event/Event.hxx"
#include "event/ShutdownListener.hxx"

#include <inline/compiler.h>
#include <socket/resolver.h>
#include <socket/util.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>

struct parsed_url {
    enum {
        HTTP, HTTPS, AJP,
    } protocol;

    char *host;

    int default_port;

    const char *uri;
};

static bool
parse_url(struct parsed_url *dest, const char *url)
{
    assert(dest != nullptr);
    assert(url != nullptr);

    if (memcmp(url, "ajp://", 6) == 0) {
        url += 6;
        dest->protocol = parsed_url::AJP;
        dest->default_port = 8009;
    } else if (memcmp(url, "http://", 7) == 0) {
        url += 7;
        dest->protocol = parsed_url::HTTP;
        dest->default_port = 80;
    } else if (memcmp(url, "https://", 8) == 0) {
        url += 8;
        dest->protocol = parsed_url::HTTPS;
        dest->default_port = 443;
    } else
        return false;

    dest->uri = strchr(url, '/');
    if (dest->uri == nullptr || dest->uri == url)
        return false;

    dest->host = g_strndup(url, dest->uri - url);
    return true;
}

struct Context final : ConnectSocketHandler, Lease {
    struct pool *pool;

    struct parsed_url url;

    ShutdownListener shutdown_listener;

    struct async_operation_ref async_ref;

    http_method_t method;
    Istream *request_body;

    SocketDescriptor fd;
    bool idle, reuse, aborted;
    http_status_t status;

    SinkFd *body;
    bool body_eof, body_abort, body_closed;

    Context()
        :shutdown_listener(ShutdownCallback, this) {}

    static void ShutdownCallback(void *ctx);

    /* virtual methods from class ConnectSocketHandler */
    void OnSocketConnectSuccess(SocketDescriptor &&fd) override;
    void OnSocketConnectError(GError *error) override;

    /* virtual methods from class Lease */
    void ReleaseLease(bool _reuse) override {
        assert(!idle);
        assert(fd.IsDefined());

        idle = true;
        reuse = _reuse;

        fd.Close();
    }
};

void
Context::ShutdownCallback(void *ctx)
{
    auto *c = (Context *)ctx;

    if (c->body != nullptr) {
        sink_fd_close(c->body);
        c->body = nullptr;
        c->body_abort = true;
    } else {
        c->aborted = true;
        c->async_ref.Abort();
    }
}

/*
 * istream handler
 *
 */

static void
my_sink_fd_input_eof(void *ctx)
{
    auto *c = (Context *)ctx;

    c->body = nullptr;
    c->body_eof = true;

    c->shutdown_listener.Disable();
}

static void
my_sink_fd_input_error(GError *error, void *ctx)
{
    auto *c = (Context *)ctx;

    g_printerr("%s\n", error->message);
    g_error_free(error);

    c->body = nullptr;
    c->body_abort = true;

    c->shutdown_listener.Disable();
}

static bool
my_sink_fd_send_error(int error, void *ctx)
{
    auto *c = (Context *)ctx;

    g_printerr("%s\n", g_strerror(error));

    c->body = nullptr;
    c->body_abort = true;

    c->shutdown_listener.Disable();
    return true;
}

static constexpr SinkFdHandler my_sink_fd_handler = {
    .input_eof = my_sink_fd_input_eof,
    .input_error = my_sink_fd_input_error,
    .send_error = my_sink_fd_send_error,
};

/*
 * http_response_handler
 *
 */

static void
my_response(http_status_t status, struct strmap *headers gcc_unused,
            Istream *body,
            void *ctx)
{
    auto *c = (Context *)ctx;

    c->status = status;

    if (body != nullptr) {
        body = istream_pipe_new(c->pool, *body, nullptr);
        c->body = sink_fd_new(*c->pool, *body, 1, guess_fd_type(1),
                              my_sink_fd_handler, c);
        body->Read();
    } else {
        c->body_eof = true;
        c->shutdown_listener.Disable();
    }
}

static void
my_response_abort(GError *error, void *ctx)
{
    auto *c = (Context *)ctx;

    g_printerr("%s\n", error->message);
    g_error_free(error);

    c->aborted = true;

    c->shutdown_listener.Disable();
}

static const struct http_response_handler my_response_handler = {
    .response = my_response,
    .abort = my_response_abort,
};

/*
 * client_socket_handler
 *
 */

void
Context::OnSocketConnectSuccess(SocketDescriptor &&new_fd)
{
    fd = std::move(new_fd);

    struct strmap *headers = strmap_new(pool);
    headers->Add("host", url.host);

    switch (url.protocol) {
    case parsed_url::AJP:
        ajp_client_request(pool, fd.Get(), FdType::FD_TCP,
                           *this,
                           "http", "127.0.0.1", "localhost",
                           "localhost", 80, false,
                           method, url.uri, headers, request_body,
                           &my_response_handler, this,
                           &async_ref);
        break;

    case parsed_url::HTTP:
        http_client_request(*pool, fd.Get(), FdType::FD_TCP,
                            *this,
                            "localhost",
                            nullptr, nullptr,
                            method, url.uri,
                            HttpHeaders(*headers),
                            request_body, false,
                            my_response_handler, this,
                            async_ref);
        break;

    case parsed_url::HTTPS: {
        GError *error = nullptr;
        void *filter_ctx = ssl_client_create(pool,
                                             url.host,
                                             &error);
        if (filter_ctx == nullptr) {
            g_printerr("%s\n", error->message);
            g_error_free(error);

            aborted = true;

            if (request_body != nullptr)
                request_body->CloseUnused();

            shutdown_listener.Disable();
            return;
        }

        auto filter = &ssl_client_get_filter();
        http_client_request(*pool, fd.Get(), FdType::FD_TCP,
                            *this,
                            "localhost",
                            filter, filter_ctx,
                            method, url.uri,
                            HttpHeaders(*headers),
                            request_body, false,
                            my_response_handler, this,
                            async_ref);
        break;
    }
    }
}

void
Context::OnSocketConnectError(GError *error)
{
    g_printerr("%s\n", error->message);
    g_error_free(error);

    aborted = true;

    if (request_body != nullptr)
        request_body->CloseUnused();

    shutdown_listener.Disable();
}

/*
 * main
 *
 */

int
main(int argc, char **argv)
{
    Context ctx;

    if (argc < 2 || argc > 3) {
        fprintf(stderr, "usage: run-ajp-client URL [BODY]\n");
        return EXIT_FAILURE;
    }

    if (!parse_url(&ctx.url, argv[1])) {
        fprintf(stderr, "Invalid or unsupported URL.\n");
        return EXIT_FAILURE;
    }

    const ScopeSslGlobalInit ssl_init;
    ssl_client_init();

    direct_global_init();

    /* connect socket */

    struct addrinfo hints, *ai;
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;

    int ret = socket_resolve_host_port(ctx.url.host, ctx.url.default_port,
                                       &hints, &ai);
    if (ret != 0) {
        fprintf(stderr, "Failed to resolve host name\n");
        return EXIT_FAILURE;
    }

    /* initialize */

    SetupProcess();

    EventBase event_base;
    fb_pool_init(false);

    ctx.shutdown_listener.Enable();

    RootPool root_pool;

    struct pool *pool = pool_new_linear(root_pool, "test", 8192);
    ctx.pool = pool;

    /* open request body */

    if (argc >= 3) {
        struct stat st;

        ret = stat(argv[2], &st);
        if (ret < 0) {
            fprintf(stderr, "Failed to stat %s: %s\n",
                    argv[2], strerror(errno));
            return EXIT_FAILURE;
        }

        ctx.method = HTTP_METHOD_POST;

        GError *error = nullptr;
        ctx.request_body = istream_file_new(pool, argv[2], st.st_size, &error);
        if (ctx.request_body == nullptr) {
            fprintf(stderr, "%s\n", error->message);
            g_error_free(error);
            return EXIT_FAILURE;
        }
    } else {
        ctx.method = HTTP_METHOD_GET;
        ctx.request_body = nullptr;
    }

    /* connect */

    client_socket_new(*pool,
                      ai->ai_family, ai->ai_socktype, ai->ai_protocol,
                      false,
                      SocketAddress::Null(),
                      SocketAddress(ai->ai_addr, ai->ai_addrlen),
                      30,
                      ctx, ctx.async_ref);
    freeaddrinfo(ai);

    /* run test */

    event_base.Dispatch();

    assert(ctx.body_eof || ctx.body_abort || ctx.aborted);

    fprintf(stderr, "reuse=%d\n", ctx.reuse);

    /* cleanup */

    pool_unref(pool);
    pool_commit();

    fb_pool_deinit();

    ssl_client_deinit();

    g_free(ctx.url.host);

    return ctx.body_eof ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>test/run_client: update usage message<commit_after>#include "ajp/ajp_client.hxx"
#include "strmap.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_response.hxx"
#include "async.hxx"
#include "lease.hxx"
#include "direct.hxx"
#include "istream/istream_file.hxx"
#include "istream/istream_pipe.hxx"
#include "istream/istream.hxx"
#include "istream/sink_fd.hxx"
#include "direct.hxx"
#include "tpool.hxx"
#include "RootPool.hxx"
#include "fb_pool.hxx"
#include "ssl/ssl_init.hxx"
#include "ssl/ssl_client.hxx"
#include "system/SetupProcess.hxx"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "event/Event.hxx"
#include "event/ShutdownListener.hxx"

#include <inline/compiler.h>
#include <socket/resolver.h>
#include <socket/util.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>

struct parsed_url {
    enum {
        HTTP, HTTPS, AJP,
    } protocol;

    char *host;

    int default_port;

    const char *uri;
};

static bool
parse_url(struct parsed_url *dest, const char *url)
{
    assert(dest != nullptr);
    assert(url != nullptr);

    if (memcmp(url, "ajp://", 6) == 0) {
        url += 6;
        dest->protocol = parsed_url::AJP;
        dest->default_port = 8009;
    } else if (memcmp(url, "http://", 7) == 0) {
        url += 7;
        dest->protocol = parsed_url::HTTP;
        dest->default_port = 80;
    } else if (memcmp(url, "https://", 8) == 0) {
        url += 8;
        dest->protocol = parsed_url::HTTPS;
        dest->default_port = 443;
    } else
        return false;

    dest->uri = strchr(url, '/');
    if (dest->uri == nullptr || dest->uri == url)
        return false;

    dest->host = g_strndup(url, dest->uri - url);
    return true;
}

struct Context final : ConnectSocketHandler, Lease {
    struct pool *pool;

    struct parsed_url url;

    ShutdownListener shutdown_listener;

    struct async_operation_ref async_ref;

    http_method_t method;
    Istream *request_body;

    SocketDescriptor fd;
    bool idle, reuse, aborted;
    http_status_t status;

    SinkFd *body;
    bool body_eof, body_abort, body_closed;

    Context()
        :shutdown_listener(ShutdownCallback, this) {}

    static void ShutdownCallback(void *ctx);

    /* virtual methods from class ConnectSocketHandler */
    void OnSocketConnectSuccess(SocketDescriptor &&fd) override;
    void OnSocketConnectError(GError *error) override;

    /* virtual methods from class Lease */
    void ReleaseLease(bool _reuse) override {
        assert(!idle);
        assert(fd.IsDefined());

        idle = true;
        reuse = _reuse;

        fd.Close();
    }
};

void
Context::ShutdownCallback(void *ctx)
{
    auto *c = (Context *)ctx;

    if (c->body != nullptr) {
        sink_fd_close(c->body);
        c->body = nullptr;
        c->body_abort = true;
    } else {
        c->aborted = true;
        c->async_ref.Abort();
    }
}

/*
 * istream handler
 *
 */

static void
my_sink_fd_input_eof(void *ctx)
{
    auto *c = (Context *)ctx;

    c->body = nullptr;
    c->body_eof = true;

    c->shutdown_listener.Disable();
}

static void
my_sink_fd_input_error(GError *error, void *ctx)
{
    auto *c = (Context *)ctx;

    g_printerr("%s\n", error->message);
    g_error_free(error);

    c->body = nullptr;
    c->body_abort = true;

    c->shutdown_listener.Disable();
}

static bool
my_sink_fd_send_error(int error, void *ctx)
{
    auto *c = (Context *)ctx;

    g_printerr("%s\n", g_strerror(error));

    c->body = nullptr;
    c->body_abort = true;

    c->shutdown_listener.Disable();
    return true;
}

static constexpr SinkFdHandler my_sink_fd_handler = {
    .input_eof = my_sink_fd_input_eof,
    .input_error = my_sink_fd_input_error,
    .send_error = my_sink_fd_send_error,
};

/*
 * http_response_handler
 *
 */

static void
my_response(http_status_t status, struct strmap *headers gcc_unused,
            Istream *body,
            void *ctx)
{
    auto *c = (Context *)ctx;

    c->status = status;

    if (body != nullptr) {
        body = istream_pipe_new(c->pool, *body, nullptr);
        c->body = sink_fd_new(*c->pool, *body, 1, guess_fd_type(1),
                              my_sink_fd_handler, c);
        body->Read();
    } else {
        c->body_eof = true;
        c->shutdown_listener.Disable();
    }
}

static void
my_response_abort(GError *error, void *ctx)
{
    auto *c = (Context *)ctx;

    g_printerr("%s\n", error->message);
    g_error_free(error);

    c->aborted = true;

    c->shutdown_listener.Disable();
}

static const struct http_response_handler my_response_handler = {
    .response = my_response,
    .abort = my_response_abort,
};

/*
 * client_socket_handler
 *
 */

void
Context::OnSocketConnectSuccess(SocketDescriptor &&new_fd)
{
    fd = std::move(new_fd);

    struct strmap *headers = strmap_new(pool);
    headers->Add("host", url.host);

    switch (url.protocol) {
    case parsed_url::AJP:
        ajp_client_request(pool, fd.Get(), FdType::FD_TCP,
                           *this,
                           "http", "127.0.0.1", "localhost",
                           "localhost", 80, false,
                           method, url.uri, headers, request_body,
                           &my_response_handler, this,
                           &async_ref);
        break;

    case parsed_url::HTTP:
        http_client_request(*pool, fd.Get(), FdType::FD_TCP,
                            *this,
                            "localhost",
                            nullptr, nullptr,
                            method, url.uri,
                            HttpHeaders(*headers),
                            request_body, false,
                            my_response_handler, this,
                            async_ref);
        break;

    case parsed_url::HTTPS: {
        GError *error = nullptr;
        void *filter_ctx = ssl_client_create(pool,
                                             url.host,
                                             &error);
        if (filter_ctx == nullptr) {
            g_printerr("%s\n", error->message);
            g_error_free(error);

            aborted = true;

            if (request_body != nullptr)
                request_body->CloseUnused();

            shutdown_listener.Disable();
            return;
        }

        auto filter = &ssl_client_get_filter();
        http_client_request(*pool, fd.Get(), FdType::FD_TCP,
                            *this,
                            "localhost",
                            filter, filter_ctx,
                            method, url.uri,
                            HttpHeaders(*headers),
                            request_body, false,
                            my_response_handler, this,
                            async_ref);
        break;
    }
    }
}

void
Context::OnSocketConnectError(GError *error)
{
    g_printerr("%s\n", error->message);
    g_error_free(error);

    aborted = true;

    if (request_body != nullptr)
        request_body->CloseUnused();

    shutdown_listener.Disable();
}

/*
 * main
 *
 */

int
main(int argc, char **argv)
{
    Context ctx;

    if (argc < 2 || argc > 3) {
        fprintf(stderr, "usage: run_client URL [BODY]\n");
        return EXIT_FAILURE;
    }

    if (!parse_url(&ctx.url, argv[1])) {
        fprintf(stderr, "Invalid or unsupported URL.\n");
        return EXIT_FAILURE;
    }

    const ScopeSslGlobalInit ssl_init;
    ssl_client_init();

    direct_global_init();

    /* connect socket */

    struct addrinfo hints, *ai;
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;

    int ret = socket_resolve_host_port(ctx.url.host, ctx.url.default_port,
                                       &hints, &ai);
    if (ret != 0) {
        fprintf(stderr, "Failed to resolve host name\n");
        return EXIT_FAILURE;
    }

    /* initialize */

    SetupProcess();

    EventBase event_base;
    fb_pool_init(false);

    ctx.shutdown_listener.Enable();

    RootPool root_pool;

    struct pool *pool = pool_new_linear(root_pool, "test", 8192);
    ctx.pool = pool;

    /* open request body */

    if (argc >= 3) {
        struct stat st;

        ret = stat(argv[2], &st);
        if (ret < 0) {
            fprintf(stderr, "Failed to stat %s: %s\n",
                    argv[2], strerror(errno));
            return EXIT_FAILURE;
        }

        ctx.method = HTTP_METHOD_POST;

        GError *error = nullptr;
        ctx.request_body = istream_file_new(pool, argv[2], st.st_size, &error);
        if (ctx.request_body == nullptr) {
            fprintf(stderr, "%s\n", error->message);
            g_error_free(error);
            return EXIT_FAILURE;
        }
    } else {
        ctx.method = HTTP_METHOD_GET;
        ctx.request_body = nullptr;
    }

    /* connect */

    client_socket_new(*pool,
                      ai->ai_family, ai->ai_socktype, ai->ai_protocol,
                      false,
                      SocketAddress::Null(),
                      SocketAddress(ai->ai_addr, ai->ai_addrlen),
                      30,
                      ctx, ctx.async_ref);
    freeaddrinfo(ai);

    /* run test */

    event_base.Dispatch();

    assert(ctx.body_eof || ctx.body_abort || ctx.aborted);

    fprintf(stderr, "reuse=%d\n", ctx.reuse);

    /* cleanup */

    pool_unref(pool);
    pool_commit();

    fb_pool_deinit();

    ssl_client_deinit();

    g_free(ctx.url.host);

    return ctx.body_eof ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>// ================================================================================
// == This file is a part of Tinkerbell UI Toolkit. (C) 2011-2012, Emil Segers ==
// ==                   See tinkerbell.h for more information.                   ==
// ================================================================================

#include "tb_message_window.h"
#include "tb_widgets_reader.h"
#include "tb_editfield.h"
#include "tb_language.h"
#include <assert.h>

namespace tinkerbell {

// == TBMessageWindow =======================================================================================

TBMessageWindow::TBMessageWindow(TBWidget *target, TBID id)
	: TBWidgetSafePointer(target)
{
	m_id.Set(id);
}

TBMessageWindow::~TBMessageWindow()
{
	if (TBWidget *dimmer = m_dimmer.Get())
	{
		dimmer->m_parent->RemoveChild(dimmer);
		delete dimmer;
	}
}

bool TBMessageWindow::Show(const char *title, const char *message, TBMessageWindowSettings *settings)
{
	TBWidget *target = Get();
	if (!target)
		return false;

	TBMessageWindowSettings default_settings;
	if (!settings)
		settings = &default_settings;

	TBWidget *root = target->GetParentRoot();

	const char *source =	"TBLayout: axis: y, distribution: available\n"
							"	TBLayout: distribution: available, size: available\n"
							"		TBSkinImage: id: 2\n"
							"		TBEditField: multiline: 1, readonly: 1, id: 1\n"
							"	TBLayout: distribution_position: right bottom, id: 3\n";
	g_widgets_reader->LoadData(GetContentRoot(), source);

	SetText(title);

	TBSafeGetByID(TBSkinImage, 2)->SetSkinBg(settings->icon_skin);

	TBEditField *editfield = TBSafeGetByID(TBEditField, 1);
	editfield->SetText(message);
	editfield->SetSkinBg("");

	// Create buttons
	if (settings->msg == TB_MSG_OK)
	{
		AddButton("TBMessageWindow.ok", true);
	}
	else if (settings->msg == TB_MSG_OK_CANCEL)
	{
		AddButton("TBMessageWindow.ok", true);
		AddButton("TBMessageWindow.cancel", false);
	}
	else if (settings->msg == TB_MSG_YES_NO)
	{
		AddButton("TBMessageWindow.yes", true);
		AddButton("TBMessageWindow.no", false);
	}

	// Size to fit content. This will use the default size of the textfield.
	ResizeToFitContent();

	// Get how much we overflow the textfield has given the current width, and grow our height to show all we can.
	int new_height = m_rect.h + editfield->GetStyleEdit()->GetOverflowY();
	new_height = MIN(new_height, root->m_rect.h - 50); // 50px for some window title and padding

	// Create background dimmer
	if (settings->dimmer)
	{
		if (TBDimmer *dimmer = new TBDimmer)
		{
			root->AddChild(dimmer);
			m_dimmer.Set(dimmer);
		}
	}

	// Center and size to the new height
	SetRect(TBRect((root->m_rect.w - m_rect.w) / 2,
					(root->m_rect.h - new_height) / 2,
					m_rect.w, new_height));
	root->AddChild(this);
	return true;
}

void TBMessageWindow::AddButton(TBID id, bool focused)
{
	TBLayout *layout = TBSafeGetByID(TBLayout, 3);
	if (!layout)
		return;
	if (TBButton *btn = new TBButton)
	{
		btn->GetID().Set(id);
		btn->SetText(g_tb_lng->GetString(btn->GetID()));
		layout->AddChild(btn);
		if (focused)
			btn->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
	}
}

bool TBMessageWindow::OnEvent(const TBWidgetEvent &ev)
{
	if (ev.type == EVENT_TYPE_CLICK && ev.target->IsOfType("TBButton"))
	{
		TBWidgetSafePointer this_widget(this);

		// Invoke the click on the target
		TBWidgetEvent target_ev(EVENT_TYPE_CLICK);
		target_ev.ref_id = ev.target->m_id;
		InvokeEvent(target_ev);

		// If target got deleted, close
		if (this_widget.Get())
			Close();
		return true;
	}
	return TBWindow::OnEvent(ev);
}

void TBMessageWindow::OnDie()
{
	if (TBWidget *dimmer = m_dimmer.Get())
		dimmer->Die();
}

void TBMessageWindow::OnWidgetDelete(TBWidget *widget)
{
	TBWidgetSafePointer::OnWidgetDelete(widget);
	// If the target widget is deleted, close!
	if (!Get())
		Close();
}

}; // namespace tinkerbell
<commit_msg>Cancel message windows on key TB_KEY_ESC.<commit_after>// ================================================================================
// == This file is a part of Tinkerbell UI Toolkit. (C) 2011-2012, Emil Segers ==
// ==                   See tinkerbell.h for more information.                   ==
// ================================================================================

#include "tb_message_window.h"
#include "tb_widgets_reader.h"
#include "tb_editfield.h"
#include "tb_language.h"
#include <assert.h>

namespace tinkerbell {

// == TBMessageWindow =======================================================================================

TBMessageWindow::TBMessageWindow(TBWidget *target, TBID id)
	: TBWidgetSafePointer(target)
{
	m_id.Set(id);
}

TBMessageWindow::~TBMessageWindow()
{
	if (TBWidget *dimmer = m_dimmer.Get())
	{
		dimmer->m_parent->RemoveChild(dimmer);
		delete dimmer;
	}
}

bool TBMessageWindow::Show(const char *title, const char *message, TBMessageWindowSettings *settings)
{
	TBWidget *target = Get();
	if (!target)
		return false;

	TBMessageWindowSettings default_settings;
	if (!settings)
		settings = &default_settings;

	TBWidget *root = target->GetParentRoot();

	const char *source =	"TBLayout: axis: y, distribution: available\n"
							"	TBLayout: distribution: available, size: available\n"
							"		TBSkinImage: id: 2\n"
							"		TBEditField: multiline: 1, readonly: 1, id: 1\n"
							"	TBLayout: distribution_position: right bottom, id: 3\n";
	g_widgets_reader->LoadData(GetContentRoot(), source);

	SetText(title);

	TBSafeGetByID(TBSkinImage, 2)->SetSkinBg(settings->icon_skin);

	TBEditField *editfield = TBSafeGetByID(TBEditField, 1);
	editfield->SetText(message);
	editfield->SetSkinBg("");

	// Create buttons
	if (settings->msg == TB_MSG_OK)
	{
		AddButton("TBMessageWindow.ok", true);
	}
	else if (settings->msg == TB_MSG_OK_CANCEL)
	{
		AddButton("TBMessageWindow.ok", true);
		AddButton("TBMessageWindow.cancel", false);
	}
	else if (settings->msg == TB_MSG_YES_NO)
	{
		AddButton("TBMessageWindow.yes", true);
		AddButton("TBMessageWindow.no", false);
	}

	// Size to fit content. This will use the default size of the textfield.
	ResizeToFitContent();

	// Get how much we overflow the textfield has given the current width, and grow our height to show all we can.
	int new_height = m_rect.h + editfield->GetStyleEdit()->GetOverflowY();
	new_height = MIN(new_height, root->m_rect.h - 50); // 50px for some window title and padding

	// Create background dimmer
	if (settings->dimmer)
	{
		if (TBDimmer *dimmer = new TBDimmer)
		{
			root->AddChild(dimmer);
			m_dimmer.Set(dimmer);
		}
	}

	// Center and size to the new height
	SetRect(TBRect((root->m_rect.w - m_rect.w) / 2,
					(root->m_rect.h - new_height) / 2,
					m_rect.w, new_height));
	root->AddChild(this);
	return true;
}

void TBMessageWindow::AddButton(TBID id, bool focused)
{
	TBLayout *layout = TBSafeGetByID(TBLayout, 3);
	if (!layout)
		return;
	if (TBButton *btn = new TBButton)
	{
		btn->GetID().Set(id);
		btn->SetText(g_tb_lng->GetString(btn->GetID()));
		layout->AddChild(btn);
		if (focused)
			btn->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
	}
}

bool TBMessageWindow::OnEvent(const TBWidgetEvent &ev)
{
	if (ev.type == EVENT_TYPE_CLICK && ev.target->IsOfType("TBButton"))
	{
		TBWidgetSafePointer this_widget(this);

		// Invoke the click on the target
		TBWidgetEvent target_ev(EVENT_TYPE_CLICK);
		target_ev.ref_id = ev.target->m_id;
		InvokeEvent(target_ev);

		// If target got deleted, close
		if (this_widget.Get())
			Close();
		return true;
	}
	else if (ev.type == EVENT_TYPE_KEY_DOWN && ev.special_key == TB_KEY_ESC)
	{
		m_close_button.InvokeEvent(TBWidgetEvent(EVENT_TYPE_CLICK));
		return true;
	}
	return TBWindow::OnEvent(ev);
}

void TBMessageWindow::OnDie()
{
	if (TBWidget *dimmer = m_dimmer.Get())
		dimmer->Die();
}

void TBMessageWindow::OnWidgetDelete(TBWidget *widget)
{
	TBWidgetSafePointer::OnWidgetDelete(widget);
	// If the target widget is deleted, close!
	if (!Get())
		Close();
}

}; // namespace tinkerbell
<|endoftext|>


<commit_before>auto count=42;
std::string sum;
for(auto i=0; i<count; ++i)
{
  std::string xyz = "some value";
  xyz += "; counter is @ ";
  xyz += std::to_string(i);
  sum += xyz;
}

std::cout << sum << std::endl;
<commit_msg>added comments to the example code<commit_after>auto count=42;                      /* initial value */
std::string sum;
for(auto i=0; i<count; ++i)         // loop
{
  std::string xyz = "some value";
  xyz += "; counter is @ ";
  xyz += std::to_string(i);
  sum += xyz;
}

std::cout << sum << std::endl;      // output sum
<|endoftext|>


<commit_before>#include <catch/catch.hpp>
#include <cmath>
#include <limits>
#include <RaPsCallion/serializer.h>

namespace rapscallion {
namespace test {

void test(const std::string& inStr, const double in, const std::ptrdiff_t expected_size = -1) {
  GIVEN("the real number " + inStr) {
    WHEN("we serialize it") {
      Serializer s;
      serializer<decltype(+in)>::write(s, in);
      Deserializer d(s);

      THEN("the output meets size expectations") {
        const auto size = d.end - d.ptr;
        if (expected_size >= 0)
          CHECK(size == expected_size);

        // largest encoding of IEEE754 binary64 float:
        //  (11 exponent bits + exponent sign + NaN/inf flag) = 13 bits / 7 bit/byte = 2 byte
        //  (52 bit fraction + sign) = 53 bits / 7 bit/byte = 8 byte
        // + = 10 byte
        CHECK(size <= 10);

        AND_WHEN("we deserialize it again") {
          const auto out = serializer<decltype(+in)>::read(d);
          THEN("the deserialized output is equal to the original input") {
            if (std::isnan(in))
              CHECK(std::isnan(out));
            else
              CHECK(out == in);
          }
        }
      }
    }
  }
}

}
}

SCENARIO("Serializing floating point numbers", "[serialization]") {
  using namespace rapscallion::test;

#define STRIFY1ST(num, ...) #num
#define TEST(...) \
  test(STRIFY1ST(__VA_ARGS__, void), __VA_ARGS__)

  // Smallest encodings, only requiring flags
  TEST(std::numeric_limits<double>::infinity(), 1);
  TEST(-std::numeric_limits<double>::infinity(), 1);
  TEST(std::numeric_limits<double>::quiet_NaN(), 1);
  TEST(0.0, 1);
  TEST(-0.0, 1);

  TEST(0.03125, 2);
  TEST(-0.03125, 2);
  TEST(0.0625, 2);
  TEST(-0.0625, 2);
  TEST(0.125, 2);
  TEST(-0.125, 2);
  TEST(0.25, 2);
  TEST(-0.25, 2);
  TEST(0.5, 2);
  TEST(-0.5, 2);
  TEST(1.0, 2);
  TEST(-1.0, 2);
  TEST(2.0, 2);
  TEST(-2.0, 2);
  TEST(M_PI, 9);
  TEST(-M_PI, 9);
  TEST((float)M_PI, 5);
  TEST(-(float)M_PI, 5);
  TEST(std::numeric_limits<double>::epsilon());
  TEST(std::numeric_limits<double>::min());
  TEST(std::numeric_limits<double>::max(), 10);
  TEST(std::numeric_limits<double>::denorm_min());

#undef STRIFY
#undef TEST
}
<commit_msg>Serializer: test that float's sign doesn't change<commit_after>#include <catch/catch.hpp>
#include <cmath>
#include <limits>
#include <RaPsCallion/serializer.h>

namespace rapscallion {
namespace test {

void test(const std::string& inStr, const double in, const std::ptrdiff_t expected_size = -1) {
  GIVEN("the real number " + inStr) {
    WHEN("we serialize it") {
      Serializer s;
      serializer<decltype(+in)>::write(s, in);
      Deserializer d(s);

      THEN("the output meets size expectations") {
        const auto size = d.end - d.ptr;
        if (expected_size >= 0)
          CHECK(size == expected_size);

        // largest encoding of IEEE754 binary64 float:
        //  (11 exponent bits + exponent sign + NaN/inf flag) = 13 bits / 7 bit/byte = 2 byte
        //  (52 bit fraction + sign) = 53 bits / 7 bit/byte = 8 byte
        // + = 10 byte
        CHECK(size <= 10);

        AND_WHEN("we deserialize it again") {
          const auto out = serializer<decltype(+in)>::read(d);
          THEN("the deserialized output is equal to the original input") {
            if (std::isnan(in)) {
              CHECK(std::isnan(out));
            } else {
              CHECK(out == in);
              CHECK(std::signbit(out) == std::signbit(in));
            }
          }
        }
      }
    }
  }
}

}
}

SCENARIO("Serializing floating point numbers", "[serialization]") {
  using namespace rapscallion::test;

#define STRIFY1ST(num, ...) #num
#define TEST(...) \
  test(STRIFY1ST(__VA_ARGS__, void), __VA_ARGS__)

  // Smallest encodings, only requiring flags
  TEST(std::numeric_limits<double>::infinity(), 1);
  TEST(-std::numeric_limits<double>::infinity(), 1);
  TEST(std::numeric_limits<double>::quiet_NaN(), 1);
  TEST(0.0, 1);
  TEST(-0.0, 1);

  TEST(0.03125, 2);
  TEST(-0.03125, 2);
  TEST(0.0625, 2);
  TEST(-0.0625, 2);
  TEST(0.125, 2);
  TEST(-0.125, 2);
  TEST(0.25, 2);
  TEST(-0.25, 2);
  TEST(0.5, 2);
  TEST(-0.5, 2);
  TEST(1.0, 2);
  TEST(-1.0, 2);
  TEST(2.0, 2);
  TEST(-2.0, 2);
  TEST(M_PI, 9);
  TEST(-M_PI, 9);
  TEST((float)M_PI, 5);
  TEST(-(float)M_PI, 5);
  TEST(std::numeric_limits<double>::epsilon());
  TEST(std::numeric_limits<double>::min());
  TEST(std::numeric_limits<double>::max(), 10);
  TEST(std::numeric_limits<double>::denorm_min());

#undef STRIFY
#undef TEST
}
<|endoftext|>


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

#include <libaddressinput/address_data.h>

#include <libaddressinput/address_field.h>
#include <libaddressinput/util/basictypes.h>

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <string>
#include <vector>

#include <re2/re2.h>

namespace i18n {
namespace addressinput {

namespace {

// Mapping from AddressField value to pointer to AddressData member.
std::string AddressData::*kStringField[] = {
  &AddressData::region_code,
  &AddressData::administrative_area,
  &AddressData::locality,
  &AddressData::dependent_locality,
  &AddressData::sorting_code,
  &AddressData::postal_code,
  NULL,
  &AddressData::recipient
};

// Mapping from AddressField value to pointer to AddressData member.
const std::vector<std::string> AddressData::*kVectorStringField[] = {
  NULL,
  NULL,
  NULL,
  NULL,
  NULL,
  NULL,
  &AddressData::address_line,
  NULL
};

COMPILE_ASSERT(arraysize(kStringField) == arraysize(kVectorStringField),
               field_mapping_array_size_mismatch);

// A string is considered to be "empty" not only if it actually is empty, but
// also if it contains nothing but whitespace.
bool IsStringEmpty(const std::string& str) {
  static const RE2 kMatcher("\\S");
  return str.empty() || !RE2::PartialMatch(str, kMatcher);
}

}  // namespace

bool AddressData::IsFieldEmpty(AddressField field) const {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kStringField));
  if (kStringField[field] != NULL) {
    const std::string& value = GetFieldValue(field);
    return IsStringEmpty(value);
  } else {
    const std::vector<std::string>& value = GetRepeatedFieldValue(field);
    return std::find_if(value.begin(), value.end(),
                        std::not1(std::ptr_fun(&IsStringEmpty))) ==
           value.end();
  }
}

const std::string& AddressData::GetFieldValue(
    AddressField field) const {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kStringField));
  assert(kStringField[field] != NULL);
  return this->*kStringField[field];
}

void AddressData::SetFieldValue(AddressField field, const std::string& value) {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kStringField));
  assert(kStringField[field] != NULL);
  (this->*kStringField[field]).assign(value);
}

const std::vector<std::string>& AddressData::GetRepeatedFieldValue(
    AddressField field) const {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kVectorStringField));
  assert(kVectorStringField[field] != NULL);
  return this->*kVectorStringField[field];
}

// static
bool AddressData::IsRepeatedFieldValue(AddressField field) {
  return field == STREET_ADDRESS;
}

}  // namespace addressinput
}  // namespace i18n
<commit_msg>Remove hardcoded STREET_ADDRESS in AddressData::IsRepeatedFieldValue().<commit_after>// Copyright (C) 2014 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <libaddressinput/address_data.h>

#include <libaddressinput/address_field.h>
#include <libaddressinput/util/basictypes.h>

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <string>
#include <vector>

#include <re2/re2.h>

namespace i18n {
namespace addressinput {

namespace {

// Mapping from AddressField value to pointer to AddressData member.
std::string AddressData::*kStringField[] = {
  &AddressData::region_code,
  &AddressData::administrative_area,
  &AddressData::locality,
  &AddressData::dependent_locality,
  &AddressData::sorting_code,
  &AddressData::postal_code,
  NULL,
  &AddressData::recipient
};

// Mapping from AddressField value to pointer to AddressData member.
const std::vector<std::string> AddressData::*kVectorStringField[] = {
  NULL,
  NULL,
  NULL,
  NULL,
  NULL,
  NULL,
  &AddressData::address_line,
  NULL
};

COMPILE_ASSERT(arraysize(kStringField) == arraysize(kVectorStringField),
               field_mapping_array_size_mismatch);

// A string is considered to be "empty" not only if it actually is empty, but
// also if it contains nothing but whitespace.
bool IsStringEmpty(const std::string& str) {
  static const RE2 kMatcher("\\S");
  return str.empty() || !RE2::PartialMatch(str, kMatcher);
}

}  // namespace

bool AddressData::IsFieldEmpty(AddressField field) const {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kStringField));
  if (kStringField[field] != NULL) {
    const std::string& value = GetFieldValue(field);
    return IsStringEmpty(value);
  } else {
    const std::vector<std::string>& value = GetRepeatedFieldValue(field);
    return std::find_if(value.begin(), value.end(),
                        std::not1(std::ptr_fun(&IsStringEmpty))) ==
           value.end();
  }
}

const std::string& AddressData::GetFieldValue(
    AddressField field) const {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kStringField));
  assert(kStringField[field] != NULL);
  return this->*kStringField[field];
}

void AddressData::SetFieldValue(AddressField field, const std::string& value) {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kStringField));
  assert(kStringField[field] != NULL);
  (this->*kStringField[field]).assign(value);
}

const std::vector<std::string>& AddressData::GetRepeatedFieldValue(
    AddressField field) const {
  assert(IsRepeatedFieldValue(field));
  return this->*kVectorStringField[field];
}

// static
bool AddressData::IsRepeatedFieldValue(AddressField field) {
  assert(field >= 0);
  assert(static_cast<size_t>(field) < arraysize(kVectorStringField));
  return kVectorStringField[field] != NULL;
}

}  // namespace addressinput
}  // namespace i18n
<|endoftext|>


<commit_before>/*
 * File:   hardcodetest.cpp
 * Author: Isaac Yochelson
 *
 * Created on August 11, 2013, 2:00 PM
 */
#include <moveit/move_group_interface/move_group.h>
#include <moveit_msgs/RobotTrajectory.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <trajectory_msgs/MultiDOFJointTrajectory.h>
#include <geometry_msgs/Pose.h>
#include <cstdlib>			//standard library for C/C++
#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>

using namespace std;

void moveToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose);
void pick (int cup, move_group_interface::MoveGroup& group, string joint);
void place (int cup, move_group_interface::MoveGroup& group, string joint);

int main(int argc, char** argv)
{
	ros::init(argc, argv, "Test_Node");
	// start a ROS spinning thread
	ros::AsyncSpinner spinner(1);
	spinner.start();
	// this connecs to a running instance of the move_group node
	move_group_interface::MoveGroup leftGroup("left_arm");
	move_group_interface::MoveGroup rightGroup("right_arm");
	leftGroup.setPlannerId("PRMstarkConfigDefault");
	leftGroup.setStartStateToCurrentState();
	rightGroup.setPlannerId("PRMstarkConfigDefault");
	rightGroup.setStartStateToCurrentState();
	ROS_INFO("setting target");
	geometry_msgs::Pose* pose = new geometry_msgs::Pose;
	pose->position.x = 0.2;
	pose->position.y = 0.4;
	pose->position.z = 0.3;
	pose->orientation.x = 0;
	pose->orientation.y = 1;
	pose->orientation.z = 0;
	pose->orientation.w = 0;
	moveToPose("right_wrist", rightGroup, pose);
	/*
	for (int ct = 1; ct < 5; ++ct) {
		pick(ct, leftGroup, "left_wrist");
		place(0, leftGroup, "left_wrist");
		pick(-ct, rightGroup, "right_wrist");
		place(0, rightGroup, "right_wrist");
	}
	pick(-5, rightGroup, "right_wrist");
	place(0, rightGroup, "right_wrist");
	pick(0, leftGroup, "left_wrist");
	place(5, leftGroup, "left_wrist");
	pick(4, leftGroup, "left_wrist");
	place(0, leftGroup, "left_wrist");
	pick(0, rightGroup, "right_wrist");
	place(-1, rightGroup, "right_wrist");
	pick(-4, rightGroup, "right_wrist");
	place(0, rightGroup, "right_wrist");
	pick(0, leftGroup, "left_wrist");
	place(1, leftGroup, "left_wrist");
	pick(3, leftGroup, "left_wrist");
	place(0, leftGroup, "left_wrist");
	pick(0, rightGroup, "right_wrist");
	place(-2, rightGroup, "right_wrist");
	pick(-3, rightGroup, "right_wrist");
	place(0, rightGroup, "right_wrist");
	pick(0, leftGroup, "left_wrist");
	place(2, leftGroup, "left_wrist");
	*/
	return 0;
}
void pick (int cup, move_group_interface::MoveGroup& group, string joint) {
	string arm;
	if (joint == "left_wrist") {
		arm = "left";
	} else {
		arm = "right";
	}
	geometry_msgs::Pose* pose = new geometry_msgs::Pose;
	pose->position.x = 0.83;
	pose->position.y = 0.104 * cup;
	pose->position.z = 0.35;
	pose->orientation.x = 0;
	pose->orientation.y = 1;
	pose->orientation.z = 0;
	pose->orientation.w = 0;
	moveToPose(joint, group, pose);
	pose->position.z = 0.135;
	moveToPose(joint, group, pose);
	stringstream ss;
	ss << "python /home/pracsys/workspaces/hydro_ws/src/drogon_interface/src/gripper.py close " << arm;
	system(ss.str().c_str());
	pose->position.z = 0.35;
	moveToPose(joint, group, pose);
}
void place (int cup, move_group_interface::MoveGroup& group, string joint) {
	string arm;
	if (joint == "left_wrist") {
		arm = "left";
	} else {
		arm = "right";
	}
	geometry_msgs::Pose* pose = new geometry_msgs::Pose;
	pose->position.x = 0.83;
	pose->position.y = 0.104 * cup;
	pose->position.z = 0.35;
	pose->orientation.x = 0;
	pose->orientation.y = 1;
	pose->orientation.z = 0;
	pose->orientation.w = 0;
	moveToPose(joint, group, pose);
	pose ->position.z = 0.20;
	moveToPose(joint, group, pose);
	stringstream ss;
	ss << "python /home/pracsys/workspaces/hydro_ws/src/drogon_interface/src/gripper.py open " << arm;
	system(ss.str().c_str());
	pose->position.z = 0.35;
	moveToPose(joint, group, pose);
	if (arm == "left") {
		pose->position.y = 0.25;
	} else {
		pose->position.y = -0.25;
	}
	moveToPose(joint, group, pose);
}
void moveToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose) {
	bool gotPlan;
	moveit::planning_interface::MoveGroup::Plan plan;
	group.setPoseTarget(*pose, joint);
	ROS_INFO("requesting plan.");
	gotPlan = group.plan(plan);
	if (gotPlan) {
		ROS_INFO("plan received.");
		cout << plan.trajectory_ << endl;
		group.execute(plan);
		ROS_INFO("plan execution completed.");
	}
}
<commit_msg>fixed hardcodetest for moved gripper.py<commit_after>/*
 * File:   hardcodetest.cpp
 * Author: Isaac Yochelson
 *
 * Created on August 11, 2013, 2:00 PM
 */
#include <moveit/move_group_interface/move_group.h>
#include <moveit_msgs/RobotTrajectory.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <trajectory_msgs/MultiDOFJointTrajectory.h>
#include <geometry_msgs/Pose.h>
#include <cstdlib>			//standard library for C/C++
#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>

using namespace std;

void moveToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose);
void pick (int cup, move_group_interface::MoveGroup& group, string joint);
void place (int cup, move_group_interface::MoveGroup& group, string joint);

int main(int argc, char** argv)
{
	ros::init(argc, argv, "Test_Node");
	// start a ROS spinning thread
	ros::AsyncSpinner spinner(1);
	spinner.start();
	// this connecs to a running instance of the move_group node
	move_group_interface::MoveGroup leftGroup("left_arm");
	move_group_interface::MoveGroup rightGroup("right_arm");
	leftGroup.setPlannerId("PRMstarkConfigDefault");
	leftGroup.setStartStateToCurrentState();
	rightGroup.setPlannerId("PRMstarkConfigDefault");
	rightGroup.setStartStateToCurrentState();
	ROS_INFO("setting target");
	geometry_msgs::Pose* pose = new geometry_msgs::Pose;
	pose->position.x = 0.2;
	pose->position.y = 0.4;
	pose->position.z = 0.3;
	pose->orientation.x = 0;
	pose->orientation.y = 1;
	pose->orientation.z = 0;
	pose->orientation.w = 0;
	moveToPose("right_wrist", rightGroup, pose);
	for (int ct = 1; ct < 5; ++ct) {
		pick(ct, leftGroup, "left_wrist");
		place(0, leftGroup, "left_wrist");
		pick(-ct, rightGroup, "right_wrist");
		place(0, rightGroup, "right_wrist");
	}/*
	pick(-5, rightGroup, "right_wrist");
	place(0, rightGroup, "right_wrist");
	pick(0, leftGroup, "left_wrist");
	place(5, leftGroup, "left_wrist");
	pick(4, leftGroup, "left_wrist");
	place(0, leftGroup, "left_wrist");
	pick(0, rightGroup, "right_wrist");
	place(-1, rightGroup, "right_wrist");
	pick(-4, rightGroup, "right_wrist");
	place(0, rightGroup, "right_wrist");
	pick(0, leftGroup, "left_wrist");
	place(1, leftGroup, "left_wrist");
	pick(3, leftGroup, "left_wrist");
	place(0, leftGroup, "left_wrist");
	pick(0, rightGroup, "right_wrist");
	place(-2, rightGroup, "right_wrist");
	pick(-3, rightGroup, "right_wrist");
	place(0, rightGroup, "right_wrist");
	pick(0, leftGroup, "left_wrist");
	place(2, leftGroup, "left_wrist");
	*/
	return 0;
}
void pick (int cup, move_group_interface::MoveGroup& group, string joint) {
	string arm;
	if (joint == "left_wrist") {
		arm = "left";
	} else {
		arm = "right";
	}
	geometry_msgs::Pose* pose = new geometry_msgs::Pose;
	pose->position.x = 0.83;
	pose->position.y = 0.104 * cup;
	pose->position.z = 0.35;
	pose->orientation.x = 0;
	pose->orientation.y = 1;
	pose->orientation.z = 0;
	pose->orientation.w = 0;
	moveToPose(joint, group, pose);
	pose->position.z = 0.135;
	moveToPose(joint, group, pose);
	moveToPose(joint, group, pose);
	stringstream ss;
	ss << "python /home/pracsys/workspaces/hydro_ws/src/drogon_interface/scripts/gripper.py close " << arm;
	system(ss.str().c_str());
	pose->position.z = 0.35;
	moveToPose(joint, group, pose);
}
void place (int cup, move_group_interface::MoveGroup& group, string joint) {
	string arm;
	if (joint == "left_wrist") {
		arm = "left";
	} else {
		arm = "right";
	}
	geometry_msgs::Pose* pose = new geometry_msgs::Pose;
	pose->position.x = 0.83;
	pose->position.y = 0.104 * cup;
	pose->position.z = 0.35;
	pose->orientation.x = 0;
	pose->orientation.y = 1;
	pose->orientation.z = 0;
	pose->orientation.w = 0;
	moveToPose(joint, group, pose);
	pose ->position.z = 0.20;
	moveToPose(joint, group, pose);
	stringstream ss;
	ss << "python /home/pracsys/workspaces/hydro_ws/src/drogon_interface/scripts/gripper.py open " << arm;
	system(ss.str().c_str());
	pose->position.z = 0.35;
	moveToPose(joint, group, pose);
	if (arm == "left") {
		pose->position.y = 0.25;
	} else {
		pose->position.y = -0.25;
	}
	moveToPose(joint, group, pose);
}
void moveToPose(string joint, move_group_interface::MoveGroup& group, geometry_msgs::Pose* pose) {
	bool gotPlan;
	moveit::planning_interface::MoveGroup::Plan plan;
	group.setPoseTarget(*pose, joint);
	ROS_INFO("requesting plan.");
	gotPlan = group.plan(plan);
	if (gotPlan) {
		ROS_INFO("plan received.");
		cout << plan.trajectory_ << endl;
		group.execute(plan);
		ROS_INFO("plan execution completed.");
	}
}
<|endoftext|>